Search in sources :

Example 1 with JavaCompiler

use of javax.tools.JavaCompiler in project hbase by apache.

the class ClassLoaderTestHelper method buildJar.

/**
   * Create a test jar for testing purpose for a given class
   * name with specified code string.
   *
   * @param testDir the folder under which to store the test class
   * @param className the test class name
   * @param code the optional test class code, which can be null.
   * If null, an empty class will be used
   * @param folder the folder under which to store the generated jar
   * @return the test jar file generated
   */
public static File buildJar(String testDir, String className, String code, String folder) throws Exception {
    String javaCode = code != null ? code : "public class " + className + " {}";
    Path srcDir = new Path(testDir, "src");
    File srcDirPath = new File(srcDir.toString());
    srcDirPath.mkdirs();
    File sourceCodeFile = new File(srcDir.toString(), className + ".java");
    BufferedWriter bw = new BufferedWriter(new FileWriter(sourceCodeFile));
    bw.write(javaCode);
    bw.close();
    // compile it by JavaCompiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    ArrayList<String> srcFileNames = new ArrayList<>(1);
    srcFileNames.add(sourceCodeFile.toString());
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> cu = fm.getJavaFileObjects(sourceCodeFile);
    List<String> options = new ArrayList<>(2);
    options.add("-classpath");
    // only add hbase classes to classpath. This is a little bit tricky: assume
    // the classpath is {hbaseSrc}/target/classes.
    String currentDir = new File(".").getAbsolutePath();
    String classpath = currentDir + File.separator + "target" + File.separator + "classes" + System.getProperty("path.separator") + System.getProperty("java.class.path") + System.getProperty("path.separator") + System.getProperty("surefire.test.class.path");
    options.add(classpath);
    LOG.debug("Setting classpath to: " + classpath);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null, options, null, cu);
    assertTrue("Compile file " + sourceCodeFile + " failed.", task.call());
    // build a jar file by the classes files
    String jarFileName = className + ".jar";
    File jarFile = new File(folder, jarFileName);
    jarFile.getParentFile().mkdirs();
    if (!createJarArchive(jarFile, new File[] { new File(srcDir.toString(), className + ".class") })) {
        assertTrue("Build jar file failed.", false);
    }
    return jarFile;
}
Also used : Path(org.apache.hadoop.fs.Path) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 2 with JavaCompiler

use of javax.tools.JavaCompiler in project hbase by apache.

the class TestClassFinder method compileTestClass.

/**
   * Compiles the test class with bogus code into a .class file.
   * Unfortunately it's very tedious.
   * @param counter Unique test counter.
   * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
   * @return The resulting .class file and the location in jar it is supposed to go to.
   */
private static FileAndPath compileTestClass(long counter, String packageNameSuffix, String classNamePrefix) throws Exception {
    classNamePrefix = classNamePrefix + counter;
    String packageName = makePackageName(packageNameSuffix, counter);
    String javaPath = basePath + classNamePrefix + ".java";
    String classPath = basePath + classNamePrefix + ".class";
    PrintStream source = new PrintStream(javaPath);
    source.println("package " + packageName + ";");
    source.println("public class " + classNamePrefix + " { public static void main(String[] args) { } };");
    source.close();
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    int result = jc.run(null, null, null, javaPath);
    assertEquals(0, result);
    File classFile = new File(classPath);
    assertTrue(classFile.exists());
    return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
Also used : PrintStream(java.io.PrintStream) JavaCompiler(javax.tools.JavaCompiler) File(java.io.File)

Example 3 with JavaCompiler

use of javax.tools.JavaCompiler in project storm by apache.

the class CompilingClassLoader method compileSourceCodeToByteCode.

/**
   * @return Whether compilation was successful.
   */
private boolean compileSourceCodeToByteCode(String className, String sourceCode, DiagnosticListener<JavaFileObject> diagnosticListener) {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    // Set up the in-memory filesystem.
    InMemoryFileManager fileManager = new InMemoryFileManager(javaCompiler.getStandardFileManager(null, null, null));
    JavaFileObject javaFile = new InMemoryJavaFile(className, sourceCode);
    // Javac option: remove these when the javac zip impl is fixed
    // (http://b/issue?id=1822932)
    // setting value to any non-null string
    System.setProperty("useJavaUtilZip", "true");
    List<String> options = new LinkedList<>();
    // this is ignored by javac currently but useJavaUtilZip should be
    // a valid javac XD option, which is another bug
    options.add("-XDuseJavaUtilZip");
    // Now compile!
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(// Null: log any unhandled errors to stderr.
    null, fileManager, diagnosticListener, options, null, singleton(javaFile));
    return compilationTask.call();
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaCompiler(javax.tools.JavaCompiler) LinkedList(java.util.LinkedList)

Example 4 with JavaCompiler

use of javax.tools.JavaCompiler in project buck by facebook.

the class Jsr199Javac method buildWithClasspath.

@Override
public int buildWithClasspath(JavacExecutionContext context, BuildTarget invokingRule, ImmutableList<String> options, ImmutableList<ResolvedJavacPluginProperties> annotationProcessors, ImmutableSortedSet<Path> javaSourceFilePaths, Path pathToSrcsList, Optional<Path> workingDirectory, JavacOptions.AbiGenerationMode abiGenerationMode) {
    JavaCompiler compiler = createCompiler(context);
    CustomZipOutputStream jarOutputStream = null;
    StandardJavaFileManager fileManager = null;
    JavaInMemoryFileManager inMemoryFileManager = null;
    try {
        fileManager = compiler.getStandardFileManager(null, null, null);
        Supplier<ImmutableSet<String>> alreadyAddedFilesAvailableAfterCompilation = Suppliers.ofInstance(ImmutableSet.of());
        if (context.getDirectToJarOutputSettings().isPresent()) {
            Path path = context.getProjectFilesystem().getPathForRelativePath(context.getDirectToJarOutputSettings().get().getDirectToJarOutputPath());
            jarOutputStream = ZipOutputStreams.newOutputStream(path, ZipOutputStreams.HandleDuplicates.APPEND_TO_ZIP);
            inMemoryFileManager = new JavaInMemoryFileManager(fileManager, path, jarOutputStream, context.getDirectToJarOutputSettings().get().getClassesToRemoveFromJar());
            alreadyAddedFilesAvailableAfterCompilation = inMemoryFileManager::getEntries;
            fileManager = inMemoryFileManager;
        }
        Iterable<? extends JavaFileObject> compilationUnits;
        try {
            compilationUnits = createCompilationUnits(fileManager, context.getProjectFilesystem()::resolve, javaSourceFilePaths);
        } catch (IOException e) {
            LOG.warn(e, "Error building compilation units");
            return 1;
        }
        try {
            int result = buildWithClasspath(context, invokingRule, options, annotationProcessors, javaSourceFilePaths, pathToSrcsList, compiler, fileManager, compilationUnits, abiGenerationMode);
            if (result != 0 || !context.getDirectToJarOutputSettings().isPresent()) {
                return result;
            }
            return JarDirectoryStepHelper.createJarFile(context.getProjectFilesystem(), context.getDirectToJarOutputSettings().get().getDirectToJarOutputPath(), Preconditions.checkNotNull(jarOutputStream), context.getDirectToJarOutputSettings().get().getEntriesToJar(), alreadyAddedFilesAvailableAfterCompilation.get(), context.getDirectToJarOutputSettings().get().getMainClass(), context.getDirectToJarOutputSettings().get().getManifestFile(), /* mergeManifests */
            true, /* blacklist */
            ImmutableSet.of(), context.getEventSink(), context.getStdErr());
        } finally {
            close(compilationUnits);
        }
    } catch (IOException e) {
        LOG.warn(e, "Unable to create jarOutputStream");
    } finally {
        closeResources(fileManager, inMemoryFileManager, jarOutputStream);
    }
    return 1;
}
Also used : Path(java.nio.file.Path) ImmutableSet(com.google.common.collect.ImmutableSet) JavaCompiler(javax.tools.JavaCompiler) StandardJavaFileManager(javax.tools.StandardJavaFileManager) CustomZipOutputStream(com.facebook.buck.zip.CustomZipOutputStream) IOException(java.io.IOException)

Example 5 with JavaCompiler

use of javax.tools.JavaCompiler in project buck by facebook.

the class Jsr199Javac method buildWithClasspath.

private int buildWithClasspath(JavacExecutionContext context, BuildTarget invokingRule, ImmutableList<String> options, ImmutableList<ResolvedJavacPluginProperties> annotationProcessors, ImmutableSortedSet<Path> javaSourceFilePaths, Path pathToSrcsList, JavaCompiler compiler, StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits, JavacOptions.AbiGenerationMode abiGenerationMode) {
    // since we do not print them out to console in case of error
    try {
        context.getProjectFilesystem().writeLinesToPath(FluentIterable.from(javaSourceFilePaths).transform(Object::toString).transform(ARGFILES_ESCAPER), pathToSrcsList);
    } catch (IOException e) {
        context.getEventSink().reportThrowable(e, "Cannot write list of .java files to compile to %s file! Terminating compilation.", pathToSrcsList);
        return 1;
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    List<String> classNamesForAnnotationProcessing = ImmutableList.of();
    Writer compilerOutputWriter = new PrintWriter(context.getStdErr());
    JavaCompiler.CompilationTask compilationTask = compiler.getTask(compilerOutputWriter, context.getUsedClassesFileWriter().wrapFileManager(fileManager), diagnostics, options, classNamesForAnnotationProcessing, compilationUnits);
    boolean isSuccess = false;
    BuckTracing.setCurrentThreadTracingInterfaceFromJsr199Javac(new Jsr199TracingBridge(context.getEventSink(), invokingRule));
    Object abiValidatingTaskListener = null;
    if (abiGenerationMode != JavacOptions.AbiGenerationMode.CLASS) {
        abiValidatingTaskListener = SourceBasedAbiStubber.newValidatingTaskListener(context.getClassLoaderCache(), compilationTask, new FileManagerBootClasspathOracle(fileManager), abiGenerationMode == JavacOptions.AbiGenerationMode.SOURCE ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING);
    }
    try {
        try (// in some unusual situations
        TranslatingJavacPhaseTracer tracer = TranslatingJavacPhaseTracer.setupTracing(invokingRule, context.getClassLoaderCache(), context.getEventSink(), compilationTask, abiValidatingTaskListener);
            // may choke with novel errors that don't occur on the command line.
            AnnotationProcessorFactory processorFactory = new AnnotationProcessorFactory(context.getEventSink(), compiler.getClass().getClassLoader(), context.getClassLoaderCache(), invokingRule)) {
            compilationTask.setProcessors(processorFactory.createProcessors(annotationProcessors));
            // Invoke the compilation and inspect the result.
            isSuccess = compilationTask.call();
        } catch (IOException e) {
            LOG.warn(e, "Unable to close annotation processor class loader. We may be leaking memory.");
        }
    } finally {
        // Clear the tracing interface so we have no chance of leaking it to code that shouldn't
        // be using it.
        BuckTracing.clearCurrentThreadTracingInterfaceFromJsr199Javac();
    }
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        LOG.debug("javac: %s", DiagnosticPrettyPrinter.format(diagnostic));
    }
    List<Diagnostic<? extends JavaFileObject>> cleanDiagnostics = DiagnosticCleaner.clean(diagnostics.getDiagnostics());
    if (isSuccess) {
        context.getUsedClassesFileWriter().writeFile(context.getProjectFilesystem(), context.getObjectMapper());
        return 0;
    } else {
        if (context.getVerbosity().shouldPrintStandardInformation()) {
            int numErrors = 0;
            int numWarnings = 0;
            for (Diagnostic<? extends JavaFileObject> diagnostic : cleanDiagnostics) {
                Diagnostic.Kind kind = diagnostic.getKind();
                if (kind == Diagnostic.Kind.ERROR) {
                    ++numErrors;
                    handleMissingSymbolError(invokingRule, diagnostic, context);
                } else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) {
                    ++numWarnings;
                }
                context.getStdErr().println(DiagnosticPrettyPrinter.format(diagnostic));
            }
            if (numErrors > 0 || numWarnings > 0) {
                context.getStdErr().printf("Errors: %d. Warnings: %d.\n", numErrors, numWarnings);
            }
        }
        return 1;
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) TranslatingJavacPhaseTracer(com.facebook.buck.jvm.java.tracing.TranslatingJavacPhaseTracer) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Aggregations

JavaCompiler (javax.tools.JavaCompiler)101 StandardJavaFileManager (javax.tools.StandardJavaFileManager)43 JavaFileObject (javax.tools.JavaFileObject)39 File (java.io.File)31 DiagnosticCollector (javax.tools.DiagnosticCollector)24 ArrayList (java.util.ArrayList)22 JavacTask (com.sun.source.util.JavacTask)20 IOException (java.io.IOException)17 CompilationTask (javax.tools.JavaCompiler.CompilationTask)16 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)15 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)11 Diagnostic (javax.tools.Diagnostic)11 PrintWriter (java.io.PrintWriter)9 Test (org.junit.Test)9 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 FileOutputStream (java.io.FileOutputStream)5 StringWriter (java.io.StringWriter)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStream (java.io.OutputStream)4