Search in sources :

Example 11 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project logging-log4j2 by apache.

the class PluginManagerPackagesTest method compile.

static void compile(final File f) throws IOException {
    // set up compiler
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    final List<String> errors = new ArrayList<>();
    try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));
        // compile generated source
        // (switch off annotation processing: no need to create Log4j2Plugins.dat)
        final List<String> options = Arrays.asList("-proc:none");
        compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call();
        // check we don't have any compilation errors
        for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
                errors.add(String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault())));
            }
        }
    }
    assertTrue(errors.toString(), errors.isEmpty());
}
Also used : JavaFileObject(javax.tools.JavaFileObject) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 12 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project gerrit by GerritCodeReview.

the class PrologCompiler method compileJava.

/** Compile java src into java .class files */
private void compileJava(File tempDir) throws IOException, CompileException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new CompileException("JDK required (running inside of JRE)");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(getAllFiles(tempDir, ".java"));
        ArrayList<String> options = new ArrayList<>();
        String classpath = getMyClasspath();
        if (classpath != null) {
            options.add("-classpath");
            options.add(classpath);
        }
        options.add("-d");
        options.add(tempDir.getPath());
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
        if (!task.call()) {
            Locale myLocale = Locale.getDefault();
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot compile to Java bytecode:");
            for (Diagnostic<? extends JavaFileObject> err : diagnostics.getDiagnostics()) {
                msg.append('\n');
                msg.append(err.getKind());
                msg.append(": ");
                if (err.getSource() != null) {
                    msg.append(err.getSource().getName());
                }
                msg.append(':');
                msg.append(err.getLineNumber());
                msg.append(": ");
                msg.append(err.getMessage(myLocale));
            }
            throw new CompileException(msg.toString());
        }
    }
}
Also used : Locale(java.util.Locale) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) JavaFileObject(javax.tools.JavaFileObject) CompileException(com.googlecode.prolog_cafe.exceptions.CompileException) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 13 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project compiler by boalang.

the class BaseTest method codegen.

protected StartContext codegen(final String input, final String error) throws IOException {
    final File outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);
    final File outputFile = new File(outputSrcDir, "Test.java");
    CodeGeneratingVisitor.combineAggregatorStrings.clear();
    CodeGeneratingVisitor.reduceAggregatorStrings.clear();
    final List<String> jobnames = new ArrayList<String>();
    final List<String> jobs = new ArrayList<String>();
    final List<Integer> seeds = new ArrayList<Integer>();
    final StartContext ctx = typecheck(input);
    // use the whole input string to seed the RNG
    seeds.add(input.hashCode());
    final Start p = ctx.ast;
    try {
        new InheritedAttributeTransformer().start(p);
        new LocalAggregationTransformer().start(p);
        new VisitorOptimizingTransformer().start(p);
        final CodeGeneratingVisitor cg = new CodeGeneratingVisitor("1");
        cg.start(p);
        jobs.add(cg.getCode());
        jobnames.add("1");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", "Test");
        st.add("numreducers", 1);
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", 64 * 1024 * 1024);
        st.add("seeds", seeds);
        final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            o.write(st.render().getBytes());
        } finally {
            o.close();
        }
        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File[] { outputFile }));
        if (!compiler.getTask(null, fileManager, diagnostics, Arrays.asList(new String[] { "-cp", System.getProperty("java.class.path") }), null, compilationUnits).call())
            for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) throw new RuntimeException("Error on line " + diagnostic.getLineNumber() + ": " + diagnostic.getMessage(null));
        if (error != null)
            fail("expected to see exception: " + error);
    } catch (final Exception e) {
        if (error == null) {
            if (e.getMessage() == null) {
                e.printStackTrace();
                fail("unexpected exception");
            } else
                fail("found unexpected exception: " + e.getMessage());
        } else
            assertEquals(error, e.getMessage());
    }
    delete(outputSrcDir);
    return ctx;
}
Also used : Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) JavaFileObject(javax.tools.JavaFileObject) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) BufferedOutputStream(java.io.BufferedOutputStream) ST(org.stringtemplate.v4.ST) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) JavaCompiler(javax.tools.JavaCompiler) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) StartContext(boa.parser.BoaParser.StartContext) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) File(java.io.File)

Example 14 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project zeppelin by apache.

the class JavaSourceFromString method execute.

public static String execute(String generatedClassName, String code) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    // Java parasing
    JavaProjectBuilder builder = new JavaProjectBuilder();
    JavaSource src = builder.addSource(new StringReader(code));
    // get all classes in code (paragraph)
    List<JavaClass> classes = src.getClasses();
    String mainClassName = null;
    // Searching for class containing Main method
    for (int i = 0; i < classes.size(); i++) {
        boolean hasMain = false;
        for (int j = 0; j < classes.get(i).getMethods().size(); j++) {
            if (classes.get(i).getMethods().get(j).getName().equals("main") && classes.get(i).getMethods().get(j).isStatic()) {
                mainClassName = classes.get(i).getName();
                hasMain = true;
                break;
            }
        }
        if (hasMain == true) {
            break;
        }
    }
    // if there isn't Main method, will retuen error
    if (mainClassName == null) {
        logger.error("Exception for Main method", "There isn't any class " + "containing static main method.");
        throw new Exception("There isn't any class containing static main method.");
    }
    // replace name of class containing Main method with generated name
    code = code.replace(mainClassName, generatedClassName);
    JavaFileObject file = new JavaSourceFromString(generatedClassName, code.toString());
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
    // Creating new stream to get the output data
    PrintStream newOut = new PrintStream(baosOut);
    PrintStream newErr = new PrintStream(baosErr);
    // Save the old System.out!
    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    // Tell Java to use your special stream
    System.setOut(newOut);
    System.setErr(newErr);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    // executing the compilation process
    boolean success = task.call();
    // if success is false will get error
    if (!success) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getLineNumber() == -1) {
                continue;
            }
            System.err.println("line " + diagnostic.getLineNumber() + " : " + diagnostic.getMessage(null));
        }
        System.out.flush();
        System.err.flush();
        System.setOut(oldOut);
        System.setErr(oldErr);
        logger.error("Exception in Interpreter while compilation", baosErr.toString());
        throw new Exception(baosErr.toString());
    } else {
        try {
            // creating new class loader
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
            // execute the Main method
            Class.forName(generatedClassName, true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
            System.out.flush();
            System.err.flush();
            // set the stream to old stream
            System.setOut(oldOut);
            System.setErr(oldErr);
            return baosOut.toString();
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.error("Exception in Interpreter while execution", e);
            System.err.println(e);
            e.printStackTrace(newErr);
            throw new Exception(baosErr.toString(), e);
        } finally {
            System.out.flush();
            System.err.flush();
            System.setOut(oldOut);
            System.setErr(oldErr);
        }
    }
}
Also used : Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaSource(com.thoughtworks.qdox.model.JavaSource) StringReader(java.io.StringReader) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaProjectBuilder(com.thoughtworks.qdox.JavaProjectBuilder) PrintStream(java.io.PrintStream) JavaCompiler(javax.tools.JavaCompiler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) InvocationTargetException(java.lang.reflect.InvocationTargetException) JavaClass(com.thoughtworks.qdox.model.JavaClass) URLClassLoader(java.net.URLClassLoader) JavaClass(com.thoughtworks.qdox.model.JavaClass) File(java.io.File)

Example 15 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project bazel by bazelbuild.

the class VanillaJavaBuilder method run.

public VanillaJavaBuilderResult run(List<String> args) throws IOException {
    OptionsParser optionsParser;
    try {
        optionsParser = new OptionsParser(args);
    } catch (InvalidCommandLineException e) {
        return new VanillaJavaBuilderResult(false, e.getMessage());
    }
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    StringWriter output = new StringWriter();
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH, UTF_8);
    setLocations(optionsParser, fileManager);
    ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
    boolean ok;
    if (sources.isEmpty()) {
        ok = true;
    } else {
        CompilationTask task = javaCompiler.getTask(new PrintWriter(output, true), fileManager, diagnosticCollector, JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()), ImmutableList.<String>of(), /*classes*/
        sources);
        setProcessors(optionsParser, fileManager, task);
        ok = task.call();
    }
    if (ok) {
        writeOutput(optionsParser);
    }
    writeGeneratedSourceOutput(optionsParser);
    // the file to be created
    if (optionsParser.getOutputDepsProtoFile() != null) {
        try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
            Deps.Dependencies.newBuilder().setRuleLabel(optionsParser.getTargetLabel()).setSuccess(ok).build().writeTo(os);
        }
    }
    // TODO(cushon): support manifest protos & genjar
    if (optionsParser.getManifestProtoPath() != null) {
        try (OutputStream os = Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
            Manifest.getDefaultInstance().writeTo(os);
        }
    }
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
        StringBuilder message = new StringBuilder();
        if (diagnostic.getSource() != null) {
            message.append(diagnostic.getSource().getName());
            if (diagnostic.getLineNumber() != -1) {
                message.append(':').append(diagnostic.getLineNumber());
            }
            message.append(": ");
        }
        message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
        message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
        output.write(message.toString());
    }
    return new VanillaJavaBuilderResult(ok, output.toString());
}
Also used : OutputStream(java.io.OutputStream) JavaCompiler(javax.tools.JavaCompiler) CompilationTask(javax.tools.JavaCompiler.CompilationTask) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) PrintWriter(java.io.PrintWriter)

Aggregations

DiagnosticCollector (javax.tools.DiagnosticCollector)28 JavaFileObject (javax.tools.JavaFileObject)28 JavaCompiler (javax.tools.JavaCompiler)24 StandardJavaFileManager (javax.tools.StandardJavaFileManager)16 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)9 Diagnostic (javax.tools.Diagnostic)9 CompilationTask (javax.tools.JavaCompiler.CompilationTask)9 File (java.io.File)8 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)8 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 Test (org.junit.Test)4 FileOutputStream (java.io.FileOutputStream)3 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 ImmutableList (com.google.common.collect.ImmutableList)2 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)2 SourceFile (com.google.errorprone.apply.SourceFile)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2