List of usage examples for javax.tools StandardJavaFileManager close
@Override void close() throws IOException;
From source file:clear.cdb.support.test.AnnotationProcessorTestCompiler.java
/** * Processes the java class specified. This implementation only parses and processes the java classes and does not * fully compile them - i.e. it does not write class files back to the disk. Basically, {@code javac} is called with * {@code -proc:only}./*from ww w .j ava 2 s.c o m*/ * * @param processor the annotation {@link javax.annotation.processing.Processor} to use during compilation * @param fileManager * @param compilationUnits * @return a list of {@link Diagnostic} messages emitted during the compilation */ private static List<Diagnostic<? extends JavaFileObject>> compileClassInternal(Processor processor, StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits, String additionalOptions) throws IOException { DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); try { List<String> options = new ArrayList<String>(); options.add(COMPILER_OPTIONS); if (additionalOptions != null) { options.add(additionalOptions); } options.add("-classpath"); options.add(System.getProperty("java.class.path")); JavaCompiler.CompilationTask task = COMPILER.getTask(null, fileManager, collector, options, null, compilationUnits); task.setProcessors(Arrays.asList(processor)); task.call(); return collector.getDiagnostics(); } finally { if (fileManager != null) { fileManager.close(); } } }
From source file:com.jhash.oimadmin.Utils.java
public static DiagnosticCollector<JavaFileObject> compileJava(String className, String code, String outputFileLocation) { logger.trace("Entering compileJava({},{},{})", new Object[] { className, code, outputFileLocation }); File outputFileDirectory = new File(outputFileLocation); logger.trace("Validating if the output location {} exists and is a directory", outputFileLocation); if (outputFileDirectory.exists()) { if (outputFileDirectory.isDirectory()) { try { logger.trace("Deleting the directory and its content"); FileUtils.deleteDirectory(outputFileDirectory); } catch (IOException exception) { throw new OIMAdminException( "Failed to delete directory " + outputFileLocation + " and its content", exception); }// ww w .ja va 2s .co m } else { throw new InvalidParameterException( "The location " + outputFileLocation + " was expected to be a directory but it is a file."); } } logger.trace("Creating destination directory for compiled class file"); outputFileDirectory.mkdirs(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new NullPointerException( "Failed to locate a java compiler. Please ensure that application is being run using JDK (Java Development Kit) and NOT JRE (Java Runtime Environment) "); } StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<File> files = Arrays.asList(new File(outputFileLocation)); boolean success = false; DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); try { JavaFileObject javaFileObject = new InMemoryJavaFileObject(className, code); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, files); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, Arrays.asList("-source", "1.6", "-target", "1.6"), null, Arrays.asList(javaFileObject)); success = task.call(); fileManager.close(); } catch (Exception exception) { throw new OIMAdminException("Failed to compile " + className, exception); } if (!success) { logger.trace("Exiting compileJava(): Return Value {}", diagnostics); return diagnostics; } else { logger.trace("Exiting compileJava(): Return Value null"); return null; } }
From source file:com.github.aliakhtar.annoTest.util.Compiler.java
private boolean compile(Processor processor, SourceFile... sourceFiles) throws Exception { Builder<String> builder = ImmutableList.builder(); builder.add("-classpath").add(buildClassPath(outputDir)); builder.add("-d").add(outputDir.getAbsolutePath()); for (Map.Entry<String, String> entry : parameterMap.entrySet()) { builder.add("-A" + entry.getKey() + "=" + entry.getValue()); }// w w w . j a va 2 s . c o m File[] files = new File[sourceFiles.length]; for (int i = 0; i < sourceFiles.length; i++) { files[i] = writeSourceFile(sourceFiles[i]); } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(files); CompilationTask compilationTask = compiler.getTask(null, null, null, builder.build(), null, javaFileObjects); if (processor != null) compilationTask.setProcessors(Arrays.asList(processor)); Boolean success = compilationTask.call(); fileManager.close(); return success; }
From source file:iristk.flow.FlowCompiler.java
public static void compileJavaFlow(File srcFile) throws FlowCompilerException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (ToolProvider.getSystemJavaCompiler() == null) { throw new FlowCompilerException("Could not find Java Compiler"); }/*from www.ja v a2s. com*/ if (!srcFile.exists()) { throw new FlowCompilerException(srcFile.getAbsolutePath() + " does not exist"); } File outputDir = new File(srcFile.getAbsolutePath().replaceFirst("([\\\\/])src[\\\\/].*", "$1") + "bin"); if (!outputDir.exists()) { throw new FlowCompilerException("Directory " + outputDir.getAbsolutePath() + " does not exist"); } DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, Locale.US, StandardCharsets.UTF_8); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(Arrays.asList(srcFile.getAbsolutePath())); Iterable<String> args = Arrays.asList("-d", outputDir.getAbsolutePath()); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, args, null, compilationUnits); boolean success = task.call(); try { fileManager.close(); } catch (IOException e) { } for (Diagnostic<? extends JavaFileObject> diag : diagnostics.getDiagnostics()) { if (diag.getKind() == Kind.ERROR) { int javaLine = (int) diag.getLineNumber(); int flowLine = mapLine(javaLine, srcFile); String message = diag.getMessage(Locale.US); message = message.replace("line " + javaLine, "line " + flowLine); throw new FlowCompilerException(message, flowLine); } } if (!success) { throw new FlowCompilerException("Compilation failed for unknown reason"); } }
From source file:nl.elucidator.patterns.builder.annotations.processor.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p/>/* ww w. j a va2 s. c o 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) { //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>/*from w w w .j a v a 2 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) { } 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>//from w w w . j a v a 2 s .c o 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:com.tojc.ormlite.android.compiler.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p>//from w w w.j a v a2 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, 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(); }
From source file:ar.edu.taco.TacoMain.java
/** * /*from ww w. ja v a 2 s . co m*/ * @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:gov.nih.nci.restgen.util.GeneratorUtil.java
public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder, GeneratorContext context) {/*from w w w. jav a 2 s. com*/ StandardJavaFileManager fileManager = null; boolean success = true; try { List<String> compilerFiles = GeneratorUtil.getFiles(srcFolder, new String[] { "java" }); GeneratorUtil.createOutputDir(destFolder); List<String> options = new ArrayList<String>(); options.add("-classpath"); String classPathStr = GeneratorUtil.getFiles(libFolder, new String[] { "jar" }, File.pathSeparator); options.add(classPathStr); options.add("-nowarn"); options.add("-Xlint:-unchecked"); options.add("-d"); options.add(destFolder); options.add("-s"); options.add(srcFolder); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(compilerFiles); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); success = task.call(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { //context.getLogger().error(diagnostic.getCode()); //context.getLogger().error(diagnostic.getKind().toString()); //context.getLogger().error(diagnostic.getPosition() + ""); //context.getLogger().error(diagnostic.getStartPosition() + ""); //context.getLogger().error(diagnostic.getEndPosition() + ""); //context.getLogger().error(diagnostic.getSource().toString()); context.getLogger().error(diagnostic.toString()); } } catch (Throwable t) { context.getLogger().error("Error compiling java code", t); } finally { try { fileManager.close(); } catch (Throwable t) { } } return success; }