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:Main.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager sjfm = compiler.getStandardFileManager(dc, null, null);
    Iterable<? extends JavaFileObject> fileObjects = sjfm.getJavaFileObjects(args);
    compiler.getTask(null, sjfm, dc, null, null, fileObjects).call();
    for (Diagnostic d : dc.getDiagnostics()) {
        System.out.println(d.getMessage(null));
        System.out.printf("Line number = %d\n", d.getLineNumber());
        System.out.printf("File = %s\n", d.getSource());
    }/*  w  w  w .  ja v a 2  s.  c o m*/
}

From source file:CompileFiles2.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> dc;
    dc = new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager sjfm;
    sjfm = compiler.getStandardFileManager(dc, null, null);

    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = sjfm.getJavaFileObjects(args);

    compiler.getTask(null, sjfm, dc, null, null, fileObjects).call();

    for (Diagnostic d : dc.getDiagnostics()) {
        System.out.println(d.getMessage(null));
        System.out.printf("Line number = %d\n", d.getLineNumber());
        System.out.printf("File = %s\n", d.getSource());
    }/*from   w  ww. ja va 2 s.  co  m*/
}

From source file:Main.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromStrings(Arrays.asList("YourFile.java"));
    Iterable<String> options = Arrays.asList("-d", "classes", "-sourcepath", "src");
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
            compilationUnits);/* w w w.  j a v  a2  s. co  m*/

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));
    }
    fileManager.close();
    System.out.println("Success: " + success);
}

From source file:CompileSourceInMemory.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();//www . j  a v  a 2  s  .com
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null,
                    new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}

From source file:de.alpharogroup.runtime.compiler.CompilerExtensions.java

/**
 * Generate a compilation stacktrace from the given parameter.
 *
 * @param diagnosticCollectors/*w  ww.  ja va 2s .  c o m*/
 *            the diagnostic collectors
 * @return the generated stacktrace string.
 */
public static String generateCompilationStacktrace(
        final DiagnosticCollector<JavaFileObject> diagnosticCollectors) {
    final StringBuilder sb = new StringBuilder();
    for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollectors.getDiagnostics()) {
        sb.append(diagnostic.getMessage(null));
        sb.append(SeparatorConstants.SEMI_COLON_WHITE_SPACE);
    }
    return sb.toString();
}

From source file:io.proscript.jlight.Runtime.java

public static void run(CommandLine line) throws IOException {

    Environment environment = new Environment();

    if (1 == line.getArgList().size()) {
        File cwdCandidate = new File(line.getArgList().get(0));
        if (cwdCandidate.isDirectory()) {
            environment.setCwd(cwdCandidate);
        } else {/*from   ww  w  .java  2 s . c om*/
            throw new IOException("Last argument must be valid source root directory");
        }
    } else {
        environment.setCwd(new File(System.getProperty("user.dir")));
    }

    if (line.hasOption("port")) {
        environment.setPort(Integer.valueOf(line.getOptionValue("port")));
    }

    if (line.hasOption("host")) {
        environment.setHost(line.getOptionValue("host"));
    }

    environment.setCacheDirectory(new File(environment.getCwd().toString() + "/.jlcache"));
    environment.setMainClassName(line.getOptionValue("class"));

    CacheManager cacheManager = new CacheManager(environment);

    try {
        cacheManager.initialize();
    } catch (IOException e) {
        log.log(Level.SEVERE, "Failed to initialize class file cache: %s", e.getMessage());
        return;
    }

    Collection<File> javaFiles = SourcesLocator.locateRecursive(environment.getCwd());

    ApplicationCompiler compiler = new ApplicationCompiler(environment.getCacheDirectory());

    boolean result = false;

    try {
        result = compiler.compile(javaFiles);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Compilation failed: %s", e.getMessage());
        return;
    }

    if (!result) {
        for (Diagnostic diagnostic : compiler.getLastDiagnosticCollector().getDiagnostics()) {
            System.out.println(diagnostic.getMessage(Locale.getDefault()));
            LogRecord record = new LogRecord(Level.SEVERE, diagnostic.getMessage(Locale.getDefault()));
            log.log(record);
        }
    } else {

        Application application = buildApplication(environment);
        ThreadedHTTPServer server = new ThreadedHTTPServer(environment);
        server.run(application);
    }

    try {
        cacheManager.destroy();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

private static void assertNotContains(List<Diagnostic<? extends JavaFileObject>> diagnostics, Kind kind,
        String errorMessage) {//w  w  w  .  j a va  2s  . co m
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        assertFalse(String.format("%s, found on line %d: %s", errorMessage, diagnostic.getLineNumber(),
                diagnostic.getMessage(Locale.getDefault())), diagnostic.getKind().equals(kind));
    }
}

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

/**
 * compile given String source and return bytecodes as a Map.
 * // ww w  .  java  2 s . c  o m
 * @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:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java

boolean isValidExpression() {
    try {/* www. j a  v  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.sillelien.dollar.DocTestingVisitor.java

@Override
public void visit(@NotNull VerbatimNode node) {
    if ("java".equals(node.getType())) {
        try {//w ww .ja va 2  s  .c o m
            String name = "DocTemp" + System.currentTimeMillis();
            File javaFile = new File("/tmp/" + name + ".java");
            File clazzFile = new File("/tmp/" + name + ".class");
            clazzFile.getParentFile().mkdirs();
            FileUtils.write(javaFile,
                    "import com.sillelien.dollar.api.*;\n"
                            + "import static com.sillelien.dollar.api.DollarStatic.*;\n" + "public class "
                            + name + " implements java.lang.Runnable{\n" + "    public void run() {\n"
                            + "        " + node.getText() + "\n" + "    }\n" + "}");
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            final StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null);
            JavaCompiler.CompilationTask task;
            DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() {

                @Override
                public void report(Diagnostic diagnostic) {
                    System.out.println(diagnostic);
                    throw new RuntimeException(diagnostic.getMessage(Locale.getDefault()));
                }
            };

            try (FileOutputStream fileOutputStream = FileUtils.openOutputStream(clazzFile)) {
                task = javac.getTask(new OutputStreamWriter(fileOutputStream), jfm, diagnosticListener, null,
                        null, jfm.getJavaFileObjects(javaFile));
            }
            task.call();

            try {
                // Convert File to a URL
                URL url = clazzFile.getParentFile().toURL();
                URL[] urls = new URL[] { url };
                ClassLoader cl = new URLClassLoader(urls);
                Class cls = cl.loadClass(name);
                ((Runnable) cls.newInstance()).run();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            System.out.println("Parsed: " + node.getText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}