Example usage for javax.tools JavaCompiler getTask

List of usage examples for javax.tools JavaCompiler getTask

Introduction

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

Prototype

CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options,
        Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits);

Source Link

Document

Creates a future for a compilation task with the given components and arguments.

Usage

From source file:de.monticore.codegen.GeneratorTest.java

/**
 * Instantiates all the parameters required for a CompilationTask and returns
 * the finished task.// w w  w. j  a v a2s .  c  o  m
 * 
 * @param sourceCodePath the source directory to be compiled
 * @param diagnostics a bin for any error messages that may be generated by
 * the compiler
 * @return the compilationtask that will compile any entries in the given
 * directory
 */
protected Optional<CompilationTask> setupCompilation(Path sourceCodePath,
        DiagnosticCollector<JavaFileObject> diagnostics) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler != null) {
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        // set compiler's classpath to be same as the runtime's
        String sPath = Paths.get("target/generated-sources/monticore/codetocompile").toAbsolutePath()
                .toString();
        List<String> optionList = Lists.newArrayList("-classpath",
                System.getProperty("java.class.path") + File.pathSeparator + sPath, "-sourcepath", sPath);
        // System.out.println("Options" + optionList);
        Iterable<? extends JavaFileObject> javaFileObjects = getJavaFileObjects(sourceCodePath, fileManager);
        // System.out.println("Java files" + javaFileObjects);
        return Optional.of(compiler.getTask(null, fileManager, diagnostics, optionList, null, javaFileObjects));
    }
    return Optional.empty();
}

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

/**
 * Compile a java source file.//from w w w  .j  a va 2s. 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: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.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(Folder webAppRootFolder, Iterable<Folder> sources, Folder destination,
        Iterable<Resource> classpath) {
    try {// ww w . j  av  a 2s  .  c  o  m
        if (webAppRootFolder != null) {
            copyRuntimeServiceFiles(webAppRootFolder, destination);
        }
        JavaCompiler compiler = new WaveMakerJavaCompiler();
        StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, getStandardClassPath());
        ResourceJavaFileManager projectFileManager = new ResourceJavaFileManager(standardFileManager);
        projectFileManager.setLocation(StandardLocation.SOURCE_PATH, sources);
        ArrayList<Folder> destinations = new ArrayList<Folder>();
        destinations.add(destination);
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT, destinations);
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
        Iterable<JavaFileObject> compilationUnits = projectFileManager.list(StandardLocation.SOURCE_PATH, "",
                Collections.singleton(Kind.SOURCE), true);
        StringWriter compilerOutput = new StringWriter();
        CompilationTask compilationTask = compiler.getTask(compilerOutput, projectFileManager, null,
                getCompilerOptions(), null, compilationUnits);
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Compile error: " + e);
    }
}

From source file:com.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(final Project project) {
    try {/*  w  ww .j a va 2s.c o  m*/
        copyRuntimeServiceFiles(project.getWebAppRootFolder(), project.getClassOutputFolder());
        JavaCompiler compiler = new WaveMakerJavaCompiler();
        StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, getStandardClassPath());
        ResourceJavaFileManager projectFileManager = new ResourceJavaFileManager(standardFileManager);
        projectFileManager.setLocation(StandardLocation.SOURCE_PATH, project.getSourceFolders());
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                Collections.singleton(project.getClassOutputFolder()));
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, getClasspath(project));
        copyResources(project);
        Iterable<JavaFileObject> compilationUnits = projectFileManager.list(StandardLocation.SOURCE_PATH, "",
                Collections.singleton(Kind.SOURCE), true);
        StringWriter compilerOutput = new StringWriter();
        CompilationTask compilationTask = compiler.getTask(compilerOutput, projectFileManager, null,
                getCompilerOptions(project), null, compilationUnits);
        ServiceDefProcessor serviceDefProcessor = configure(new ServiceDefProcessor(), projectFileManager);
        ServiceConfigurationProcessor serviceConfigurationProcessor = configure(
                new ServiceConfigurationProcessor(), projectFileManager);
        compilationTask.setProcessors(Arrays.asList(serviceConfigurationProcessor, serviceDefProcessor));
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Unable to compile " + project.getProjectName(), e);
    }
}

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

/**
 * /*from  www. j a va 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: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 ww.  ja  va2s .c o 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:me.dwtj.java.compiler.utils.CompilationTaskBuilder.java

private CompilationTask buildTask() throws IOException {
    // Configure the compiler itself and its file manager.
    JavaCompiler compiler = getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostic, null, null);
    fileManagerConfig.config(fileManager);

    // Use the file manager and the class list to get the compilation units to be compiled.
    for (String c : classes) {
        JavaFileObject srcFile = fileManager.getJavaFileForInput(SOURCE_PATH, c, SOURCE);
        if (srcFile == null) {
            throw new IOException("No such class found on the source path: " + c);
        } else {/*from  w  w  w.  j  a  va2s.  co  m*/
            compilationUnits.add(srcFile);
        }
    }

    // Configure the compilation task itself.
    if (compilationUnits.isEmpty()) {
        String msg = "CompilationTaskBuilder: No compilation units have been added.";
        throw new IllegalStateException(msg);
    }
    CompilationTask task = compiler.getTask(null, // TODO: Support user-defined writer.
            fileManager, diagnostic, options, // TODO: Support more user-defined options.
            null, // TODO: Support user-defined classes.
            compilationUnits);
    task.setProcessors(processors);

    return task;
}

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  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: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  w w.ja  v  a 2s .  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);
        }
    }
}