Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

In this page you can find the example usage for java.lang ProcessBuilder start.

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java

/**
 * Runs Maven in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir                The directory below src/test/resources to run maven in.
 * @param extraArgs          The extra arguments (if any) for Maven.
 * @return The standard output.//from   w  w  w . j  a va2s . co  m
 * @throws Exception When the execution failed.
 */
private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String m2Home = System.getenv("M2_HOME");
    String flywayVersion = System.getProperty("flywayVersion");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(m2Home + "/bin/mvn" + extension);
    args.add("-Dflyway.version=" + flywayVersion);
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}

From source file:com.googlecode.flyway.ant.AntLargeTest.java

/**
 * Runs Ant in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir       The directory below src/test/resources to run maven in.
 * @param extraArgs The extra arguments (if any) for Maven.
 * @return The standard output./*from w w w. j av  a 2  s.com*/
 * @throws Exception When the execution failed.
 */
private String runAnt(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String antHome = System.getenv("ANT_HOME");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(antHome + "/bin/ant" + extension);
    args.add("-DlibDir=" + System.getProperty("libDir"));
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}

From source file:com.sonar.it.android.AndroidTest.java

@Test
@Ignore("Deactivated awaiting resolution of http://jira.sonarsource.com/browse/JC-145")
public void should_run_lint_after_export_and_import_results() throws Exception {
    assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1());
    String response = exportProfile("it-profile");
    File baseDir = new File("projects/SonarAndroidSample/app");
    FileUtils.write(new File(baseDir, "lint.xml"), response, Charsets.UTF_8);
    ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "gradle lint");
    pb.directory(baseDir);//www. jav  a2  s .  com
    pb.inheritIO();
    Process gradleProcess = pb.start();
    int exitStatus = gradleProcess.waitFor();
    if (exitStatus != 0) {
        fail("Failed to execute gradle lint.");
    }
    SonarRunner analysis = SonarRunner.create().setProfile("it-profile").setProjectName("SonarAndroidSample2")
            .setProjectKey("SonarAndroidSample2").setProjectVersion("1.0").setSourceDirs("src/main")
            .setProjectDir(baseDir).setProperty("sonar.android.lint.report", "lint-report-build.xml")
            .setProperty("sonar.import_unknown_files", "true");
    orchestrator.executeBuild(analysis);
    Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample2", "violations"));

    assertThat(project.getMeasureIntValue("violations")).isEqualTo(2);

}

From source file:hyperheuristics.main.comparisons.CompareHypervolumes.java

private static void hypervolumeComparison(String[] problems, String[] heuristicFunctions,
        int numberOfObjectives) throws InterruptedException, IOException {
    for (String heuristicFunction : heuristicFunctions) {
        String path = outpath;/*from w w w.  j  a va 2s.co  m*/
        String outputDirectory = path + numberOfObjectives + "objectives/" + heuristicFunction + "/";

        try (FileWriter fileWriter = new FileWriter(outputDirectory + "HYPERVOLUMES.txt")) {

            int hyperheuristicBest = 0;
            int mecbaBest = 0;
            int tied = 0;

            int hyperheuristicBestMean = 0;
            int mecbaBestMean = 0;
            int tiedMean = 0;
            int equivalent = 0;
            for (String problem : problems) {
                fileWriter.append("Hypervolume comparison for " + problem + ":\n");
                fileWriter.append("\n");
                HypervolumeHandler hypervolumeHandler = new HypervolumeHandler();

                String hyperheuristicDirectory = outputDirectory + problem + "/";

                String mecbaDirectory = "resultado/nsgaii/" + problem + "_Comb_" + numberOfObjectives + "obj/";

                //Best hypervolume for PFknown
                hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "FUN.txt");
                hypervolumeHandler.addParetoFront(mecbaDirectory + "All_FUN_nsgaii-" + problem);

                double mecbaHypervolume = hypervolumeHandler
                        .calculateHypervolume(mecbaDirectory + "All_FUN_nsgaii-" + problem, numberOfObjectives);
                double hyperheuristicHypervolume = hypervolumeHandler
                        .calculateHypervolume(hyperheuristicDirectory + "FUN.txt", numberOfObjectives);
                fileWriter.append("MECBA PFknown: " + mecbaHypervolume + "\n");
                fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicHypervolume + "\n");
                if (mecbaHypervolume == hyperheuristicHypervolume) {
                    fileWriter.append("Best PFknown: Tied!\n");
                    tied++;
                } else {
                    if (mecbaHypervolume > hyperheuristicHypervolume) {
                        fileWriter.append("Best PFknown: MECBA\n");
                        mecbaBest++;
                    } else {
                        fileWriter.append("Best PFknown: " + heuristicFunction + "\n");
                        hyperheuristicBest++;
                    }
                }

                //Best mean hypervolume
                fileWriter.append("\n");

                hypervolumeHandler.clear();

                for (int i = 0; i < EXECUTIONS; i++) {
                    hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt");
                    hypervolumeHandler.addParetoFront(
                            mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas");
                }

                double[] mecbaHypervolumes = new double[EXECUTIONS];
                double[] hyperheuristicHypervolumes = new double[EXECUTIONS];

                mecbaHypervolume = 0;
                hyperheuristicHypervolume = 0;

                for (int i = 0; i < EXECUTIONS; i++) {
                    mecbaHypervolumes[i] = hypervolumeHandler.calculateHypervolume(
                            mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas",
                            numberOfObjectives);
                    mecbaHypervolume += mecbaHypervolumes[i];
                    hyperheuristicHypervolumes[i] = hypervolumeHandler.calculateHypervolume(
                            hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt", numberOfObjectives);
                    hyperheuristicHypervolume += hyperheuristicHypervolumes[i];
                }

                mecbaHypervolume /= (double) EXECUTIONS;
                hyperheuristicHypervolume /= (double) EXECUTIONS;

                fileWriter.append("MECBA (Mean): " + mecbaHypervolume + "\n");
                fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicHypervolume + "\n");

                if (mecbaHypervolume == hyperheuristicHypervolume) {
                    fileWriter.append("Best (Mean): Tied!\n");
                    tiedMean++;
                } else {
                    if (mecbaHypervolume > hyperheuristicHypervolume) {
                        fileWriter.append("Best (Mean): MECBA\n");
                        mecbaBestMean++;
                    } else {
                        fileWriter.append("Best (Mean): " + heuristicFunction + "\n");
                        hyperheuristicBestMean++;
                    }

                    String script = "";

                    script += "MECBA <- c(";
                    for (double value : mecbaHypervolumes) {
                        script += value + ",";
                    }
                    script = script.substring(0, script.lastIndexOf(",")) + ")";

                    script += "\n";

                    script += "MECBA_Hyp <- c(";
                    for (double value : hyperheuristicHypervolumes) {
                        script += value + ",";
                    }
                    script = script.substring(0, script.lastIndexOf(",")) + ")";

                    script += "\n";

                    script += "require(pgirmess)\n";
                    script += "AR1 <- cbind(MECBA, MECBA_Hyp)\n";
                    script += "result <- friedman.test(AR1)\n";
                    script += "m <- data.frame(result$statistic,result$p.value)\n";
                    script += "pos_teste <- friedmanmc(AR1)\n";
                    script += "print(pos_teste)";

                    try (FileWriter scriptWriter = new FileWriter(hyperheuristicDirectory + "temp_input.txt")) {
                        scriptWriter.append(script);
                    }
                    ProcessBuilder processBuilder = new ProcessBuilder("R", "--no-save");

                    File tempOutput = new File(hyperheuristicDirectory + "temp_output.txt");
                    processBuilder.redirectOutput(tempOutput);

                    File tempInput = new File(hyperheuristicDirectory + "temp_input.txt");
                    processBuilder.redirectInput(tempInput);

                    Process process = processBuilder.start();
                    process.waitFor();

                    Scanner scanner = new Scanner(tempOutput);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        if (line.contains("FALSE")) {
                            equivalent++;
                            fileWriter.append("Statistical Equivalents (Friedman 5%)\n");
                            break;
                        }
                    }

                    tempInput.delete();
                    tempOutput.delete();
                }

                fileWriter.append("\n");
                fileWriter.append("----------\n");
                fileWriter.append("\n");
            }
            fileWriter.append("Problems: " + problems.length + "\n");
            fileWriter.append("\n");
            fileWriter.append("Tied PFknown: " + tied + "\n");
            fileWriter.append("MECBA PFknown: " + mecbaBest + "\n");
            fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicBest + "\n");
            fileWriter.append("\n");
            fileWriter.append("Tied (Mean): " + tiedMean + "\n");
            fileWriter.append("MECBA (Mean): " + mecbaBestMean + "\n");
            fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicBestMean + "\n");
            fileWriter.append("Statistically Equivalent: " + equivalent + "\n");
        }
    }
}

From source file:name.martingeisse.ecobuild.util.CommandLineToolInvocation.java

@Override
protected void invoke(List<String> tokens) throws IOException {

    final ProcessBuilder processBuilder = new ProcessBuilder(tokens);
    processBuilder.directory(getWorkingDirectory());
    processBuilder.redirectErrorStream(true);
    final Process process;
    try {//from  w  ww .ja v a2 s. c om
        process = processBuilder.start();
    } catch (IOException e) {
        getLogger().logError(
                "Exception while starting tool. Command Line: " + getCommand() + " / " + tokens.get(0));
        throw e;
    }
    final MyLoggerWriter loggerWriter = new MyLoggerWriter(getLogger());
    IOUtils.copy(process.getInputStream(), loggerWriter);
    loggerWriter.endStartedLine();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new ToolBuildException("An InterruptedException occurred", e);
    }

}

From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java

public Document analyze(URL url) throws IOException, JDOMException, InterruptedException {
    InputStream in = null;/*  w ww  .  jav a  2 s  .  c  o  m*/
    boolean threw = true;
    try {
        log.info("Starting analysis of [" + url.toExternalForm() + "]");

        List<String> command = constructCommand(url);

        logCommand(command);

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream();
        Process p = pb.start();
        // FIXME: we need to filter the InputStream as it seems we can get
        // content outside of the XML document (see sitespeed.io)
        in = p.getInputStream();
        byte[] result = IOUtils.toByteArray(in);

        log.info("Result of analysis:" + ArrayUtils.toString(result));

        Document doc = docBuilder.get().build(new ByteArrayInputStream(result));

        log.info(XmlPrettyPrinter.prettyPrint(doc));

        int status = p.waitFor();
        if (status != 0) {
            throw new RuntimeException("PhantomJS returned with status [" + status + "]");
        }
        threw = false;
        return doc;
    } finally {
        Closeables.close(in, threw);
    }
}

From source file:ape.SuspendNodeCommand.java

public boolean runImpl(String[] args) throws IOException {
    String nodeType = null;/*from www . j a v a2 s .c o m*/
    nodeType = args[0];

    if (Main.VERBOSE)
        System.out.println("Nodetype" + args[0]);

    Process p;

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Suspend is about to execute the following command:");
        String cmd = "echo \"kill -19 \\$(ps aux | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > kill-node.sh && chmod +x kill-node.sh && ./kill-node.sh";
        System.out.println(cmd);
        /**
         * The above code block checks to see if a valid node type is passed.
         * If it is, then it sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh;
        try {
            sh = pb.start();
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            sh.waitFor();
        } catch (InterruptedException e) {
            System.out.println("The suspend node command caught an Interrupt...");
            e.printStackTrace();
            return false;
        }
        InputStream shIn = sh.getInputStream();
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the suspend process.");
            e.printStackTrace();
            return false;
        }
        return true;
    } else {
        System.err.println("Invalid node type.");
        return false;
    }
}

From source file:com.googlecode.flyway.commandline.largetest.CommandLineLargeTest.java

/**
 * Runs the Flyway Command Line tool.//www .ja v a  2s . c  om
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param configFileName     The config file name. {@code null} for default.
 * @param operation          The operation {@code null} for none.
 * @param extraArgs          The extra arguments to pass to the tool.
 * @return The standard output produced by the tool.
 * @throws Exception thrown when the invocation failed.
 */
private String runFlywayCommandLine(int expectedReturnCode, String configFileName, String operation,
        String... extraArgs) throws Exception {
    List<String> args = new ArrayList<String>();

    String installDir = System.getProperty("installDir");
    args.add(installDir + "/flyway." + flywayCmdLineExtensionForCurrentSystem());

    if (operation != null) {
        args.add(operation);
    }
    if (configFileName != null) {
        String configFile = new ClassPathResource("largeTest.properties").getFile().getPath();
        args.add("-configFile=" + configFile);
    }
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}

From source file:com.kelveden.karma.AbstractKarmaMojo.java

protected Process startKarmaProcess(ProcessBuilder builder) throws MojoExecutionException {
    try {/* w  ww.  j ava2s .  c om*/
        builder.redirectErrorStream(true);

        System.out.println(StringUtils.join(builder.command().iterator(), " "));

        return builder.start();

    } catch (IOException e) {
        throw new MojoExecutionException("There was an error executing Karma.", e);
    }
}

From source file:cz.muni.fi.pb138.cvmanager.service.PDFgenerator.java

/**
 * By external calling pdflatex function of laTex generates pdf curriculum vitae document from .tex file
 * @param username name of user whose is the CV
 * @return language to export (sk/en)//from w  ww . j  a va  2  s.  c  o m
 * @throws IOException
 * @throws InterruptedException
 * @throws NullPointerException
 */
public InputStream latexToPdf(String username) throws IOException, InterruptedException, NullPointerException {
    ProcessBuilder pb = new ProcessBuilder("pdflatex", username + "_cv.tex", "--output-directory=");
    File file = new File("cvxml/");
    pb.directory(file);
    Process p = pb.start();

    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("cvxml/");
    dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    while (true) {
        // wait for a key to be available for 10 seconds
        WatchKey key = watcher.poll(10000L, TimeUnit.MILLISECONDS);
        if (key == null) {
            break;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            // get event type
            WatchEvent.Kind<?> kind = event.kind();

            // get file name
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();

            System.out.println(kind.name() + ": " + fileName);
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }

    System.out.println("end of cycle");

    File pdf = new File("cvxml/" + username + "_cv.pdf");

    return new FileInputStream(pdf);
}