Search in sources :

Example 76 with StandardJavaFileManager

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

the class BaseErrorProneCompiler method run.

public Result run(String[] argv) {
    try {
        argv = CommandLine.parse(argv);
    } catch (IOException e) {
        throw new IOError(e);
    }
    List<String> javacOpts = new ArrayList<>();
    List<String> sources = new ArrayList<>();
    for (String arg : argv) {
        // TODO(cushon): is there a better way to categorize javacopts?
        if (!arg.startsWith("-") && arg.endsWith(".java")) {
            sources.add(arg);
        } else {
            javacOpts.add(arg);
        }
    }
    StandardJavaFileManager fileManager = new MaskedFileManager();
    return run(javacOpts.toArray(new String[0]), fileManager, ImmutableList.copyOf(fileManager.getJavaFileObjectsFromStrings(sources)), /* processors= */
    null);
}
Also used : MaskedFileManager(com.google.errorprone.MaskedClassLoader.MaskedFileManager) IOError(java.io.IOError) ArrayList(java.util.ArrayList) StandardJavaFileManager(javax.tools.StandardJavaFileManager) IOException(java.io.IOException)

Example 77 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project DistributedFractalNetwork by Budder21.

the class DynamicCompiler method compile.

/**
 * compile your files by JavaCompiler. If the class was succesfuly compiled, it will print 'Succeded'. Otherwise, it
 * will print diagnositc information.
 * @param files takes in an Arrays.asList of the JavaFileObject
 * @throws NullPointerException this is thrown if the java file is run from a JRE instead of a JDK.
 */
public static void compile(Iterable<? extends JavaFileObject> files) throws NullPointerException {
    // get system compiler:
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // for compilation diagnostic message processing on compilation
    // WARNING/ERROR
    MyDiagnosticListener c = new MyDiagnosticListener();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(c, Locale.ENGLISH, null);
    // specify classes output folder
    Iterable options = Arrays.asList("-d", classOutputFolder);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, c, options, null, files);
    Boolean result = task.call();
    if (result == true) {
        System.out.println("Succeeded");
    } else
        System.out.println("Failed");
}
Also used : JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Example 78 with StandardJavaFileManager

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

the class PluginManagerPackagesTest method compile.

static void compile(final Path path) {
    // set up compiler
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    final List<String> errors = new ArrayList<>();
    assertDoesNotThrow(() -> {
        try (final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
            final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromPaths(List.of(path));
            String classPath = System.getProperty("jdk.module.path");
            List<String> options = new ArrayList<>();
            if (Strings.isNotBlank(classPath)) {
                options.add("-classpath");
                options.add(classPath);
            }
            options.add("-proc:none");
            // compile generated source
            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())));
                }
            }
        }
    });
    assertThat(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 79 with StandardJavaFileManager

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

the class GenerateCustomLoggerTest method testGenerateSource.

@Test
public void testGenerateSource() throws Exception {
    final String CLASSNAME = "org.apache.logging.log4j.core.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(TEST_SOURCE);
    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(Collections.singletonList(f));
        String classPath = System.getProperty("jdk.module.path");
        List<String> optionList = new ArrayList<>();
        if (Strings.isNotBlank(classPath)) {
            optionList.add("-classpath");
            optionList.add(classPath);
        }
        // compile generated source
        compiler.getTask(null, fileManager, diagnostics, optionList, 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.isEmpty(), errors.toString());
    // 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").getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", 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) {
        assertDoesNotThrow(() -> {
            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", 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.test.TestLogger) JavaFileObject(javax.tools.JavaFileObject) FileOutputStream(java.io.FileOutputStream) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) 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.jupiter.api.Test)

Example 80 with StandardJavaFileManager

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

the class GenerateExtendedLoggerTest method testGenerateSource.

@Test
public void testGenerateSource() throws Exception {
    final String CLASSNAME = "org.apache.logging.log4j.core.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(TEST_SOURCE);
    f.getParentFile().mkdirs();
    try (final FileOutputStream out = new FileOutputStream(f)) {
        out.write(src.getBytes(Charset.defaultCharset()));
    }
    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(Collections.singletonList(f));
        String classPath = System.getProperty("jdk.module.path");
        List<String> optionList = new ArrayList<>();
        if (Strings.isNotBlank(classPath)) {
            optionList.add("-classpath");
            optionList.add(classPath);
        }
        // compile generated source
        compiler.getTask(null, fileManager, diagnostics, optionList, 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.isEmpty(), errors.toString());
    // 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").getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Class.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", Object.class).getModifiers()));
    assertTrue(Modifier.isStatic(cls.getDeclaredMethod("create", 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) {
        assertDoesNotThrow(() -> {
            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", 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) 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.test.TestLogger) ExtendedLogger(org.apache.logging.log4j.spi.ExtendedLogger) FileOutputStream(java.io.FileOutputStream) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File) Test(org.junit.jupiter.api.Test)

Aggregations

StandardJavaFileManager (javax.tools.StandardJavaFileManager)124 JavaCompiler (javax.tools.JavaCompiler)99 File (java.io.File)60 JavaFileObject (javax.tools.JavaFileObject)50 IOException (java.io.IOException)37 DiagnosticCollector (javax.tools.DiagnosticCollector)36 ArrayList (java.util.ArrayList)33 CompilationTask (javax.tools.JavaCompiler.CompilationTask)25 JavacTask (com.sun.source.util.JavacTask)17 StringWriter (java.io.StringWriter)10 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)9 JavacTool (com.sun.tools.javac.api.JavacTool)8 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)6 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)5 URL (java.net.URL)5 FileOutputStream (java.io.FileOutputStream)4 PrintWriter (java.io.PrintWriter)4 Diagnostic (javax.tools.Diagnostic)4 Charset (java.nio.charset.Charset)3 HashSet (java.util.HashSet)3