Example usage for javax.tools StandardJavaFileManager getJavaFileObjectsFromFiles

List of usage examples for javax.tools StandardJavaFileManager getJavaFileObjectsFromFiles

Introduction

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

Prototype

Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files);

Source Link

Document

Returns file objects representing the given files.

Usage

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

public void compile(String fileName) {
    ClassLoader cl = this.getClass().getClassLoader();
    List<URL> classpath = new ArrayList<URL>();
    if (cl instanceof URLClassLoader) {
        URLClassLoader cl2 = (URLClassLoader) cl;
        for (URL jar : cl2.getURLs()) {
            classpath.add(jar);//  ww w .ja  va2  s .c  o  m
        }
    }
    String classPath = System.getProperty("java.class.path");
    for (String path : classPath.split(File.pathSeparator)) {
        try {
            classpath.add(new URL("file:" + path));
        } catch (MalformedURLException e) {
            System.err.println("Wrong url: " + e.getMessage());
            e.printStackTrace();
        }
    }

    StringBuffer sb = new StringBuffer();
    for (URL jar : classpath) {
        if (SystemUtils.IS_OS_WINDOWS == false) {
            sb.append(jar.getPath());
            sb.append(File.pathSeparatorChar);
        } else {
            sb.append(jar.getPath().substring(1));
            sb.append(File.pathSeparatorChar);
        }
    }
    String ops[] = new String[] { "-classpath", sb.toString() };

    List<String> opsIter = new ArrayList<String>();
    try {
        for (String s : ops) {
            // XXX test usage, removed use of deprecated method
            // ((ArrayList) opsIter).add(URLDecoder.decode(s));
            ((ArrayList) opsIter).add(URLDecoder.decode(s, Charset.forName("UTF-8").toString()));
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    File[] files1 = new File[1];
    files1[0] = new File(fileName);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files1));

    compiler.getTask(null, fileManager, null, opsIter, null, compilationUnits1).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:plaid.compilerjava.CompilerCore.java

private void generateCode(List<CompilationUnit> cus, final PackageRep plaidpath) throws Exception {
    if (cc.isVerbose()) {
        System.out.println("Generating code.");
    }//from  w  w w  . j a v a2 s .c o m

    final List<File> allFiles = new ArrayList<File>();
    ExecutorService taskPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (final CompilationUnit cu : cus) {
        if (!cc.forceRecompile()) {
            boolean rebuild = false;
            for (Decl d : cu.getDecls()) {
                //System.out.println(d);
                StringBuilder packageName = new StringBuilder();
                for (String s : cu.getPackageName()) {
                    packageName.append(s);
                    packageName.append(System.getProperty("file.separator"));
                }
                File targetFile = new File(cc.getTempDir() + System.getProperty("file.separator") + packageName
                        + d.getName() + ".java");
                if (!targetFile.exists() || targetFile.lastModified() < cu.getSourceFile().lastModified()) {
                    rebuild = true;
                    break;
                }
            }
            if (!rebuild) {
                if (cc.isVerbose()) {
                    System.out.println("file up-to-date : " + cu.getSourceFile());
                }
                continue;
            }
            if (cc.isVerbose()) {
                System.out.println("Rebuild: " + cu.getSourceFile());
            }
        }
        Callable<Object> task = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                try {
                    if (cc.isVerbose())
                        System.out.println("Generating code for:\n" + cu);
                    List<File> fileList = cu.codegen(cc, plaidpath);

                    synchronized (allFiles) {
                        allFiles.addAll(fileList);
                    }
                } catch (PlaidException p) {
                    System.err.println("Error while compiling " + cu.getSourceFile().toString() + ":");
                    System.err.println("");
                    printExceptionInformation(p);
                }
                return null;
            }
        };
        taskPool.submit(task);
    }
    taskPool.shutdown();
    while (!taskPool.isTerminated()) {
        taskPool.awaitTermination(1, TimeUnit.MINUTES);
    }

    if (!cc.isKeepTemporaryFiles()) {
        for (File f : allFiles) {
            f.deleteOnExit();
        }
    }

    if (cc.isVerbose()) {
        System.out.println("invoke Java compiler");
    }
    if (cc.isInvokeCompiler() && allFiles.size() > 0) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(allFiles);

        List<String> optionList = new ArrayList<String>();
        optionList.addAll(Arrays.asList("-target", "1.5"));
        // Set compiler's classpath to be same as the runtime's
        optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));
        // TODO: Add a separate compiler flag for this.
        optionList.addAll(Arrays.asList("-d", cc.getOutputDir()));
        //         optionList.add("-verbose");

        // Invoke the compiler
        CompilationTask task = compiler.getTask(null, null, null, optionList, null, fileObjects);
        Boolean resultCode = task.call();
        if (!resultCode.booleanValue())
            throw new RuntimeException("Error while compiling generated Java files.");
    }
}