Example usage for javax.tools Diagnostic toString

List of usage examples for javax.tools Diagnostic toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.glowroot.common2.repo.util.Compilations.java

public static Class<?> compile(String source) throws Exception {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();

    IsolatedClassLoader isolatedClassLoader = new IsolatedClassLoader();

    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(diagnosticCollector,
            Locale.ENGLISH, UTF_8);
    standardFileManager.setLocation(StandardLocation.CLASS_PATH, getCompilationClassPath());
    JavaFileManager fileManager = new IsolatedJavaFileManager(standardFileManager, isolatedClassLoader);
    try {// www.j a  v a 2s .  co m
        List<JavaFileObject> compilationUnits = Lists.newArrayList();

        String className = getPublicClassName(source);
        int index = className.lastIndexOf('.');
        String simpleName;
        if (index == -1) {
            simpleName = className;
        } else {
            simpleName = className.substring(index + 1);
        }
        compilationUnits.add(new SourceJavaFileObject(simpleName, source));

        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnosticCollector, null,
                null, compilationUnits);
        task.call();

        List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
        if (!diagnostics.isEmpty()) {
            List<String> compilationErrors = Lists.newArrayList();
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
                compilationErrors.add(checkNotNull(diagnostic.toString()));
            }
            throw new CompilationException(compilationErrors);
        }
        if (className.isEmpty()) {
            throw new CompilationException(ImmutableList.of("Class must be public"));
        }
        return isolatedClassLoader.loadClass(className);
    } finally {
        fileManager.close();
    }
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder,
        GeneratorContext context) {/* w  w  w .  j  a  v a 2 s .co  m*/
    StandardJavaFileManager fileManager = null;
    boolean success = true;
    try {
        List<String> compilerFiles = GeneratorUtil.getFiles(srcFolder, new String[] { "java" });

        GeneratorUtil.createOutputDir(destFolder);

        List<String> options = new ArrayList<String>();
        options.add("-classpath");
        String classPathStr = GeneratorUtil.getFiles(libFolder, new String[] { "jar" }, File.pathSeparator);

        options.add(classPathStr);
        options.add("-nowarn");
        options.add("-Xlint:-unchecked");
        options.add("-d");
        options.add(destFolder);

        options.add("-s");
        options.add(srcFolder);

        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);
        success = task.call();

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            //context.getLogger().error(diagnostic.getCode());
            //context.getLogger().error(diagnostic.getKind().toString());
            //context.getLogger().error(diagnostic.getPosition() + "");
            //context.getLogger().error(diagnostic.getStartPosition() + "");
            //context.getLogger().error(diagnostic.getEndPosition() + "");
            //context.getLogger().error(diagnostic.getSource().toString());
            context.getLogger().error(diagnostic.toString());
        }
    } catch (Throwable t) {
        context.getLogger().error("Error compiling java code", t);
    } finally {
        try {
            fileManager.close();
        } catch (Throwable t) {
        }
    }
    return success;
}

From source file:de.monticore.codegen.GeneratorTest.java

/**
 * Compiles the files in the given directory, printing errors to the console
 * if any occur./*from   w ww .  j a v a2  s  .  c om*/
 * 
 * @param sourceCodePath the source directory to be compiled
 * @return true if the compilation succeeded
 */
protected boolean compile(Path sourceCodePath) {
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    boolean compilationSuccess = false;
    Optional<CompilationTask> task = setupCompilation(sourceCodePath, diagnostics);
    if (!task.isPresent()) {
        return compilationSuccess;
    }
    compilationSuccess = task.get().call();
    if (!compilationSuccess) {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            Log.error(diagnostic.toString());
        }
    }
    return compilationSuccess;
}

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

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

private static Class<?> compileClassJavac(String name, String src) {
    try {//ww w. j  a va2  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.javascool.compiler.Main.java

/**
 * Fonction pricipale du programme.//from   w w  w  . ja v a  2 s.  c  o  m
 *
 * @param args Les arguments de l'application.
 */
public static void main(String... args) {
    try {
        parseArguments(args);
        if (getCommandLine().hasOption('h')
                || (!getCommandLine().hasOption("src") || getCommandLine().getOptionValue("src").isEmpty())) {
            if (!getCommandLine().hasOption("src") || getCommandLine().getOptionValue("src").isEmpty())
                System.err.println("Aucun fichier source  compiler");
            printHelpMessage();
            return;
        }

        File jvsFile = new File("C:\\Users\\PhilippeGeek\\IdeaProjects\\Javascool-Compiler\\test.jvs");
        ProgletCodeCompiler codeCompiler = new ProgletCodeCompiler(ProgletCodeCompiler.DEFAULT_PROGLET,
                jvsFile);
        ArrayList<Diagnostic<? extends JavaFileObject>> result = codeCompiler.compile();
        for (Diagnostic<? extends JavaFileObject> error : result) {
            System.out.println("Erreur : " + error.toString());
        }
        if (result.size() == 0)
            codeCompiler.getCompiledRunnable().run();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}