Example usage for javax.tools ToolProvider getSystemJavaCompiler

List of usage examples for javax.tools ToolProvider getSystemJavaCompiler

Introduction

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

Prototype

public static JavaCompiler getSystemJavaCompiler() 

Source Link

Document

Returns the Java™ programming language compiler provided with this platform.

Usage

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

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

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

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

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

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

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

From source file:boa.compiler.BoaCompiler.java

private static void compileGeneratedSrc(final CommandLine cl, final String jarName, final File outputRoot,
        final File outputFile) throws RuntimeException, IOException, FileNotFoundException {
    // compile the generated .java file
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null)
        throw new RuntimeException(
                "Could not get javac - are you running the Boa compiler with a JDK or a JRE?");
    LOG.info("compiling: " + outputFile);
    LOG.info("classpath: " + System.getProperty("java.class.path"));
    if (compiler.run(null, null, null, "-source", "5", "-target", "5", "-cp",
            System.getProperty("java.class.path"), outputFile.toString()) != 0)
        throw new RuntimeException("compile failed");

    final List<File> libJars = new ArrayList<File>();

    if (cl.hasOption('j')) {
        libJars.add(new File(cl.getOptionValue('j')));
    } else {//from   w w  w . j  a  v a 2s .  c om
        // find the location of the jar this class is in
        final String path = ClasspathUrlFinder.findClassBase(BoaCompiler.class).getPath();
        // find the location of the compiler distribution
        final File root = new File(path.substring(path.indexOf(':') + 1, path.indexOf('!'))).getParentFile();

        libJars.add(new File(root, "boa-runtime.jar"));
    }

    if (cl.hasOption('l'))
        for (final String s : Arrays.asList(cl.getOptionValues('l')))
            libJars.add(new File(s));

    generateJar(jarName, outputRoot, libJars);

    if (DefaultProperties.localDataPath == null) {
        delete(outputRoot);
    }
}

From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java

private void compileWebServiceInterface() {
    java.util.Set<String> processedFocusDomainSet = (java.util.Set<String>) getScriptContext().getMemory()
            .get("processedFocusDomainSet");

    if (processedFocusDomainSet == null) {
        processedFocusDomainSet = new java.util.HashSet<String>();
        getScriptContext().getMemory().put("processedFocusDomainSet", processedFocusDomainSet);
    }/*from  ww  w.  ja va2s  .c  o  m*/

    processedFocusDomainSet.add(getScriptContext().getFocusDomain());

    if (processedFocusDomainSet.containsAll(getScriptContext().retrieveDomainSet()) == true) { //All domains have been processed so now we can compile and generate WSDL

        StandardJavaFileManager fileManager = null;

        try {
            String jaxbPojoPath = GeneratorUtil.getJaxbPojoPath(getScriptContext());
            String servicePath = GeneratorUtil.getServicePath(getScriptContext());
            String serviceImplPath = GeneratorUtil.getServiceImplPath(getScriptContext());
            String projectRoot = getScriptContext().getProperties().getProperty("PROJECT_ROOT");

            List<String> compilerFiles = GeneratorUtil.getFiles(jaxbPojoPath, new String[] { "java" });
            compilerFiles.addAll(GeneratorUtil.getFiles(servicePath, new String[] { "java" }));
            compilerFiles.addAll(GeneratorUtil.getFiles(serviceImplPath, new String[] { "java" }));

            getScriptContext().logInfo("Compiling files: " + compilerFiles);
            // Check if output directory exist, create it
            GeneratorUtil.createOutputDir(projectRoot + File.separator + "classes");

            List<String> options = new ArrayList<String>();
            options.add("-classpath");
            String classPathStr = GeneratorUtil
                    .getFiles(new java.io.File(getScriptContext().getGeneratorBase()).getAbsolutePath()
                            + File.separator + "lib", new String[] { "jar" }, File.pathSeparator)
                    + File.pathSeparator
                    + new java.io.File(projectRoot + File.separatorChar + "classes").getAbsolutePath();

            getScriptContext().logInfo("compiler classpath is: " + classPathStr);

            options.add(classPathStr);

            options.add("-d");
            options.add(projectRoot + File.separator + "classes");

            options.add("-s");
            options.add(projectRoot + File.separator + "src/generated");

            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);
            boolean success = task.call();

            for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
                getScriptContext().logInfo(diagnostic.getCode());
                getScriptContext().logInfo(diagnostic.getKind().toString());
                getScriptContext().logInfo(diagnostic.getPosition() + "");
                getScriptContext().logInfo(diagnostic.getStartPosition() + "");
                getScriptContext().logInfo(diagnostic.getEndPosition() + "");
                getScriptContext().logInfo(diagnostic.getSource().toString());
                getScriptContext().logInfo(diagnostic.getMessage(null));
            }
        } catch (Throwable t) {
            getScriptContext().logError(t);
        } finally {
            try {
                fileManager.close();
            } catch (Throwable t) {
            }
        }

        for (String focusDomain : getScriptContext().retrieveDomainSet()) {
            generateWebServiceArtifacts(focusDomain);
        }
    }
}

From source file:com.legstar.protobuf.cobol.ProtoCobol.java

/**
 * Compile a java source file./* w w  w.  ja  v  a2s .c o  m*/
 * 
 * @param javaOut where, on the file system, the generated java class will
 *            be produced
 * @param javaSourceFile the java source file
 * @return the java class loaded
 * @throws ProtoCobolException if compilation fails
 */
public Class<?> runJavaCompiler(File javaOut, File javaSourceFile) throws ProtoCobolException {

    logger.info("About to compile " + javaSourceFile.getAbsolutePath());

    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    if (javaCompiler == null) {
        throw new ProtoCobolException("You need to have the JDK tools.jar on the classpath");
    }
    StandardJavaFileManager manager = javaCompiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(javaSourceFile.getAbsolutePath());
    String[] opts = new String[] { "-d", javaOut.getAbsolutePath() };
    CompilationTask task = javaCompiler.getTask(null, manager, null, Arrays.asList(opts), null, units);
    boolean status = task.call();
    if (status) {
        logger.info("Compilation successful");
    } else {
        throw new ProtoCobolException("Compilation failed for " + javaSourceFile.getAbsolutePath());
    }
    return loadClass(javaOut, getRelativeClassName(javaOut, javaSourceFile));
}

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

/**
 * // www .  ja  v  a  2s .  c o 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.anl.cue.arcane.engine.matrix.MatrixModel.java

/**
 * Formulate bytecode./*from w  ww.java  2 s .c om*/
 */
public void formulateBytecode() {

    // Attempt to compile the file.
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null,
            Util.TEMP_DIR + MatrixModel.PACKAGE_PATH + MatrixModel.CONCRETE_CLASS_NAME + ".java");

}

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 w  w w .ja v  a 2  s  . c  om
    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:org.abstractmeta.toolbox.compilation.compiler.impl.JavaSourceCompilerImpl.java

@Override
public boolean compile(ClassLoader parentClassLoader, CompilationUnit compilationUnit, String... options) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    return compile(compiler, parentClassLoader, compilationUnit, options);
}

From source file:org.apache.geode.test.compiler.JavaCompiler.java

public List<CompiledSourceCode> compile(UncompiledSourceCode... uncompiledSources) throws IOException {
    File temporarySourcesDirectory = createSubdirectory(tempDir, "sources");
    File temporaryClassesDirectory = createSubdirectory(tempDir, "classes");

    List<String> options = Stream.of("-d", temporaryClassesDirectory.getAbsolutePath(), "-classpath", classpath)
            .collect(toList());/*  w ww.  j av  a 2  s  .c om*/

    try {
        for (UncompiledSourceCode sourceCode : uncompiledSources) {
            File sourceFile = new File(temporarySourcesDirectory, sourceCode.simpleClassName + ".java");
            FileUtils.writeStringToFile(sourceFile, sourceCode.sourceCode, Charsets.UTF_8);
            options.add(sourceFile.getAbsolutePath());
        }

        int exitCode = ToolProvider.getSystemJavaCompiler().run(System.in, System.out, System.err,
                options.toArray(new String[] {}));

        if (exitCode != 0) {
            throw new RuntimeException("Unable to compile the given source code. See System.err for details.");
        }

        List<CompiledSourceCode> compiledSourceCodes = new ArrayList<>();
        addCompiledClasses(compiledSourceCodes, "", temporaryClassesDirectory);
        return compiledSourceCodes;
    } finally {
        FileUtils.deleteDirectory(temporaryClassesDirectory);
    }
}

From source file:org.apache.hadoop.hbase.TestClassFinder.java

/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.// w w  w . j a va 2s  . c o m
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter, String packageNameSuffix, String classNamePrefix)
        throws Exception {
    classNamePrefix = classNamePrefix + counter;
    String packageName = makePackageName(packageNameSuffix, counter);
    String javaPath = basePath + classNamePrefix + ".java";
    String classPath = basePath + classNamePrefix + ".class";
    PrintStream source = new PrintStream(javaPath);
    source.println("package " + packageName + ";");
    source.println("public class " + classNamePrefix + " { public static void main(String[] args) { } };");
    source.close();
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    int result = jc.run(null, null, null, javaPath);
    assertEquals(0, result);
    File classFile = new File(classPath);
    assertTrue(classFile.exists());
    return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}