Search in sources :

Example 21 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project neo4j by neo4j.

the class DbStructureInvocationTracingAcceptanceTest method compile.

private <T> T compile(String className, String source, CompilationListener<T> listener) {
    JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager manager = new InMemFileManager();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
    Iterable<? extends JavaFileObject> sources = Arrays.asList(new InMemSource(className, source));
    CompilationTask task = systemCompiler.getTask(null, manager, diagnosticsCollector, null, null, sources);
    Boolean success = task.call();
    return listener.compiled(success, manager, diagnosticsCollector.getDiagnostics());
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 22 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project yyl_example by Relucent.

the class JavaCompilerTest method compile.

private static boolean compile(String className, String source) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    //DiagnosticListener 编译的诊断信息
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    CompilationTask task = compiler.getTask(null, null, diagnostics, Arrays.asList("-d", tempdir), null, Arrays.asList(new JavaSourceFromString(className, source)));
    boolean success = task.call();
    System.out.println("Success: " + success);
    print(diagnostics);
    return success;
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 23 with DiagnosticCollector

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

the class ClassBuilder method compileClass.

/**
   * Compile the provided class. The className may have a package separated by /. For example:
   * my/package/myclass
   * 
   * @param className Name of the class to compile.
   * @param classCode Plain text contents of the class
   * @return The byte contents of the compiled class.
   * @throws IOException
   */
public byte[] compileClass(final String className, final String classCode) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    OutputStreamJavaFileManager<JavaFileManager> fileManager = new OutputStreamJavaFileManager<JavaFileManager>(javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);
    List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
    fileObjects.add(new JavaSourceFromString(className, classCode));
    List<String> options = Arrays.asList("-classpath", this.classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
        StringBuilder errorMsg = new StringBuilder();
        for (Diagnostic d : diagnostics.getDiagnostics()) {
            String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(), d.getMessage(null));
            errorMsg.append(err);
            System.err.print(err);
        }
        throw new IOException(errorMsg.toString());
    }
    return byteArrayOutputStream.toByteArray();
}
Also used : JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 24 with DiagnosticCollector

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

the class GenerateCustomLoggerTest method testGenerateSource.

@Test
public void testGenerateSource() throws Exception {
    final String CLASSNAME = "org.myorg.MyCustomLogger";
    // generate custom logger source
    final List<String> values = Arrays.asList("DEFCON1=350 DEFCON2=450 DEFCON3=550".split(" "));
    final List<Generate.LevelInfo> levels = Generate.LevelInfo.parse(values, Generate.CustomLogger.class);
    final String src = Generate.generateSource(CLASSNAME, levels, Generate.Type.CUSTOM);
    final File f = new File("target/test-classes/org/myorg/MyCustomLogger.java");
    f.getParentFile().mkdirs();
    try (final FileOutputStream out = new FileOutputStream(f)) {
        out.write(src.getBytes(Charset.defaultCharset()));
    }
    // 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
        compiler.getTask(null, fileManager, diagnostics, null, 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());
    // load the compiled class
    final Class<?> cls = Class.forName(CLASSNAME);
    // check that all factory methods exist and are static
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[0]).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Class.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Object.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { String.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class, MessageFactory.class).getModifiers()));
    // check that all log methods exist
    final String[] logMethods = { "defcon1", "defcon2", "defcon3" };
    for (final String name : logMethods) {
        cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, Message.class);
        cls.getDeclaredMethod(name, Marker.class, Object.class);
        cls.getDeclaredMethod(name, Marker.class, String.class);
        cls.getDeclaredMethod(name, Message.class);
        cls.getDeclaredMethod(name, Object.class);
        cls.getDeclaredMethod(name, String.class);
        cls.getDeclaredMethod(name, Message.class, Throwable.class);
        cls.getDeclaredMethod(name, Object.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Object[].class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
        // 2.4 lambda support
        cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
        cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
        cls.getDeclaredMethod(name, Marker.class, Supplier.class);
        cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
        cls.getDeclaredMethod(name, MessageSupplier.class);
        cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Supplier[].class);
        cls.getDeclaredMethod(name, Supplier.class);
        cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
    }
    // now see if it actually works...
    final Method create = cls.getDeclaredMethod("create", new Class[] { String.class });
    final Object customLogger = create.invoke(null, "X.Y.Z");
    int n = 0;
    for (final String name : logMethods) {
        final Method method = cls.getDeclaredMethod(name, String.class);
        method.invoke(customLogger, "This is message " + n++);
    }
    final TestLogger underlying = (TestLogger) LogManager.getLogger("X.Y.Z");
    final List<String> lines = underlying.getEntries();
    for (int i = 0; i < lines.size(); i++) {
        assertEquals(" " + levels.get(i).name + " This is message " + i, lines.get(i));
    }
}
Also used : MessageFactory(org.apache.logging.log4j.message.MessageFactory) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Method(java.lang.reflect.Method) TestLogger(org.apache.logging.log4j.TestLogger) JavaFileObject(javax.tools.JavaFileObject) FileOutputStream(java.io.FileOutputStream) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) BeforeClass(org.junit.BeforeClass) JavaFileObject(javax.tools.JavaFileObject) MessageSupplier(org.apache.logging.log4j.util.MessageSupplier) Supplier(org.apache.logging.log4j.util.Supplier) File(java.io.File) Test(org.junit.Test)

Example 25 with DiagnosticCollector

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

the class GenerateExtendedLoggerTest method testGenerateSource.

@Test
public void testGenerateSource() throws Exception {
    final String CLASSNAME = "org.myorg.MyExtendedLogger";
    // generate custom logger source
    final List<String> values = Arrays.asList("DIAG=350 NOTICE=450 VERBOSE=550".split(" "));
    final List<Generate.LevelInfo> levels = Generate.LevelInfo.parse(values, Generate.ExtendedLogger.class);
    final String src = Generate.generateSource(CLASSNAME, levels, Generate.Type.EXTEND);
    final File f = new File("target/test-classes/org/myorg/MyExtendedLogger.java");
    f.getParentFile().mkdirs();
    try (final FileOutputStream out = new FileOutputStream(f)) {
        out.write(src.getBytes(Charset.defaultCharset()));
    }
    // 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
        compiler.getTask(null, fileManager, diagnostics, null, 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());
    // load the compiled class
    final Class<?> cls = Class.forName(CLASSNAME);
    // check that all factory methods exist and are static
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[0]).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Class.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { Object.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", new Class[] { String.class }).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class, MessageFactory.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", String.class, MessageFactory.class).getModifiers()));
    // check that the extended log methods exist
    final String[] extendedMethods = { "diag", "notice", "verbose" };
    for (final String name : extendedMethods) {
        cls.getDeclaredMethod(name, Marker.class, Message.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, Object.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, Message.class);
        cls.getDeclaredMethod(name, Marker.class, Object.class);
        cls.getDeclaredMethod(name, Marker.class, String.class);
        cls.getDeclaredMethod(name, Message.class);
        cls.getDeclaredMethod(name, Object.class);
        cls.getDeclaredMethod(name, String.class);
        cls.getDeclaredMethod(name, Message.class, Throwable.class);
        cls.getDeclaredMethod(name, Object.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Object[].class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Object[].class);
        // 2.4 lambda support
        cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class);
        cls.getDeclaredMethod(name, Marker.class, MessageSupplier.class, Throwable.class);
        cls.getDeclaredMethod(name, Marker.class, String.class, Supplier[].class);
        cls.getDeclaredMethod(name, Marker.class, Supplier.class);
        cls.getDeclaredMethod(name, Marker.class, Supplier.class, Throwable.class);
        cls.getDeclaredMethod(name, MessageSupplier.class);
        cls.getDeclaredMethod(name, MessageSupplier.class, Throwable.class);
        cls.getDeclaredMethod(name, String.class, Supplier[].class);
        cls.getDeclaredMethod(name, Supplier.class);
        cls.getDeclaredMethod(name, Supplier.class, Throwable.class);
    }
    // now see if it actually works...
    final Method create = cls.getDeclaredMethod("create", new Class[] { String.class });
    final Object extendedLogger = create.invoke(null, "X.Y.Z");
    int n = 0;
    for (final String name : extendedMethods) {
        final Method method = cls.getDeclaredMethod(name, String.class);
        method.invoke(extendedLogger, "This is message " + n++);
    }
    // This logger extends o.a.l.log4j.spi.ExtendedLogger,
    // so all the standard logging methods can be used as well
    final ExtendedLogger logger = (ExtendedLogger) extendedLogger;
    logger.trace("trace message");
    logger.debug("debug message");
    logger.info("info message");
    logger.warn("warn message");
    logger.error("error message");
    logger.fatal("fatal message");
    final TestLogger underlying = (TestLogger) LogManager.getLogger("X.Y.Z");
    final List<String> lines = underlying.getEntries();
    for (int i = 0; i < lines.size() - 6; i++) {
        assertEquals(" " + levels.get(i).name + " This is message " + i, lines.get(i));
    }
    // test that the standard logging methods still work
    int i = lines.size() - 6;
    assertEquals(" TRACE trace message", lines.get(i++));
    assertEquals(" DEBUG debug message", lines.get(i++));
    assertEquals(" INFO info message", lines.get(i++));
    assertEquals(" WARN warn message", lines.get(i++));
    assertEquals(" ERROR error message", lines.get(i++));
    assertEquals(" FATAL fatal message", lines.get(i++));
}
Also used : ArrayList(java.util.ArrayList) JavaFileObject(javax.tools.JavaFileObject) Generate(org.apache.logging.log4j.core.tools.Generate) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) MessageSupplier(org.apache.logging.log4j.util.MessageSupplier) Supplier(org.apache.logging.log4j.util.Supplier) MessageFactory(org.apache.logging.log4j.message.MessageFactory) JavaCompiler(javax.tools.JavaCompiler) Method(java.lang.reflect.Method) TestLogger(org.apache.logging.log4j.TestLogger) ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) FileOutputStream(java.io.FileOutputStream) BeforeClass(org.junit.BeforeClass) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) Test(org.junit.Test)

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