Example usage for javax.tools DiagnosticCollector DiagnosticCollector

List of usage examples for javax.tools DiagnosticCollector DiagnosticCollector

Introduction

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

Prototype

DiagnosticCollector

Source Link

Usage

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

private static Class<?> compileClassJavac(String name, String src) {
    try {//from  w ww .  j a v a 2  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.auroraide.server.jci.compilers.Jsr199JavaCompiler.java

public CompilationResult compile(final String[] pResourcePaths, final ResourceReader pReader,
        final ResourceStore pStore, final ClassLoader classLoader, JavaCompilerSettings settings) {

    final Collection<JavaFileObject> units = new ArrayList<JavaFileObject>();
    for (int i = 0; i < pResourcePaths.length; i++) {
        final String sourcePath = pResourcePaths[i];
        log.debug("compiling " + sourcePath);
        final String source = pResourcePaths[i];
        if (pReader.isAvailable(source))
            units.add(new CompilationUnit(sourcePath, pReader));
    }/*from w w w . j  a  va  2  s. c  o  m*/

    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    final JavaFileManager fileManager = new JciJavaFileManager(units, pStore);
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    // final JavaFileManager fileManager1 =
    // compiler.getStandardFileManager(null,null,null);

    System.getProperties();

    compiler.getTask(null, fileManager, diagnostics, options, null, units).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final List<Diagnostic<? extends JavaFileObject>> jsrProblems = diagnostics.getDiagnostics();
    final CompilationProblem[] problems = new CompilationProblem[jsrProblems.size()];
    int i = 0;
    for (final Diagnostic<? extends JavaFileObject> jsrProblem : jsrProblems) {
        problems[i++] = new Jsr199CompilationProblem(jsrProblem);

        if (problemHandler != null) {
            problemHandler.handle(problems[i - 1]);
        }
    }

    return new CompilationResult(problems);
}

From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java

/**
 * F2 test.//from  w  w  w  . j  a v a  2s. co m
 * 
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 */
@Test
public void f2Test()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.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...
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar");

    File helloWorldJava = new File(System.getProperty("user.dir")
            + "/generated-code/caserunners/org/bigtester/ate/model/project/CaseRunner8187856223134148550.java");

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);
    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        System.out.println("Yipe");
        // 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!
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() });
        // Load the class from the classloader by name....
        Class<?> loadedClass = classLoader
                .loadClass("org.bigtester.ate.model.project.CaseRunner8187856223134148550");
        // Create a new instance...
        Object obj = loadedClass.newInstance();
        // Santity check
        if (obj instanceof IRunTestCase) {
            ((IRunTestCase) obj).setCurrentExecutingTCName("test case name example");
            Assert.assertEquals(((IRunTestCase) obj).getCurrentExecutingTCName(), "test case name example");
            System.out.println("pass");
        }
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(),
                    diagnostic.getSource().toUri());
        }
    }
}

From source file:org.commonjava.test.compile.CompilerFixture.java

public CompilerResult compile(final File directory, final CompilerFixtureConfig config) throws IOException {
    if (directory == null || !directory.isDirectory()) {
        return null;
    }/*from  w  ww.  j  ava2  s. c om*/

    final File target = temp.newFolder(directory.getName() + "-classes");

    final List<File> sources = scan(directory, "**/*.java");

    final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    final Set<JavaFileObject> objects = new HashSet<>();

    for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(sources)) {
        objects.add(jfo);
    }

    final DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();

    final List<String> options = new ArrayList<>(Arrays.asList("-g", "-d", target.getCanonicalPath()));

    options.addAll(config.getExtraOptions());

    final StringBuilder sp = new StringBuilder();
    sp.append(directory.getCanonicalPath()).append(';').append(target.getCanonicalPath());

    File generatedSourceDir = null;

    final List<String> procOptions = new ArrayList<>(options);
    procOptions.add("-proc:only");

    final Set<File> seenSources = new HashSet<>(sources);
    Boolean result = Boolean.TRUE;

    final List<Class<? extends AbstractProcessor>> annoProcessors = config.getAnnotationProcessors();
    if (!annoProcessors.isEmpty()) {
        final StringBuilder sb = new StringBuilder();
        for (final Class<? extends AbstractProcessor> annoProcessor : annoProcessors) {
            if (sb.length() > 0) {
                sb.append(",");
            }

            sb.append(annoProcessor.getCanonicalName());
        }

        procOptions.add("-processor");
        procOptions.add(sb.toString());

        generatedSourceDir = temp.newFolder(directory.getName() + "-generated-sources");
        procOptions.add("-s");
        procOptions.add(generatedSourceDir.getCanonicalPath());

        sp.append(';').append(generatedSourceDir.getCanonicalPath());

        procOptions.add("-sourcepath");
        procOptions.add(sp.toString());

        int pass = 1;
        List<File> nextSources;
        do {
            logger.debug("pass: {} Compiling/processing generated sources with: '{}':\n  {}\n", pass,
                    new JoinLogString(procOptions, ", "), new JoinLogString(sources, "\n  "));

            for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
                objects.add(jfo);
            }

            final CompilationTask task = javac.getTask(null, fileManager, diags, procOptions, null, objects);
            result = task.call();

            nextSources = scan(generatedSourceDir, "**/*.java");

            logger.debug("\n\nNewly scanned sources:\n  {}\n\nPreviously seen sources:\n  {}\n\n",
                    new JoinLogString(nextSources, "\n  "), new JoinLogString(seenSources, "\n  "));
            nextSources.removeAll(seenSources);
            seenSources.addAll(nextSources);
            pass++;
        } while (pass < config.getMaxAnnotationProcessorPasses() && !nextSources.isEmpty());
    }

    if (result) {
        options.add("-sourcepath");
        options.add(sp.toString());

        options.add("-proc:none");

        for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
            objects.add(jfo);
        }

        final CompilationTask task = javac.getTask(null, fileManager, diags, options, null, objects);
        result = task.call();

        logger.debug("Compiled classes:\n  {}\n\n", new JoinLogString(scan(target, "**/*.class"), "\n  "));
    } else {
        logger.warn("Annotation processing must have failed. Skipping compilation step.");
    }

    for (final Diagnostic<? extends JavaFileObject> diag : diags.getDiagnostics()) {
        logger.error(String.valueOf(diag));
    }

    final CompilerResult cr = new CompilerResultBuilder().withClasses(target).withDiagnosticCollector(diags)
            .withGeneratedSources(generatedSourceDir).withResult(result).build();

    results.add(cr);
    return cr;
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Compila el java en tiempo real//from  w  ww.ja va  2s. com
 *
 * @return xito de la operacin
 */
protected boolean compileEDMCrossWalk() {
    boolean status = false;

    SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(canonicalCrosswalkName,
            edmCrossWalkContent);
    JavaFileObject javaFileObjects[] = new JavaFileObject[] { fileObject };

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

    // libreras necesarias para linkar con el fuente a compilar
    String myInstallerPackagesDirPath = myInstallerDirPath + fileSeparator + "packages" + fileSeparator;
    StringBuilder jars = (fileSeparator.equals("\\"))
            ? new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar;")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar;")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar")
            : new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar:")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar:")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar");

    String[] compileOptions = new String[] { "-d", myInstallerWorkDirPath, "-source", "1.6", "-target", "1.6",
            "-cp", jars.toString() };
    Iterable<String> compilationOptionss = Arrays.asList(compileOptions);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);

    JavaCompiler.CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics,
            compilationOptionss, null, compilationUnits);

    status = compilerTask.call();

    if (!status) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            installerEDMDisplay
                    .showMessage("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic);
        }
    }

    try {
        stdFileManager.close();
    } catch (IOException e) {
        showException(e);
    }
    return status;
}

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

private static boolean compileJavaFile(String javaBinDirName, File javaFile) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        return false; //fail
    }//from  w  w  w  .  ja  v a  2 s .co m

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.getDefault(),
            Charset.forName("UTF-8"));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Collections.singletonList(javaFile));

    List<String> optionList;
    optionList = new ArrayList<String>();
    optionList.addAll(Arrays.asList("-d", javaBinDirName));
    CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits);
    boolean compiled = task.call();
    try {
        fileManager.close();
    } catch (IOException e) {
        return false;
    }
    return compiled;
}

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  v a  2s .c om*/

    //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.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);
            }//  w  w w .  j a v  a 2s . c  o  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:org.openmrs.logic.CompilingClassLoader.java

private String compile(String javaFile) throws IOException {
    String errorMessage = null;//from  w  w  w  .j a v  a2  s  .c o m
    String ruleClassDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER);
    String ruleJavaDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    log.info("JavaCompiler is null: " + compiler == null);
    if (compiler != null) {
        // java compiler only available on JDK. This part of "IF" will not get executed when we run JUnit test
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] options = {};
        DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector,
                Context.getLocale(), Charset.defaultCharset());
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFolder));
        // create compiling classpath
        String stringProperties = System.getProperty("java.class.path");
        if (log.isDebugEnabled())
            log.debug("Compiler classpath: " + stringProperties);
        String[] properties = StringUtils.split(stringProperties, File.pathSeparator);
        List<File> classpathFiles = new ArrayList<File>();
        for (String property : properties) {
            File f = new File(property);
            if (f.exists())
                classpathFiles.add(f);
        }
        classpathFiles.addAll(getCompilerClasspath());
        fileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);
        // create the compilation task
        CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnosticCollector,
                Arrays.asList(options), null, fileManager.getJavaFileObjects(javaFile));
        boolean success = compilationTask.call();
        fileManager.close();
        if (success) {
            return null;
        } else {
            errorMessage = "";
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                errorMessage += diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Context.getLocale())
                        + "\n";
            }
            return errorMessage;
        }
    } else {
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] commands = { "javac", "-classpath", System.getProperty("java.class.path"), "-d",
                outputFolder.getAbsolutePath(), javaFile };
        // Start up the compiler
        File workingDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir);
        boolean success = LogicUtil.executeCommand(commands, workingDirectory);
        return success ? null : "Compilation error. (You must be using the JDK to see details.)";
    }
}

From source file:org.wso2.carbon.config.annotationprocessor.AnnotationProcessorTest.java

@BeforeClass
public void initClass() {
    //get the java compiler.
    compiler = ToolProvider.getSystemJavaCompiler();
    //configure the diagnostics collector.
    collector = new DiagnosticCollector<>();
    fileManager = compiler.getStandardFileManager(collector, Locale.US, Charset.forName("UTF-8"));
    packagePath = Paths.get("src", "test", "java", "org", "wso2", "carbon", "config", "annotationprocessor")
            .toString();//from  ww  w .  ja v  a 2s  .co m
    classesToCompile = new String[] { Paths.get(packagePath, "Configurations.java").toString() };
}