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:neembuu.uploader.zip.generator.NUCompiler.java

/**
 * Compile all the given files in the given build directory.
 *
 * @param files The array of files to compiles.
 * @param buildDirectory The build directory in which put all the compiled
 * files.//  www  .j  a v a2s  . com
 * @throws FileNotFoundException
 * @throws IOException
 */
private void compileFiles(File[] files, File buildDirectory) throws FileNotFoundException, IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    buildDirectory.mkdir();

    /**/
    List<String> optionList = new ArrayList<String>();
    // set compiler's classpath to be same as the runtime's
    //optionList.addAll(Arrays.asList("-classpath", "C:\\neembuuuploader\\modules\\libs\\jsoup-1.7.2.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-codec-1.6.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\commons-logging-1.1.1.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpclient-cache-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpcore-4.2.4.jar;C:\\neembuuuploader\\modules\\libs\\ApacheHttpComponent-4.2.5\\httpmime-4.2.5.jar;C:\\neembuuuploader\\modules\\libs\\json-java.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-utils\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-api\\build\\classes;C:\\neembuuuploader\\modules\\neembuu-uploader-interfaces-abstractimpl\\build\\classes;C:\\neembuuuploader\\modules\\libs\\neembuu-now-api-ui.jar;C:\\neembuuuploader\\modules\\libs\\neembuu-release1-ui-mc.jar;C:\\neembuuuploader\\modules\\neembuu-uploader-uploaders\\build\\classes;C:\\neembuuuploader\\modules\\NeembuuUploader\\build\\classes"));
    optionList.addAll(Arrays.asList("-classpath", classPath));
    optionList.addAll(Arrays.asList("-d", buildDirectory.getAbsolutePath()));

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files));

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

    JavaCompiler.CompilationTask task = compiler.getTask(null, null, diagnostics, optionList, null,
            compilationUnits);
    boolean result = task.call();

    if (result) {
        System.out.println("Compilation was successful");
    } else {
        System.out.println("Compilation failed");

        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
        }
    }
}

From source file:gool.parser.java.JavaParser.java

/**
 * if the parser is called on a directory, wrap it into a compilation unit,
 * and call the parser on that file.//from   www .  j a  va  2  s .co m
 */
public Collection<ClassDef> parseGoolFiles(Platform defaultPlatform, List<File> dirs) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(dirs);
    return parseGool(defaultPlatform, compilationUnits);
}

From source file:com.qwazr.compiler.JavaCompiler.java

private void compile(javax.tools.JavaCompiler compiler, Collection<File> javaFiles) throws IOException {
    final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    try {//from   www . j  a  v a2 s . c  om
        Iterable<? extends JavaFileObject> sourceFileObjects = fileManager
                .getJavaFileObjectsFromFiles(javaFiles);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        final List<String> options = new ArrayList<String>();
        if (classPath != null) {
            options.add("-classpath");
            options.add(classPath);
        }
        options.add("-d");
        options.add(javaClassesDirectory.getAbsolutePath());
        options.add("-sourcepath");
        options.add(javaSourceDirectory.getAbsolutePath());
        javax.tools.JavaCompiler.CompilationTask task = compiler.getTask(pw, fileManager, diagnostics, options,
                null, sourceFileObjects);
        if (!task.call()) {
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics())
                pw.format("Error on line %d in %s%n%s%n", diagnostic.getLineNumber(),
                        diagnostic.getSource().toUri(), diagnostic.getMessage(null));
            pw.flush();
            pw.close();
            sw.close();
            throw new IOException(sw.toString());
        }
    } finally {
        IOUtils.close(fileManager);
    }
}

From source file:cop.maven.plugins.AbstractRestToRamlMojo.java

protected void executeWithExceptionsHandled() throws Exception {
    evaluator = new PluginParameterExpressionEvaluator(session, mojoExecution);

    checkOutputDirectoryExists();//w ww.  ja  v a2  s.c  o  m
    checkFileName();

    FileUtils.write(new File(out, Config.YAML), readConfiguration(), encoding);

    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(null, null,
            Charset.forName(encoding));
    List<JavaFileObject> compilationUnits = StreamSupport
            .stream(fileManager.getJavaFileObjectsFromFiles(getSourceFiles()).spliterator(), true)
            .collect(Collectors.toList());

    if (compilationUnits.isEmpty())
        getLog().warn("no source file(s) detected! Processor task will be skipped");
    else {
        JavaCompiler.CompilationTask task = COMPILER.getTask(null, fileManager, null, getCompilerOptions(),
                null, compilationUnits);

        if (!task.call())
            throw new Exception("error during compilation");
    }
}

From source file:de.uni_koblenz.jgralab.utilities.tgschema2java.TgSchema2Java.java

public void compile() throws Exception {
    String packageFolder = schema.getPathName();
    File folder = new File(commitPath + File.separator + packageFolder);
    List<File> files1 = findFilesInDirectory(folder);

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

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
    ArrayList<String> options = new ArrayList<>();
    if (classpath != null) {
        options.add("-cp");
        options.add(classpath);//from   w ww . ja  v a 2s .  c  o  m
    }
    System.out.print("Starting compilation....");
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    System.out.println("finished");
}

From source file:nl.elucidator.patterns.builder.annotations.processor.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p/>/*from w w  w  .  j a  va2  s.c  om*/
 * The compilation units and all their dependencies are expected to be on the classpath.
 *
 * @param compilationUnitPaths the paths of the source files to compile, as would be expected
 *                             by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     * 
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
        //Nothing to do
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:org.mule.devkit.apt.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>/*  w  w  w  . ja va 2s. com*/
 * The compilation units and all their dependencies are expected to be on the classpath.
 *
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected
 *            by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 *
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     *
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:com.qrmedia.commons.test.annotation.processing.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>// w  w w  .  j a v  a 2s . co  m
 * The compilation units and all their dependencies are expected to be on the classpath.
 * 
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected
 *            by {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation,
 *         as demonstrated in the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 * 
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert (compilationUnitPaths != null);

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names"
     * option (which could, in principle, be used instead of compilation
     * units for annotation processing) isn't useful in this case because
     * only annotations on the classes being compiled are accessible.
     * 
     * Information about the classes being compiled (such as what they are annotated
     * with) is *not* available via the RoundEnvironment. However, if these classes
     * are annotations, they certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"),
            null, fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
    }

    return diagnosticCollector.getDiagnostics();
}

From source file:ar.edu.taco.TacoMain.java

/**
 * /*from w  ww. j a v a 2 s . com*/
 * @param configFile
 * @param overridingProperties
 *            Properties that overrides properties file's values
 */

public TacoAnalysisResult run(String configFile, Properties overridingProperties)
        throws IllegalArgumentException {

    AlloyTyping varsEncodingValueOfArithmeticOperationsInObjectInvariants = new AlloyTyping();
    List<AlloyFormula> predsEncodingValueOfArithmeticOperationsInObjectInvariants = new ArrayList<AlloyFormula>();

    if (configFile == null) {
        throw new IllegalArgumentException("Config file not found, please verify option -cf");
    }

    List<JCompilationUnitType> compilation_units = null;
    String classToCheck = null;
    String methodToCheck = null;

    // Start configurator
    JDynAlloyConfig.reset();
    JDynAlloyConfig.buildConfig(configFile, overridingProperties);

    List<JDynAlloyModule> jdynalloy_modules = new ArrayList<JDynAlloyModule>();
    SimpleJmlToJDynAlloyContext simpleJmlToJDynAlloyContext;
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JMLPARSER_ENABLED,
            TacoConfigurator.JMLPARSER_ENABLED_DEFAULT)) {
        // JAVA PARSING
        String sourceRootDir = TacoConfigurator.getInstance()
                .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);

        if (TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD) == null) {
            throw new TacoException(
                    "Config key 'CLASS_TO_CHECK_FIELD' is mandatory. Please check your config file or add the -c parameter");
        }
        List<String> files = new ArrayList<String>(Arrays.asList(JDynAlloyConfig.getInstance().getClasses()));

        classToCheck = TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD);
        String[] splitName = classToCheck.split("_");
        classToCheck = "";
        for (int idx = 0; idx < splitName.length - 2; idx++) {
            classToCheck += splitName[idx] + "_";
        }

        if (splitName.length >= 2)
            classToCheck += splitName[splitName.length - 2] + "Instrumented_";
        classToCheck += splitName[splitName.length - 1];

        if (!files.contains(classToCheck)) {
            files.add(classToCheck);
        }

        List<String> processedFileNames = new ArrayList<String>();
        for (String file : files) {
            String begin = file.substring(0, file.lastIndexOf('.'));
            String end = file.substring(file.lastIndexOf('.'), file.length());
            processedFileNames.add(begin + "Instrumented" + end);
        }

        files = processedFileNames;

        JmlParser.getInstance().initialize(sourceRootDir,
                System.getProperty("user.dir") + System.getProperty("file.separator") + "bin" /* Unused */,
                files);
        compilation_units = JmlParser.getInstance().getCompilationUnits();
        // END JAVA PARSING

        // SIMPLIFICATION
        JmlStage aJavaCodeSimplifier = new JmlStage(compilation_units);
        aJavaCodeSimplifier.execute();
        JmlToSimpleJmlContext jmlToSimpleJmlContext = aJavaCodeSimplifier.getJmlToSimpleJmlContext();
        List<JCompilationUnitType> simplified_compilation_units = aJavaCodeSimplifier
                .get_simplified_compilation_units();
        // END SIMPLIFICATION

        // JAVA TO JDYNALLOY TRANSLATION
        SimpleJmlStage aJavaToDynJAlloyTranslator = new SimpleJmlStage(simplified_compilation_units);
        aJavaToDynJAlloyTranslator.execute();
        // END JAVA TO JDYNALLOY TRANSLATION
        simpleJmlToJDynAlloyContext = aJavaToDynJAlloyTranslator.getSimpleJmlToJDynAlloyContext();
        varsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getVarsEncodingValueOfArithmeticOperationsInInvariants();
        predsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getPredsEncodingValueOfArithmeticOperationsInInvariants();

        // JFSL TO JDYNALLOY TRANSLATION
        JfslStage aJfslToDynJAlloyTranslator = new JfslStage(simplified_compilation_units,
                aJavaToDynJAlloyTranslator.getModules(), jmlToSimpleJmlContext, simpleJmlToJDynAlloyContext);
        aJfslToDynJAlloyTranslator.execute();
        /**/ aJfslToDynJAlloyTranslator = null;
        // END JFSL TO JDYNALLOY TRANSLATION

        // PRINT JDYNALLOY
        JDynAlloyPrinterStage printerStage = new JDynAlloyPrinterStage(aJavaToDynJAlloyTranslator.getModules());
        printerStage.execute();
        /**/ printerStage = null;
        // END PRINT JDYNALLOY

        jdynalloy_modules.addAll(aJavaToDynJAlloyTranslator.getModules());

    } else {
        simpleJmlToJDynAlloyContext = null;
    }

    // JDYNALLOY BUILT-IN MODULES
    PrecompiledModules precompiledModules = new PrecompiledModules();
    precompiledModules.execute();
    jdynalloy_modules.addAll(precompiledModules.getModules());
    // END JDYNALLOY BUILT-IN MODULES

    // JDYNALLOY STATIC FIELDS CLASS
    JDynAlloyModule staticFieldsModule = precompiledModules.generateStaticFieldsModule();
    jdynalloy_modules.add(staticFieldsModule);
    /**/ staticFieldsModule = null;
    // END JDYNALLOY STATIC FIELDS CLASS

    // JDYNALLOY PARSING
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JDYNALLOY_PARSER_ENABLED,
            TacoConfigurator.JDYNALLOY_PARSER_ENABLED_DEFAULT)) {
        log.info("****** START: Parsing JDynAlloy files ****** ");
        JDynAlloyParsingStage jDynAlloyParser = new JDynAlloyParsingStage(jdynalloy_modules);
        jDynAlloyParser.execute();
        jdynalloy_modules.addAll(jDynAlloyParser.getParsedModules());
        /**/ jDynAlloyParser = null;
        log.info("****** END: Parsing JDynAlloy files ****** ");
    } else {
        log.info(
                "****** INFO: Parsing JDynAlloy is disabled (hint enablet it using 'jdynalloy.parser.enabled') ****** ");
    }
    // END JDYNALLOY PARSING

    // JDYNALLOY TO DYNALLOY TRANSLATION
    JDynAlloyStage dynJAlloyToDynAlloyTranslator = new JDynAlloyStage(jdynalloy_modules);
    /**/ jdynalloy_modules = null;
    dynJAlloyToDynAlloyTranslator.execute();
    // BEGIN JDYNALLOY TO DYNALLOY TRANSLATION

    AlloyAnalysisResult alloy_analysis_result = null;
    DynalloyStage dynalloyToAlloy = null;

    // DYNALLOY TO ALLOY TRANSLATION
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.DYNALLOY_TO_ALLOY_ENABLE)) {

        dynalloyToAlloy = new DynalloyStage(dynJAlloyToDynAlloyTranslator.getOutputFileNames());
        dynalloyToAlloy.setSourceJDynAlloy(dynJAlloyToDynAlloyTranslator.getPrunedModules());
        /**/ dynJAlloyToDynAlloyTranslator = null;
        dynalloyToAlloy.execute();
        // DYNALLOY TO ALLOY TRANSLATION

        log.info("****** Transformation process finished ****** ");

        if (TacoConfigurator.getInstance().getNoVerify() == false) {
            // Starts dynalloy to alloy tranlation and alloy verification

            AlloyStage alloy_stage = new AlloyStage(dynalloyToAlloy.get_alloy_filename());
            /**/ dynalloyToAlloy = null;

            alloy_stage.execute();

            alloy_analysis_result = alloy_stage.get_analysis_result();
            /**/ alloy_stage = null;
        }
    }

    TacoAnalysisResult tacoAnalysisResult = new TacoAnalysisResult(alloy_analysis_result);

    String junitFile = null;

    if (TacoConfigurator.getInstance().getGenerateUnitTestCase()
            || TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        // Begin JUNIT Generation Stage
        methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);

        SnapshotStage snapshotStage = new SnapshotStage(compilation_units, tacoAnalysisResult, classToCheck,
                methodToCheck);
        snapshotStage.execute();

        RecoveredInformation recoveredInformation = snapshotStage.getRecoveredInformation();
        recoveredInformation.setFileNameSuffix(StrykerStage.fileSuffix);
        JUnitStage jUnitStage = new JUnitStage(recoveredInformation);
        jUnitStage.execute();
        junitFile = jUnitStage.getJunitFileName();
        //         StrykerStage.fileSuffix++;
        // End JUNIT Generation Stage
    } else {
        log.info("****** JUnit with counterexample values will not be generated. ******* ");
        if (!TacoConfigurator.getInstance().getGenerateUnitTestCase()) {
            log.info("****** generateUnitTestCase=false ******* ");
        }

    }

    if (TacoConfigurator.getInstance().getBuildJavaTrace()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT()) {
            log.info("****** START: Java Trace Generation ****** ");
            DynAlloyCompiler compiler = dynalloyToAlloy.getDynAlloyCompiler();
            JavaTraceStage javaTraceStage = new JavaTraceStage(compiler.getSpecContext(), alloy_analysis_result,
                    false);
            javaTraceStage.execute();
            //            DynAlloySolution dynAlloySolution = javaTraceStage.getDynAlloySolution();
            //            List<TraceStep> trace = dynAlloySolution.getTrace();

            log.info("****** FINISH: Java Trace Generation ****** ");
        }
    } else {
        log.info("****** Java Trace will not be generated. ******* ");
        log.info("****** generateJavaTrace=false ******* ");
    }

    if (TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT() && tacoAnalysisResult
                .get_alloy_analysis_result().getAlloy_solution().getOriginalCommand().startsWith("Check")) {
            log.info("****** START: Stryker ****** ");
            methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);
            String sourceRootDir = TacoConfigurator.getInstance()
                    .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);
            StrykerStage strykerStage = new StrykerStage(compilation_units, sourceRootDir, classToCheck,
                    methodToCheck, configFile, overridingProperties,
                    TacoConfigurator.getInstance().getMaxStrykerMethodsForFile());
            StrykerStage.junitInputs = new Class<?>[50];

            try {
                String currentJunit = null;

                String tempFilename = junitFile.substring(0,
                        junitFile.lastIndexOf(FILE_SEP) + 1) /*+ FILE_SEP*/;
                String packageToWrite = "ar.edu.output.junit";
                String fileClasspath = tempFilename.substring(0, tempFilename
                        .lastIndexOf(new String("ar.edu.generated.junit").replaceAll("\\.", FILE_SEP)));
                fileClasspath = fileClasspath.replaceFirst("generated", "output");
                //               String currentClasspath = System.getProperty("java.class.path")+PATH_SEP+fileClasspath/*+PATH_SEP+System.getProperty("user.dir")+FILE_SEP+"generated"*/;
                currentJunit = editTestFileToCompile(junitFile, classToCheck, packageToWrite, methodToCheck);

                File[] file1 = new File[] { new File(currentJunit) };
                JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
                StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
                Iterable<? extends JavaFileObject> compilationUnit1 = fileManager
                        .getJavaFileObjectsFromFiles(Arrays.asList(file1));
                javaCompiler.getTask(null, fileManager, null, null, null, compilationUnit1).call();
                fileManager.close();
                javaCompiler = null;
                file1 = null;
                fileManager = null;

                ///*mfrias*/      int compilationResult =   javaCompiler.run(null, null, null /*new NullOutputStream()*/, new String[]{"-classpath", currentClasspath, currentJunit});
                ///**/            javaCompiler = null;
                //               if(compilationResult == 0) {
                log.warn("junit counterexample compilation succeded");
                ClassLoader cl = ClassLoader.getSystemClassLoader();
                @SuppressWarnings("resource")
                ClassLoader cl2 = new URLClassLoader(new URL[] { new File(fileClasspath).toURI().toURL() }, cl);
                //                  ClassLoaderTools.addFile(fileClasspath);
                Class<?> clazz = cl2.loadClass(packageToWrite + "." + obtainClassNameFromFileName(junitFile));
                //                  Method[] meth = clazz.getMethods();
                //                  log.info("preparing to add a class containing a test input to the pool... "+packageToWrite+"."+MuJavaController.obtainClassNameFromFileName(junitFile));
                //                  Result result = null;
                //                  final Object oToRun = clazz.newInstance();
                StrykerStage.junitInputs[StrykerStage.indexToLastJUnitInput] = clazz;
                StrykerStage.indexToLastJUnitInput++;
                cl = null;
                cl2 = null;

                //               
                //               } else {
                //                  log.warn("compilation failed");
                //               }
                //                     File originalFile = new File(tempFilename);
                //                     originalFile.delete();

            } catch (ClassNotFoundException e) {
                //                     e.printStackTrace();
            } catch (IOException e) {
                //                     e.printStackTrace();
            } catch (IllegalArgumentException e) {
                //                     e.printStackTrace();
            } catch (Exception e) {
                //                     e.printStackTrace();
            }

            strykerStage.execute();

            log.info("****** FINISH: Stryker ****** ");
        }
    } else {
        log.info("****** BugFix will not be generated. ******* ");
        log.info("****** attemptToCorrectBug=false ******* ");
    }

    return tacoAnalysisResult;
}

From source file:com.tojc.ormlite.android.compiler.AbstractAnnotationProcessorTest.java

/**
 * Attempts to compile the given compilation units using the Java Compiler API.
 * <p>//from www . ja v a 2s  .co  m
 * The compilation units and all their dependencies are expected to be on the classpath.
 * @param compilationUnitPaths
 *            the paths of the source files to compile, as would be expected by
 *            {@link ClassLoader#getResource(String)}
 * @return the {@link Diagnostic diagnostics} returned by the compilation, as demonstrated in
 *         the documentation for {@link JavaCompiler}
 * @see #compileTestCase(Class...)
 */
protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) {
    assert compilationUnitPaths != null;

    Collection<File> compilationUnits;

    try {
        compilationUnits = findClasspathFiles(compilationUnitPaths);
    } catch (IOException exception) {
        throw new IllegalArgumentException("Unable to resolve compilation units "
                + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception);
    }

    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null);

    /*
     * Call the compiler with the "-proc:only" option. The "class names" option (which could, in
     * principle, be used instead of compilation units for annotation processing) isn't useful
     * in this case because only annotations on the classes being compiled are accessible.
     * Information about the classes being compiled (such as what they are annotated with) is
     * *not* available via the RoundEnvironment. However, if these classes are annotations, they
     * certainly need to be validated.
     */
    CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector,
            mergeCompilerOptions(Arrays.asList("-proc:only")), null,
            fileManager.getJavaFileObjectsFromFiles(compilationUnits));
    task.setProcessors(getProcessors());
    task.call();

    try {
        fileManager.close();
    } catch (IOException exception) {
        exception.printStackTrace();
    }

    return diagnosticCollector.getDiagnostics();
}