Example usage for javax.tools JavaCompiler getStandardFileManager

List of usage examples for javax.tools JavaCompiler getStandardFileManager

Introduction

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

Prototype

StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Locale locale, Charset charset);

Source Link

Document

Returns a new instance of the standard file manager implementation for this tool.

Usage

From source file:org.apache.pig.test.TestJobControlCompiler.java

/**
 * creates a jar containing a UDF not in the current classloader
 * @param jarFile the jar to create/*  w w w .  j av  a  2s  . co  m*/
 * @return the name of the class created (in the default package)
 * @throws IOException
 * @throws FileNotFoundException
 */
private String createTestJar(File jarFile) throws IOException, FileNotFoundException {

    // creating the source .java file
    File javaFile = File.createTempFile("TestUDF", ".java");
    javaFile.deleteOnExit();
    String className = javaFile.getName().substring(0, javaFile.getName().lastIndexOf('.'));
    FileWriter fw = new FileWriter(javaFile);
    try {
        fw.write("import org.apache.pig.EvalFunc;\n");
        fw.write("import org.apache.pig.data.Tuple;\n");
        fw.write("import java.io.IOException;\n");
        fw.write("public class " + className + " extends EvalFunc<String> {\n");
        fw.write("  public String exec(Tuple input) throws IOException {\n");
        fw.write("    return \"test\";\n");
        fw.write("  }\n");
        fw.write("}\n");
    } finally {
        fw.close();
    }

    // compiling it
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFile);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits1);
    task.call();

    // here is the compiled file
    File classFile = new File(javaFile.getParentFile(), className + ".class");
    Assert.assertTrue(classFile.exists());

    // putting it in the jar
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile));
    try {
        jos.putNextEntry(new ZipEntry(classFile.getName()));
        try {
            InputStream testClassContentIS = new FileInputStream(classFile);
            try {
                byte[] buffer = new byte[64000];
                int n;
                while ((n = testClassContentIS.read(buffer)) != -1) {
                    jos.write(buffer, 0, n);
                }
            } finally {
                testClassContentIS.close();
            }
        } finally {
            jos.closeEntry();
        }
    } finally {
        jos.close();
    }

    return className;
}

From source file:org.apache.pig.test.TestRegisteredJarVisibility.java

private static List<File> compile(File[] javaFiles) {
    LOG.info("Compiling: " + Arrays.asList(javaFiles));

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFiles);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null,
            compilationUnits1);//from   w w  w  .j a v a 2 s  . c  o m
    task.call();

    List<File> classFiles = Lists.newArrayList();
    for (File javaFile : javaFiles) {
        File classFile = new File(javaFile.getAbsolutePath().replace(".java", ".class"));
        classFile.deleteOnExit();
        Assert.assertTrue(classFile.exists());
        classFiles.add(classFile);
        LOG.info("Created " + classFile.getAbsolutePath());
    }

    return classFiles;
}

From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap)
        throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFiles = new ArrayList<>();
    for (JarContents jarContents : sourceFileToJarMap.values()) {
        sourceFiles.addAll(jarContents.sourceFiles);
    }/*from   w  ww .  ja v a2s  .c  o m*/

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString())));

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles);

    boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    if (!compiled) {
        throw new RuntimeException("failed to compile");
    }

    for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");

        JarOutputStream target = new JarOutputStream(
                new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()),
                manifest);
        List<String> classesForJar = new ArrayList<>();
        for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) {
            //split the file on dot to get the filename from FILENAME.java
            String fileName = sourceFile.getName().split("\\.")[0];
            classesForJar.add(fileName);
        }

        File dir = new File(outputDir);
        File[] directoryListing = dir.listFiles();
        for (File compiledClass : directoryListing) {
            String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0];
            if (classesForJar.contains(classFileName)) {
                addFileToJar(compiledClass, target);
            }
        }

        for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) {
            addFileToJar(propertiesFile, target);
        }

        target.close();

    }
    //delete non jar files
    File dir = new File(outputDir);
    File[] directoryListing = dir.listFiles();
    for (File file : directoryListing) {
        String extension = file.getName().split("\\.")[1];
        if (!extension.equals("jar")) {
            file.delete();
        }
    }

    Map<String, String> jarMap = new HashMap<>();
    jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME);
    jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME);
    return jarMap;
}

From source file:org.apache.sqoop.orm.CompilationManager.java

/**
 * Compile the .java files into .class files via embedded javac call.
 * On success, move .java files to the code output dir.
 *//* www. j  a va 2s .co m*/
public void compile() throws IOException {
    List<String> args = new ArrayList<String>();

    // ensure that the jar output dir exists.
    String jarOutDir = options.getJarOutputDir();
    File jarOutDirObj = new File(jarOutDir);
    if (!jarOutDirObj.exists()) {
        boolean mkdirSuccess = jarOutDirObj.mkdirs();
        if (!mkdirSuccess) {
            LOG.debug("Warning: Could not make directories for " + jarOutDir);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + jarOutDir);
    }

    // Make sure jarOutDir ends with a '/'.
    if (!jarOutDir.endsWith(File.separator)) {
        jarOutDir = jarOutDir + File.separator;
    }

    // find hadoop-*-core.jar for classpath.
    String coreJar = findHadoopCoreJar();
    if (null == coreJar) {
        // Couldn't find a core jar to insert into the CP for compilation.  If,
        // however, we're running this from a unit test, then the path to the
        // .class files might be set via the hadoop.alt.classpath property
        // instead. Check there first.
        String coreClassesPath = System.getProperty("hadoop.alt.classpath");
        if (null == coreClassesPath) {
            // no -- we're out of options. Fail.
            throw new IOException("Could not find hadoop core jar!");
        } else {
            coreJar = coreClassesPath;
        }
    }

    // find sqoop jar for compilation classpath
    String sqoopJar = Jars.getSqoopJarPath();
    if (null != sqoopJar) {
        sqoopJar = File.pathSeparator + sqoopJar;
    } else {
        LOG.warn("Could not find sqoop jar; child compilation may fail");
        sqoopJar = "";
    }

    String curClasspath = System.getProperty("java.class.path");

    args.add("-sourcepath");
    args.add(jarOutDir);

    args.add("-d");
    args.add(jarOutDir);

    args.add("-classpath");
    args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (null == compiler) {
        LOG.error("It seems as though you are running sqoop with a JRE.");
        LOG.error("Sqoop requires a JDK that can compile Java code.");
        LOG.error("Please install a JDK and set $JAVA_HOME to use it.");
        throw new IOException("Could not start Java compiler.");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    ArrayList<String> srcFileNames = new ArrayList<String>();
    for (String srcfile : sources) {
        srcFileNames.add(jarOutDir + srcfile);
        LOG.debug("Adding source file: " + jarOutDir + srcfile);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Invoking javac with args:");
        for (String arg : args) {
            LOG.debug("  " + arg);
        }
    }

    Iterable<? extends JavaFileObject> srcFileObjs = fileManager.getJavaFileObjectsFromStrings(srcFileNames);
    JavaCompiler.CompilationTask task = compiler.getTask(null, // Write to stderr
            fileManager, null, // No special diagnostic handling
            args, null, // Compile all classes in the source compilation units
            srcFileObjs);

    boolean result = task.call();
    if (!result) {
        throw new IOException("Error returned by javac");
    }

    // Where we should move source files after compilation.
    String srcOutDir = new File(options.getCodeOutputDir()).getAbsolutePath();
    if (!srcOutDir.endsWith(File.separator)) {
        srcOutDir = srcOutDir + File.separator;
    }

    // Move these files to the srcOutDir.
    for (String srcFileName : sources) {
        String orig = jarOutDir + srcFileName;
        String dest = srcOutDir + srcFileName;
        File fOrig = new File(orig);
        File fDest = new File(dest);
        File fDestParent = fDest.getParentFile();
        if (null != fDestParent && !fDestParent.exists()) {
            if (!fDestParent.mkdirs()) {
                LOG.error("Could not make directory: " + fDestParent);
            }
        }
        try {
            FileUtils.moveFile(fOrig, fDest);
        } catch (IOException e) {
            LOG.debug("Could not rename " + orig + " to " + dest, e);
        }
    }
}

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

/**
 * Compiles the given source code into java bytecode
 *//*from  ww w  .  j  a 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());
    }
}

From source file:org.apache.sysml.runtime.codegen.CodegenUtils.java

private static Class<?> compileClassJavac(String name, String src) {
    try {//from w  w  w .j  a v  a  2  s  .com
        //create working dir on demand
        if (_workingDir == null)
            createWorkingDir();

        //write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);

        //get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");

        //prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

        //prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(ftmp));

        //prepare class path 
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);

        //compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();

        //output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics())
            if (tmp.getKind() == Kind.ERROR)
                System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);

        //dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir },
                    CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        LOG.error("Failed to compile class " + name + ": \n" + src);
        throw new DMLRuntimeException("Failed to compile class " + name + ".", ex);
    }
}

From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java

/**
 * F2 test.//from  w w  w  .ja v a2s  . co m
 * 
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws MalformedURLException
 */
@Test
public void f2Test()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within
    // in it...
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar");

    File helloWorldJava = new File(System.getProperty("user.dir")
            + "/generated-code/caserunners/org/bigtester/ate/model/project/CaseRunner8187856223134148550.java");

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);
    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        System.out.println("Yipe");
        // Create a new custom class loader, pointing to the directory that
        // contains the compiled
        // classes, this should point to the top of the package structure!
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() });
        // Load the class from the classloader by name....
        Class<?> loadedClass = classLoader
                .loadClass("org.bigtester.ate.model.project.CaseRunner8187856223134148550");
        // Create a new instance...
        Object obj = loadedClass.newInstance();
        // Santity check
        if (obj instanceof IRunTestCase) {
            ((IRunTestCase) obj).setCurrentExecutingTCName("test case name example");
            Assert.assertEquals(((IRunTestCase) obj).getCurrentExecutingTCName(), "test case name example");
            System.out.println("pass");
        }
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(),
                    diagnostic.getSource().toUri());
        }
    }
}

From source file:org.commonjava.test.compile.CompilerFixture.java

public CompilerResult compile(final File directory, final CompilerFixtureConfig config) throws IOException {
    if (directory == null || !directory.isDirectory()) {
        return null;
    }//from w  w  w . j a v  a  2  s .  c om

    final File target = temp.newFolder(directory.getName() + "-classes");

    final List<File> sources = scan(directory, "**/*.java");

    final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
    final Set<JavaFileObject> objects = new HashSet<>();

    for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(sources)) {
        objects.add(jfo);
    }

    final DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();

    final List<String> options = new ArrayList<>(Arrays.asList("-g", "-d", target.getCanonicalPath()));

    options.addAll(config.getExtraOptions());

    final StringBuilder sp = new StringBuilder();
    sp.append(directory.getCanonicalPath()).append(';').append(target.getCanonicalPath());

    File generatedSourceDir = null;

    final List<String> procOptions = new ArrayList<>(options);
    procOptions.add("-proc:only");

    final Set<File> seenSources = new HashSet<>(sources);
    Boolean result = Boolean.TRUE;

    final List<Class<? extends AbstractProcessor>> annoProcessors = config.getAnnotationProcessors();
    if (!annoProcessors.isEmpty()) {
        final StringBuilder sb = new StringBuilder();
        for (final Class<? extends AbstractProcessor> annoProcessor : annoProcessors) {
            if (sb.length() > 0) {
                sb.append(",");
            }

            sb.append(annoProcessor.getCanonicalName());
        }

        procOptions.add("-processor");
        procOptions.add(sb.toString());

        generatedSourceDir = temp.newFolder(directory.getName() + "-generated-sources");
        procOptions.add("-s");
        procOptions.add(generatedSourceDir.getCanonicalPath());

        sp.append(';').append(generatedSourceDir.getCanonicalPath());

        procOptions.add("-sourcepath");
        procOptions.add(sp.toString());

        int pass = 1;
        List<File> nextSources;
        do {
            logger.debug("pass: {} Compiling/processing generated sources with: '{}':\n  {}\n", pass,
                    new JoinLogString(procOptions, ", "), new JoinLogString(sources, "\n  "));

            for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
                objects.add(jfo);
            }

            final CompilationTask task = javac.getTask(null, fileManager, diags, procOptions, null, objects);
            result = task.call();

            nextSources = scan(generatedSourceDir, "**/*.java");

            logger.debug("\n\nNewly scanned sources:\n  {}\n\nPreviously seen sources:\n  {}\n\n",
                    new JoinLogString(nextSources, "\n  "), new JoinLogString(seenSources, "\n  "));
            nextSources.removeAll(seenSources);
            seenSources.addAll(nextSources);
            pass++;
        } while (pass < config.getMaxAnnotationProcessorPasses() && !nextSources.isEmpty());
    }

    if (result) {
        options.add("-sourcepath");
        options.add(sp.toString());

        options.add("-proc:none");

        for (final JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(seenSources)) {
            objects.add(jfo);
        }

        final CompilationTask task = javac.getTask(null, fileManager, diags, options, null, objects);
        result = task.call();

        logger.debug("Compiled classes:\n  {}\n\n", new JoinLogString(scan(target, "**/*.class"), "\n  "));
    } else {
        logger.warn("Annotation processing must have failed. Skipping compilation step.");
    }

    for (final Diagnostic<? extends JavaFileObject> diag : diags.getDiagnostics()) {
        logger.error(String.valueOf(diag));
    }

    final CompilerResult cr = new CompilerResultBuilder().withClasses(target).withDiagnosticCollector(diags)
            .withGeneratedSources(generatedSourceDir).withResult(result).build();

    results.add(cr);
    return cr;
}

From source file:org.deventropy.shared.utils.ClassUtilTest.java

@Test
public void testCallerClassloader() throws Exception {

    // Write the source file - see
    // http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class
    final File sourceFolder = workingFolder.newFolder();
    // Prepare source somehow.
    final String source = "package test; public class Test { }";
    // Save source in .java file.
    final File sourceFile = new File(sourceFolder, "test/Test.java");
    sourceFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(sourceFile, source, "UTF-8");

    // Compile the file
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
    compiler.getTask(null, fileManager, null, null, null, compilationUnit).call();

    // Create the class loader
    final URLClassLoader urlcl = new URLClassLoader(new URL[] { sourceFolder.toURI().toURL() });
    final Class<?> loadedClass = urlcl.loadClass("test.Test");

    final ContextClNullingObject testObj = new ContextClNullingObject(loadedClass.newInstance());
    final Thread worker = new Thread(testObj);
    worker.start();//w  ww.  java  2 s  .  c  om
    worker.join();

    assertEquals(urlcl, testObj.getReturnedCl());

    urlcl.close();
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Compila el java en tiempo real// w  w  w. jav  a2 s .c om
 *
 * @return xito de la operacin
 */
protected boolean compileEDMCrossWalk() {
    boolean status = false;

    SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(canonicalCrosswalkName,
            edmCrossWalkContent);
    JavaFileObject javaFileObjects[] = new JavaFileObject[] { fileObject };

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

    // libreras necesarias para linkar con el fuente a compilar
    String myInstallerPackagesDirPath = myInstallerDirPath + fileSeparator + "packages" + fileSeparator;
    StringBuilder jars = (fileSeparator.equals("\\"))
            ? new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar;")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar;")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar")
            : new StringBuilder(myInstallerPackagesDirPath).append("dspace-api-1.7.2.jar:")
                    .append(myInstallerPackagesDirPath).append("jdom-1.0.jar:")
                    .append(myInstallerPackagesDirPath).append("oaicat-1.5.48.jar");

    String[] compileOptions = new String[] { "-d", myInstallerWorkDirPath, "-source", "1.6", "-target", "1.6",
            "-cp", jars.toString() };
    Iterable<String> compilationOptionss = Arrays.asList(compileOptions);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

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

    StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);

    JavaCompiler.CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics,
            compilationOptionss, null, compilationUnits);

    status = compilerTask.call();

    if (!status) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            installerEDMDisplay
                    .showMessage("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic);
        }
    }

    try {
        stdFileManager.close();
    } catch (IOException e) {
        showException(e);
    }
    return status;
}