Example usage for javax.tools Diagnostic getEndPosition

List of usage examples for javax.tools Diagnostic getEndPosition

Introduction

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

Prototype

long getEndPosition();

Source Link

Document

Returns the character offset from the beginning of the file associated with this diagnostic that indicates the end of the problem.

Usage

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  . java2  s  . c om

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

From source file:org.kantega.dogmaticmvc.java.JavaScriptCompiler.java

@Override
public Class compile(HttpServletRequest request) {

    String className = request.getServletPath().substring(1).replace('/', '.');

    List<JavaFileObject> compilationUnits = new ArrayList<JavaFileObject>();
    for (String path : (Set<String>) servletContext.getResourcePaths("/WEB-INF/dogmatic/")) {
        if (path.endsWith("java")) {
            try {
                String classNAme = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                compilationUnits.add(new JavaSourceFromURL(classNAme, servletContext.getResource(path)));
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }//from   w w  w .j  ava  2s .  co m
        }
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(
            compiler.getStandardFileManager(null, null, null),
            new ClassLoaderImpl(getClass().getClassLoader()));

    String cp = "";
    for (ClassLoader cl : Arrays.asList(getClass().getClassLoader(), getClass().getClassLoader().getParent())) {
        if (cl instanceof URLClassLoader) {
            URLClassLoader ucl = (URLClassLoader) cl;

            for (URL url : ucl.getURLs()) {
                if (cp.length() > 0) {
                    cp += File.pathSeparator;
                }
                cp += url.getFile();
            }
        }
    }
    List<String> options = new ArrayList(Arrays.asList("-classpath", cp));

    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
            compilationUnits);

    boolean success = task.call();
    StringWriter sw = new StringWriter();
    PrintWriter w = new PrintWriter(sw);

    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        w.println(diagnostic.getCode());
        w.println(diagnostic.getKind());
        w.println(diagnostic.getPosition());
        w.println(diagnostic.getStartPosition());
        w.println(diagnostic.getEndPosition());
        w.println(diagnostic.getSource());
        w.println(diagnostic.getMessage(null));

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

    if (success) {
        try {
            return fileManager.getClassLoader(null).loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("Compilation failed: " + sw);
    }
}

From source file:rita.compiler.CompileString.java

/**
 * El mtodo compile crea el archivo compilado a partir de un codigo fuente
 * y lo deja en un directorio determinado
 * /*from www  .j a  va2  s .c  o m*/
 * @param sourceCode
 *            el codigo fuente
 * @param className
 *            el nombre que debera llevar la clase
 * @param packageName
 *            nombre del paquete
 * @param outputDirectory
 *            directorio donde dejar el archivo compilado
 * */
public static final Collection<File> compile(File sourceCode, File outputDirectory) throws Exception {
    diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>();
    JavaCompiler compiler = new EclipseCompiler();

    System.out.println(sourceCode);

    DiagnosticListener<JavaFileObject> listener = new DiagnosticListener<JavaFileObject>() {
        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            if (diagnostic.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) {
                System.err.println("=======================ERROR==========================");
                System.err.println("Tipo: " + diagnostic.getKind());
                System.err.println("mensaje: " + diagnostic.getMessage(Locale.ENGLISH));
                System.err.println("linea: " + diagnostic.getLineNumber());
                System.err.println("columna: " + diagnostic.getColumnNumber());
                System.err.println("CODE: " + diagnostic.getCode());
                System.err.println(
                        "posicion: de " + diagnostic.getStartPosition() + " a " + diagnostic.getEndPosition());
                System.err.println(diagnostic.getSource());
                diagnostics.add(diagnostic);
            }
        }

    };

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    /* guardar los .class y  directorios (packages) en un directorio separado; de esta manera
     * si se genera mas de 1 clase (porque p.ej. hay inner classes en el codigo) podemos identificar
     * a todas las clases resultantes de esta compilacion
     */
    File tempOutput = createTempDirectory();
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempOutput));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceCode);
    try {
        if (compiler.getTask(null, fileManager, listener, null, null, compilationUnits).call()) {
            // copiar .class y  directorios (packages) generados por el compilador en tempOutput al directorio final
            FileUtils.copyDirectory(tempOutput, outputDirectory);
            // a partir de los paths de los archivos .class generados en el dir temp, modificarlos para que sean relativos a outputDirectory
            Collection<File> compilationResults = new ArrayList<File>();
            final int tempPrefix = tempOutput.getAbsolutePath().length();
            for (File classFile : FileUtils.listFiles(tempOutput, new SuffixFileFilter(".class"),
                    TrueFileFilter.INSTANCE)) {
                compilationResults
                        .add(new File(outputDirectory, classFile.getAbsolutePath().substring(tempPrefix)));
            }
            // retornar los paths de todos los .class generados
            return compilationResults;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error al realizar el compilado");
    } finally {
        FileUtils.deleteDirectory(tempOutput);
        fileManager.close();
    }
    return null;
}