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:com.legstar.protobuf.cobol.ProtoCobol.java

/**
 * Compile a java source file.//from  w ww .j a  va2 s . c  om
 * 
 * @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:com.cloudera.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.
 */// w  w w.  java 2 s  . 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);
            }
        }

        if (!fOrig.renameTo(fDest)) {
            LOG.error("Could not rename " + orig + " to " + dest);
        }
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java

@SuppressWarnings("unchecked")
private JavaFileManager compileClass(String fqcn, String code) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager fileManager = new MockClassFileManager<StandardJavaFileManager>(
            compiler.getStandardFileManager(null, null, null));

    List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
    javaFiles.add(new MockCharSequenceJavaFileObject(fqcn, code));

    ByteArrayOutputStream compilerOutput = new ByteArrayOutputStream();

    JavaCompiler.CompilationTask task = compiler.getTask(new OutputStreamWriter(compilerOutput), fileManager,
            null, null, null, javaFiles);

    if (!task.call())
        fail("Compiling of generated class did not succeed. Java code:\r\n" + code + "\r\nCompiler output:\r\n"
                + compilerOutput.toString());

    return fileManager;
}

From source file:com.webcohesion.enunciate.modules.java_json_client.JavaJSONClientModule.java

protected File compileClientSources(File sourceDir) {
    File compileDir = getCompileDir();
    compileDir.mkdirs();//w  w  w . j ava 2  s  .  com

    //Compile the java files.
    if (!isDisableCompile()) {
        if (!isUpToDateWithSources(compileDir)) {
            List<File> sources = findJavaFiles(sourceDir);
            if (sources != null && !sources.isEmpty()) {
                String classpath = this.enunciate.writeClasspath(enunciate.getClasspath());
                JavaCompiler compiler = JavacTool.create();
                List<String> options = Arrays.asList("-source", "1.5", "-target", "1.5", "-encoding", "UTF-8",
                        "-cp", classpath, "-d", compileDir.getAbsolutePath(), "-nowarn");
                JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null,
                        compiler.getStandardFileManager(null, null, null).getJavaFileObjectsFromFiles(sources));
                if (!task.call()) {
                    throw new EnunciateException("Compile failed of Java JSON client-side classes.");
                }
            } else {
                debug("No Java JSON client classes to compile.");
            }
        } else {
            info("Skipping compilation of Java JSON client classes as everything appears up-to-date...");
        }
    }

    return compileDir;

}

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

/**
 * /*from   w w w  . j av a2s  .  c  om*/
 * @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.webcohesion.enunciate.modules.java_xml_client.JavaXMLClientModule.java

protected File compileClientSources(File sourceDir) {
    File compileDir = getCompileDir();
    compileDir.mkdirs();/*from w ww .  j  ava  2 s . com*/

    //Compile the java files.
    if (!isDisableCompile()) {
        if (!isUpToDateWithSources(compileDir)) {
            List<File> sources = findJavaFiles(sourceDir);
            if (sources != null && !sources.isEmpty()) {
                String classpath = this.enunciate.writeClasspath(enunciate.getClasspath());
                JavaCompiler compiler = JavacTool.create();
                List<String> options = Arrays.asList("-source", "1.5", "-target", "1.5", "-encoding", "UTF-8",
                        "-cp", classpath, "-d", compileDir.getAbsolutePath(), "-nowarn");
                JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, options, null,
                        compiler.getStandardFileManager(null, null, null).getJavaFileObjectsFromFiles(sources));
                if (!task.call()) {
                    throw new EnunciateException("Compile failed of Java client-side classes.");
                }
            } else {
                debug("No Java XML client classes to compile.");
            }
        } else {
            info("Skipping compilation of Java client classes as everything appears up-to-date...");
        }
    }

    return compileDir;

}

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");
    }//  w w  w . j  a  va  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: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.//from w  ww  . j  av a2s. c o  m
 * @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:org.abstractmeta.toolbox.compilation.compiler.impl.JavaSourceCompilerImpl.java

protected boolean compile(JavaCompiler compiler, ClassLoader parentClassLoader, CompilationUnit compilationUnit,
        String... options) {//from w  w  w  .  j  a v a  2  s  .  c o m
    if (compiler == null) {
        throw new IllegalStateException(
                "Failed to create the system Java compiler. Check that your class path includes tools.jar");
    }
    JavaFileObjectRegistry registry = compilationUnit.getRegistry();
    SimpleClassLoader result = new SimpleClassLoader(parentClassLoader, registry,
            compilationUnit.getOutputClassDirectory());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaFileManager standardFileManager = compiler.getStandardFileManager(diagnostics, null, null);
    JavaFileManager javaFileManager = new SimpleJavaFileManager(standardFileManager, result, registry);
    Iterable<JavaFileObject> sources = registry.get(JavaFileObject.Kind.SOURCE);
    Collection<String> compilationOptions = buildOptions(compilationUnit, result, options);
    JavaCompiler.CompilationTask task = compiler.getTask(null, javaFileManager, diagnostics, compilationOptions,
            null, sources);
    task.call();
    if (getDiagnosticCountByType(diagnostics, Diagnostic.Kind.ERROR) > 0) {
        String diagnosticString = getDiagnosticString(registry, diagnostics);
        if (diagnosticString.contains("missing return statement")) {
            return false;
        }
        throw new IllegalStateException(diagnosticString);
    }
    if (getDiagnosticCountByType(diagnostics, Diagnostic.Kind.WARNING) > 0) {
        logger.warn(getDiagnosticString(registry, diagnostics));
    }
    result.addClassPathEntries(compilationUnit.getClassPathsEntries());
    return true;
}

From source file:org.apache.hadoop.hbase.util.ClassLoaderTestHelper.java

/**
 * Create a test jar for testing purpose for a given class
 * name with specified code string./*from  ww w  . ja v  a2 s .  c o  m*/
 *
 * @param testDir the folder under which to store the test class
 * @param className the test class name
 * @param code the optional test class code, which can be null.
 * If null, an empty class will be used
 * @param folder the folder under which to store the generated jar
 * @return the test jar file generated
 */
public static File buildJar(String testDir, String className, String code, String folder) throws Exception {
    String javaCode = code != null ? code : "public class " + className + " {}";
    Path srcDir = new Path(testDir, "src");
    File srcDirPath = new File(srcDir.toString());
    srcDirPath.mkdirs();
    File sourceCodeFile = new File(srcDir.toString(), className + ".java");
    BufferedWriter bw = new BufferedWriter(new FileWriter(sourceCodeFile));
    bw.write(javaCode);
    bw.close();

    // compile it by JavaCompiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    ArrayList<String> srcFileNames = new ArrayList<String>();
    srcFileNames.add(sourceCodeFile.toString());
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> cu = fm.getJavaFileObjects(sourceCodeFile);
    List<String> options = new ArrayList<String>();
    options.add("-classpath");
    // only add hbase classes to classpath. This is a little bit tricky: assume
    // the classpath is {hbaseSrc}/target/classes.
    String currentDir = new File(".").getAbsolutePath();
    String classpath = currentDir + File.separator + "target" + File.separator + "classes"
            + System.getProperty("path.separator") + System.getProperty("java.class.path")
            + System.getProperty("path.separator") + System.getProperty("surefire.test.class.path");

    options.add(classpath);
    LOG.debug("Setting classpath to: " + classpath);

    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null, options, null, cu);
    assertTrue("Compile file " + sourceCodeFile + " failed.", task.call());

    // build a jar file by the classes files
    String jarFileName = className + ".jar";
    File jarFile = new File(folder, jarFileName);
    jarFile.getParentFile().mkdirs();
    if (!createJarArchive(jarFile, new File[] { new File(srcDir.toString(), className + ".class") })) {
        assertTrue("Build jar file failed.", false);
    }
    return jarFile;
}