Example usage for javax.tools ForwardingJavaFileManager ForwardingJavaFileManager

List of usage examples for javax.tools ForwardingJavaFileManager ForwardingJavaFileManager

Introduction

In this page you can find the example usage for javax.tools ForwardingJavaFileManager ForwardingJavaFileManager.

Prototype

protected ForwardingJavaFileManager(M fileManager) 

Source Link

Document

Creates a new instance of ForwardingJavaFileManager.

Usage

From source file:net.cliseau.composer.javacor.MissingToolException.java

/**
 * Compiles the unit startup file from Java source to Java bytecode.
 *
 * This compiles the startup file. During this process, multiple class files
 * may be generated even though only a single input file to compile is
 * specified. The reason for this is that classes other than the main class
 * may be defined in the single file and are written to distinct class
 * files. All created files are collected and returned by the method.
 *
 * @param startupFile The file to be compiled.
 * @param startupDependencies Names of classpath entries to use for compilation.
 * @return List of names of created (class) files during compilation.
 * @exception UnitGenerationException Thrown when finding a Java compiler failed.
 *//*w  ww  .j  a v a  2 s.  co  m*/
private LinkedList<String> compile(final File startupFile, final Collection<String> startupDependencies)
        throws MissingToolException, InvalidConfigurationException {
    // code inspired by the examples at
    //   http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html
    final LinkedList<String> createdFiles = new LinkedList<String>();

    // set the file manager, which records the written files
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new MissingToolException("Could not find system Java compiler.");
    }
    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, null, null);
    JavaFileManager fileManager = new ForwardingJavaFileManager<StandardJavaFileManager>(stdFileManager) {
        /**
         * Collect the list of all output (class) files.
         *
         * Besides its side-effect on the createdFiles list of the containing
         * method, this method is functionally equivalent to its superclass
         * version.
         */
        public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className,
                JavaFileObject.Kind kind, FileObject sibling) throws IOException {
            JavaFileObject fileForOutput = super.getJavaFileForOutput(location, className, kind, sibling);
            createdFiles.addLast(fileForOutput.getName());
            return fileForOutput;
        }
    };

    // set the files to compile
    Iterable<? extends JavaFileObject> compilationUnits = stdFileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(startupFile));

    // do the actual compilation
    ArrayList<String> compileParams = new ArrayList<String>(2);

    boolean verbose = org.apache.log4j.Level.DEBUG.isGreaterOrEqual(config.getInstantiationLogLevel());
    if (verbose)
        compileParams.add("-verbose");

    compileParams
            .addAll(Arrays.asList("-classpath", StringUtils.join(startupDependencies, File.pathSeparator)));
    if (!compiler.getTask(null, fileManager, null, compileParams, null, compilationUnits).call()) {
        // could not compile all files without error
        //TODO: throw an exception ... see where to get the required information from
    }
    return createdFiles;
}

From source file:org.apache.struts2.JSPLoader.java

/**
 * Compiles the given source code into java bytecode
 *///from w  ww.  ja  va 2s. c  o  m
private void compileJava(String className, final String source, Set<String> extraClassPath) throws IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("Compiling [#0], source: [#1]", className, source);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    //the generated bytecode is fed to the class loader
    JavaFileManager jfm = new ForwardingJavaFileManager<StandardJavaFileManager>(
            compiler.getStandardFileManager(diagnostics, null, null)) {

        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind,
                FileObject sibling) throws IOException {
            MemoryJavaFileObject fileObject = new MemoryJavaFileObject(name, kind);
            classLoader.addMemoryJavaFileObject(name, fileObject);
            return fileObject;
        }
    };

    //read java source code from memory
    String fileName = className.replace('.', '/') + ".java";
    SimpleJavaFileObject sourceCodeObject = new SimpleJavaFileObject(toURI(fileName),
            JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors)
                throws IOException, IllegalStateException, UnsupportedOperationException {
            return source;
        }

    };

    //build classpath
    //some entries will be added multiple times, hence the set
    List<String> optionList = new ArrayList<String>();
    Set<String> classPath = new HashSet<String>();

    FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class)
            .getFileManager();

    //find available jars
    ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
    UrlSet urlSet = new UrlSet(classLoaderInterface);

    //find jars
    List<URL> urls = urlSet.getUrls();

    for (URL url : urls) {
        URL normalizedUrl = fileManager.normalizeToFileProtocol(url);
        File file = FileUtils.toFile(ObjectUtils.defaultIfNull(normalizedUrl, url));
        if (file.exists())
            classPath.add(file.getAbsolutePath());
    }

    //these should be in the list already, but I am feeling paranoid
    //this jar
    classPath.add(getJarUrl(EmbeddedJSPResult.class));
    //servlet api
    classPath.add(getJarUrl(Servlet.class));
    //jsp api
    classPath.add(getJarUrl(JspPage.class));

    try {
        Class annotationsProcessor = Class.forName("org.apache.AnnotationProcessor");
        classPath.add(getJarUrl(annotationsProcessor));
    } catch (ClassNotFoundException e) {
        //ok ignore
    }

    //add extra classpath entries (jars where tlds were found will be here)
    for (Iterator<String> iterator = extraClassPath.iterator(); iterator.hasNext();) {
        String entry = iterator.next();
        classPath.add(entry);
    }

    String classPathString = StringUtils.join(classPath, File.pathSeparator);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Compiling [#0] with classpath [#1]", className, classPathString);
    }

    optionList.addAll(Arrays.asList("-classpath", classPathString));

    //compile
    JavaCompiler.CompilationTask task = compiler.getTask(null, jfm, diagnostics, optionList, null,
            Arrays.asList(sourceCodeObject));

    if (!task.call()) {
        throw new StrutsException("Compilation failed:" + diagnostics.getDiagnostics().get(0).toString());
    }
}