Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void createPatch(Repository repository, String site, String path) {
    StringBuffer output = new StringBuffer();

    String tempPath = System.getProperty("java.io.tmpdir");
    if (tempPath == null) {
        tempPath = "temp";
    }//  ww  w  .j  a v a 2s  .c o m
    Path patchPath = Paths.get(tempPath, "patch" + site + ".bin");

    String gitPath = getGitPath(path);
    Process p = null;
    File file = patchPath.toAbsolutePath().normalize().toFile();
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("git", "diff", "--binary", environment, "master", "--", gitPath);

        pb.redirectOutput(file);
        pb.directory(repository.getDirectory().getParentFile());
        p = pb.start();
        p.waitFor();
    } catch (Exception e) {
        logger.error("Error while creating patch for site: " + site + " path: " + path, e);
    }
}

From source file:org.sipfoundry.sipxconfig.admin.time.TimeManagerImpl.java

public void setSystemTimezone(String timezone) {
    String errorMsg = "Error when changing time zone";
    ProcessBuilder pb = new ProcessBuilder(getLibExecDirectory() + File.separator + TIMEZONE_BINARY);
    pb.command().add(timezone);
    try {//  w  w w .  j  av a 2 s. c  o m
        LOG.debug(pb.command());
        Process process = pb.start();
        BufferedReader scriptErrorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String errorLine = scriptErrorReader.readLine();
        while (errorLine != null) {
            LOG.warn("sipx-sudo-timezone: " + errorLine);
            errorLine = scriptErrorReader.readLine();
        }
        int code = process.waitFor();
        if (code != 0) {
            errorMsg = String.format("Error when changing time zone. Exit code: %d", code);
            LOG.error(errorMsg);
        }
        TimeZone tz = TimeZone.getTimeZone(timezone);
        TimeZone.setDefault(tz);
    } catch (IOException e) {
        LOG.error(errorMsg, e);
    } catch (InterruptedException e) {
        LOG.error(errorMsg, e);
    }
}

From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolProcess.java

/**
 * Start the DynamoDBLocal process.//  w  ww.  java 2 s. com
 *
 * @param  onExitAction optional action to be executed when the process
 *                      exits
 * @throws IOException  if starting the process fails
 */
public synchronized void start(final Runnable onExitAction) throws IOException {

    if (process != null) {
        throw new IllegalStateException("Already started!");
    }

    ProcessBuilder builder = new ProcessBuilder();

    builder.directory(installDirectory);
    builder.command(jre.getInstallLocation().getAbsolutePath().concat("/bin/java"),
            "-Djava.library.path=".concat(findLibraryDirectory().getAbsolutePath()), "-jar",
            "DynamoDBLocal.jar", "--port", Integer.toString(port));

    // Drop STDERR into STDOUT so we can handle them together.
    builder.redirectErrorStream(true);

    // Register a shutdown hook to kill DynamoDBLocal if Eclipse exits.
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    // Start the DynamoDBLocal process.
    process = builder.start();

    // Start a background thread to read any output from DynamoDBLocal
    // and dump it to an IConsole.
    new ConsoleOutputLogger(process.getInputStream(), onExitAction).start();
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;//  w w  w  .  j a va2 s  .  co  m
    try {
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:functionaltests.matlab.AbstractMatlabTest.java

protected void runCommand(String testName, int nb_iter) throws Exception {

    ProcessBuilder pb = initCommand(testName, nb_iter);
    System.out.println("Running command : " + pb.command());

    File okFile = new File(mat_tb_home + fs + "ok.tst");
    File koFile = new File(mat_tb_home + fs + "ko.tst");
    File startFile = new File(mat_tb_home + fs + "start.tst");

    if (okFile.exists()) {
        okFile.delete();//from w  w w  .  j a  va  2 s  .  com
    }

    if (koFile.exists()) {
        koFile.delete();
    }
    if (startFile.exists()) {
        startFile.delete();
    }

    Process p = pb.start();

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[" + testName + "]", System.out);
    Thread t1 = new Thread(lt1, testName);
    t1.setDaemon(true);
    t1.start();

    p.waitFor();
    // sometimes a matlab laucher is used and it returns immediately, the waitFor will not be of use and we need to wait
    // for files to be created
    while (!startFile.exists()) {
        Thread.sleep(100);
    }

    while (!okFile.exists() && !koFile.exists()) {
        Thread.sleep(100);
    }

    if (logFile.exists()) {
        System.out.println(IOUtils.toString(logFile.toURI()));
    }

    assertTrue(testName + " passed", okFile.exists());
}

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

private Process createKarmaProcess() throws MojoExecutionException {

    final ProcessBuilder builder;

    if (isWindows()) {
        builder = new ProcessBuilder("cmd", "/C", "karma", "start", configFile.getAbsolutePath());
    } else {//ww  w  . j a  v  a  2  s.com
        builder = new ProcessBuilder("karma", "start", configFile.getAbsolutePath());
    }

    final List<String> command = builder.command();

    command.addAll(valueToKarmaArgument(singleRun, "--single-run", "--no-single-run"));
    addKarmaArguments(command);

    return startKarmaProcess(builder);
}

From source file:org.sipfoundry.sipxconfig.admin.time.TimeManagerImpl.java

public CommandOutput executeCommand(String command, String... parameters)
        throws IOException, InterruptedException {
    // executes command with parameters
    // returns a 3 item String[] which contains at the first position, the return code, the
    // second = the stdout of the command and the third the stderr of the command
    ProcessBuilder pb = new ProcessBuilder(command);
    for (int i = 0; i < parameters.length; i++) {
        pb.command().add(parameters[i]);
    }//w  ww .  java 2s  .  c o m
    LOG.debug(pb.command());
    Process process = pb.start();

    BufferedReader scriptOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader scriptErrorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    String line;
    String errors = new String();
    String output = new String();

    while ((line = scriptOutputReader.readLine()) != null) {
        output = output + NEW_LINE + line;
    }

    while ((line = scriptErrorReader.readLine()) != null) {
        errors = errors + NEW_LINE + line;
    }

    int code = process.waitFor();

    CommandOutput commandOutput = new CommandOutput(code, output, errors);
    return commandOutput;
}

From source file:org.ostara.cmd.BaseCmdLineCmd.java

protected void executeCommand(ICmdResult result, List<String> cmd, String cmdExecDir, boolean wait) {
    Process p = null;/*from  ww w . jav  a  2 s .  co m*/
    ProcessCall processCall = null;
    ProcessCallOutput output = null;

    List<String> cmdLine = new ArrayList<String>();

    // For windows system
    if (SystemUtils.IS_OS_WINDOWS) {
        cmdLine.add("cmd.exe");
        cmdLine.add("/C");
    }

    cmdLine.addAll(cmd);

    int retry = 0;
    Exception error = null;
    while (retry < 3) {
        try {

            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.redirectErrorStream(true);
            processBuilder.directory(new File(cmdExecDir));

            logger.info("Executing process: " + cmdLine);

            p = processBuilder.command(cmdLine).start();
            if (wait) {
                processCall = new ProcessCall(p);
                output = processCall.call();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            error = e;
            retry++;
            continue;
        }
        break;
    }

    if (output == null) {
        result.setException(error);
    } else if (output.exitValue != 0) {
        result.setException(new RuntimeException(
                "Failed to execute command(%" + getClass().getName() + "%), rtn value:" + output.exitValue));
    } else {
        result.setMessage(output.output);
    }
}

From source file:org.apache.asterix.test.common.TestExecutor.java

public static String executeScript(ProcessBuilder pb, String scriptPath) throws Exception {
    LOGGER.info("Executing script: " + scriptPath);
    pb.command(scriptPath);
    Process p = pb.start();/*ww  w . j  a v a 2 s . c  o  m*/
    return getProcessOutput(p);
}

From source file:net.sf.mavenjython.test.PythonTestMojo.java

public void execute() throws MojoExecutionException {
    // all we have to do is to run nose on the source directory
    List<String> l = new ArrayList<String>();
    if (program.equals("nose")) {
        l.add("nosetests.bat");
        l.add("--failure-detail");
        l.add("--verbose");
    } else {/*from w ww  . j  a va  2 s .  c  o m*/
        l.add(program);
    }

    ProcessBuilder pb = new ProcessBuilder(l);
    pb.directory(testOutputDirectory);
    pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath());
    final Process p;
    getLog().info("starting python tests");
    getLog().info("executing " + pb.command());
    getLog().info("in directory " + testOutputDirectory);
    getLog().info("and also including " + outputDirectory);
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Python tests execution failed. Provide the executable '" + program + "' in the path", e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue());
        } else {
            getLog().info("Python tests (" + program + ") succeeded.");
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }
}