Search in sources :

Example 36 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project jdk8u_jdk by JetBrains.

the class ManyMethodsBenchmarkApp method main.

public static void main(String[] args) throws Exception {
    System.out.println("test started: ManyMethodsBenchmarkApp");
    // Create source files with many methods
    File base = new File("Base.java");
    try (FileWriter fw = new FileWriter(base)) {
        fw.write("public class Base {\n");
        final int L = 10;
        // Each of the first L methods makes calls to its own chunk of METHOD_COUNT/L methods
        for (int k = 0; k < L; k++) {
            fw.write("    public void f" + k + "() {\n");
            int shift = (k == 0) ? L : 0;
            for (int i = (k * (METHOD_COUNT / L)) + shift; i < (k + 1) * METHOD_COUNT / L; i++) {
                fw.write("        f" + i + "();\n");
            }
            fw.write("    }\n");
        }
        // The rest of (METHOD_COUNT - L) methods have empty body
        for (int i = L; i < METHOD_COUNT; i++) {
            fw.write("    public static void f" + i + "() {}\n");
        }
        fw.write("}\n");
    }
    // Compile the generated source files.
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<File> files = Arrays.asList(new File[] { base });
    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
        compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(files)).call();
    }
    benchmarkClassOperations("Base");
    ManyMethodsBenchmarkAgent.instr();
    // Cleanup
    base.delete();
    new File("Base.class").delete();
    if (!ManyMethodsBenchmarkAgent.completed) {
        throw new Exception("ERROR: ManyMethodsBenchmarkAgent did not complete.");
    }
    if (ManyMethodsBenchmarkAgent.fail) {
        throw new Exception("ERROR: ManyMethodsBenchmarkAgent failed.");
    } else {
        System.out.println("ManyMethodsBenchmarkAgent succeeded.");
    }
    System.out.println("test finished: ManyMethodsBenchmarkApp");
}
Also used : FileWriter(java.io.FileWriter) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 37 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.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 38 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.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)

Example 39 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project ceylon-compiler by ceylon.

the class ClassReader method fillIn.

/** Load directory of package into members scope.
     */
private void fillIn(PackageSymbol p) throws IOException {
    if (p.members_field == null)
        p.members_field = new Scope(p);
    String packageName = p.fullname.toString();
    Set<JavaFileObject.Kind> kinds = getPackageFileKinds();
    fillIn(p, PLATFORM_CLASS_PATH, fileManager.list(PLATFORM_CLASS_PATH, packageName, EnumSet.of(JavaFileObject.Kind.CLASS), false));
    Set<JavaFileObject.Kind> classKinds = EnumSet.copyOf(kinds);
    classKinds.remove(JavaFileObject.Kind.SOURCE);
    boolean wantClassFiles = !classKinds.isEmpty();
    Set<JavaFileObject.Kind> sourceKinds = EnumSet.copyOf(kinds);
    sourceKinds.remove(JavaFileObject.Kind.CLASS);
    boolean wantSourceFiles = !sourceKinds.isEmpty();
    boolean haveSourcePath = fileManager.hasLocation(SOURCE_PATH);
    if (verbose && verbosePath) {
        if (fileManager instanceof StandardJavaFileManager) {
            StandardJavaFileManager fm = (StandardJavaFileManager) fileManager;
            if (haveSourcePath && wantSourceFiles) {
                List<File> path = List.nil();
                for (File file : fm.getLocation(SOURCE_PATH)) {
                    path = path.prepend(file);
                }
                log.printVerbose("sourcepath", path.reverse().toString());
            } else if (wantSourceFiles) {
                List<File> path = List.nil();
                for (File file : fm.getLocation(CLASS_PATH)) {
                    path = path.prepend(file);
                }
                log.printVerbose("sourcepath", path.reverse().toString());
            }
            if (wantClassFiles) {
                List<File> path = List.nil();
                for (File file : fm.getLocation(PLATFORM_CLASS_PATH)) {
                    path = path.prepend(file);
                }
                for (File file : fm.getLocation(CLASS_PATH)) {
                    path = path.prepend(file);
                }
                log.printVerbose("classpath", path.reverse().toString());
            }
        }
    }
    if (wantSourceFiles && !haveSourcePath) {
        fillIn(p, CLASS_PATH, fileManager.list(CLASS_PATH, packageName, kinds, false));
    } else {
        if (wantClassFiles)
            fillIn(p, CLASS_PATH, fileManager.list(CLASS_PATH, packageName, classKinds, false));
        if (wantSourceFiles)
            fillIn(p, SOURCE_PATH, fileManager.list(SOURCE_PATH, packageName, sourceKinds, false));
    }
    verbosePath = false;
}
Also used : StandardJavaFileManager(javax.tools.StandardJavaFileManager) ClassFile(com.sun.tools.javac.jvm.ClassFile)

Example 40 with StandardJavaFileManager

use of javax.tools.StandardJavaFileManager in project ceylon-compiler by ceylon.

the class T6458823 method main.

public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl, options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " + diagCount + ", expected: 2");
    }
}
Also used : ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JavaFileObject(javax.tools.JavaFileObject) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Aggregations

StandardJavaFileManager (javax.tools.StandardJavaFileManager)57 JavaCompiler (javax.tools.JavaCompiler)42 JavaFileObject (javax.tools.JavaFileObject)24 File (java.io.File)23 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)17 DiagnosticCollector (javax.tools.DiagnosticCollector)15 CompilationTask (javax.tools.JavaCompiler.CompilationTask)9 JavacTask (com.sun.source.util.JavacTask)7 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)4 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 JavacTool (com.sun.tools.javac.api.JavacTool)4 FileOutputStream (java.io.FileOutputStream)4 StringWriter (java.io.StringWriter)3 ZipFile (java.util.zip.ZipFile)3 Test (org.junit.Test)3 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)2 PrintWriter (java.io.PrintWriter)2 Method (java.lang.reflect.Method)2 URI (java.net.URI)2