Search in sources :

Example 16 with Diagnostic

use of javax.tools.Diagnostic 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 17 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneCompilerIntegrationTest method fileWithMultipleTopLevelClassesExtendsWithError.

/**
   * Regression test for a bug in which multiple top-level classes may cause
   * NullPointerExceptions in the matchers.
   */
@Test
public void fileWithMultipleTopLevelClassesExtendsWithError() throws Exception {
    Result exitCode = compiler.compile(compiler.fileManager().forResources(getClass(), "testdata/MultipleTopLevelClassesWithErrors.java", "testdata/ExtendedMultipleTopLevelClassesWithErrors.java"));
    assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
    assertTrue("Warning should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
    assertThat(diagnosticHelper.getDiagnostics()).hasSize(4);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Example 18 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneCompilerIntegrationTest method fileWithWarning.

@Test
public void fileWithWarning() throws Exception {
    compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(NonAtomicVolatileUpdate.class));
    compiler = compilerBuilder.build();
    Result exitCode = compiler.compile(compiler.fileManager().forResources(NonAtomicVolatileUpdate.class, "testdata/NonAtomicVolatileUpdatePositiveCases.java"));
    assertThat(outputStream.toString(), exitCode, is(Result.OK));
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[NonAtomicVolatileUpdate]")));
    assertTrue("Warning should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
}
Also used : NonAtomicVolatileUpdate(com.google.errorprone.bugpatterns.NonAtomicVolatileUpdate) JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Example 19 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneCompilerIntegrationTest method severityIsResetOnNextCompilation.

@Test
public void severityIsResetOnNextCompilation() throws Exception {
    String[] testFile = { "public class Test {", "  void doIt (int i) {", "    i = i;", "  }", "}" };
    String[] args = { "-Xep:SelfAssignment:WARN" };
    Result exitCode = compiler.compile(args, Arrays.asList(compiler.fileManager().forSourceLines("Test.java", testFile)));
    outputStream.flush();
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[SelfAssignment]")));
    assertThat(outputStream.toString(), exitCode, is(Result.OK));
    assertTrue("Warning should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
    // Should reset to default severity (ERROR)
    exitCode = compiler.compile(Arrays.asList(compiler.fileManager().forSourceLines("Test.java", testFile)));
    outputStream.flush();
    assertThat(outputStream.toString(), exitCode, is(Result.ERROR));
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) Matchers.containsString(org.hamcrest.Matchers.containsString) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Example 20 with Diagnostic

use of javax.tools.Diagnostic in project error-prone by google.

the class ErrorProneJavaCompilerTest method testMaturityResetsAfterOverride.

@Test
public void testMaturityResetsAfterOverride() throws Exception {
    DiagnosticTestHelper diagnosticHelper = new DiagnosticTestHelper();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, UTF_8), true);
    ErrorProneInMemoryFileManager fileManager = new ErrorProneInMemoryFileManager();
    JavaCompiler errorProneJavaCompiler = new ErrorProneJavaCompiler();
    List<String> args = Lists.newArrayList("-d", tempDir.getRoot().getAbsolutePath(), "-proc:none", "-Xep:EmptyIf");
    List<JavaFileObject> sources = fileManager.forResources(BadShiftAmount.class, "testdata/EmptyIfStatementPositiveCases.java");
    fileManager.close();
    JavaCompiler.CompilationTask task = errorProneJavaCompiler.getTask(printWriter, null, diagnosticHelper.collector, args, null, sources);
    boolean succeeded = task.call();
    assertThat(succeeded).isFalse();
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticMessage(containsString("[EmptyIf]")));
    assertTrue(matcher.matches(diagnosticHelper.getDiagnostics()));
    diagnosticHelper.clearDiagnostics();
    args.remove("-Xep:EmptyIf");
    task = errorProneJavaCompiler.getTask(printWriter, null, diagnosticHelper.collector, args, null, sources);
    fileManager.close();
    succeeded = task.call();
    assertThat(succeeded).isTrue();
    assertThat(diagnosticHelper.getDiagnostics()).isEmpty();
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) JavaFileObject(javax.tools.JavaFileObject) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Aggregations

Diagnostic (javax.tools.Diagnostic)31 JavaFileObject (javax.tools.JavaFileObject)30 Test (org.junit.Test)13 JavaCompiler (javax.tools.JavaCompiler)11 Result (com.sun.tools.javac.main.Main.Result)10 DiagnosticCollector (javax.tools.DiagnosticCollector)9 File (java.io.File)7 IOException (java.io.IOException)7 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)7 PrintWriter (java.io.PrintWriter)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 ArrayList (java.util.ArrayList)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2 JavacTask (com.sun.source.util.JavacTask)2 OutputStreamWriter (java.io.OutputStreamWriter)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2