Example usage for javax.tools Diagnostic getSource

List of usage examples for javax.tools Diagnostic getSource

Introduction

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

Prototype

S getSource();

Source Link

Document

Returns the source object associated with this diagnostic.

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  ww. j  a v  a 2  s. co 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  w w  .  j  a v a 2s  . c  o  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);/*from   ww w . j  a va 2 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();//from  w  w  w . j ava 2 s  .  c o  m
    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:Main.java

private static String errorsToString(DiagnosticCollector<JavaFileObject> diagnosticCollector) {
    StringBuilder builder = new StringBuilder();
    for (javax.tools.Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
        if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
            builder.append(diagnostic.getSource().getName()).append(":").append(diagnostic.getLineNumber())
                    .append(":").append(diagnostic.getColumnNumber()).append(":").append(diagnostic.getCode())
                    .append("\n");
        }/*  w  ww .  j av a 2s .  c  o  m*/
    }
    return builder.toString();
}

From source file:com.joliciel.talismane.utils.compiler.DynamicCompilerTest.java

@Test
public void testCompileError() throws Exception {
    ClassLoader classLoader = this.getClass().getClassLoader();
    DiagnositicsLogger diagnosticsLogger = new DiagnositicsLogger();

    DynamicCompiler compiler = new DynamicCompiler(classLoader, diagnosticsLogger);

    String src = "package com.joliciel.talismane.utils.compiler.foo;\n"
            + "import com.joliciel.talismane.utils.compiler.DynamicCompilerTest.HelloInterface;\n"
            + "public class Foo implements HelloInterface {\n" + "        public String hello(String who) {\n"
            + "            return \"Hello \" + who\n" + "        }\n" + "    }";

    String fullName = "com.joliciel.talismane.utils.compiler.foo.Foo";

    try {/*from ww  w . j  a  v a 2  s.  c  om*/
        compiler.compile(fullName, src, null);
        fail("Expected exception");
    } catch (DynamicCompilerException e) {
        LOG.debug(e.getMessage());
    }

    Diagnostic<? extends JavaFileObject> diagnostic = diagnosticsLogger.getDiagnostics().get(0);
    assertEquals(5, diagnostic.getLineNumber());
    assertEquals("compiler.err.expected", diagnostic.getCode());
    assertEquals("Foo.java", diagnostic.getSource().getName());
}

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 a2  s  .  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.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 . java 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 ww .  j  a  va2 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) + "";
    }//from ww w. j a v a 2  s.  c  o m
    diagnosticBuilder.append(diagnostic.getMessage(null));
    diagnosticBuilder.append("\n");
    diagnosticBuilder.append(sourceErrorDetails);
    return diagnostic.getKind().equals(Diagnostic.Kind.ERROR);
}