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.dawnsci.commandserver.core.process.ProgressableProcess.java

protected void pkill(int pid, String dir) throws Exception {

    // Use pkill, seems to kill all of the tree more reliably
    ProcessBuilder pb = new ProcessBuilder();

    // Can adjust env if needed:
    // Map<String, String> env = pb.environment();
    pb.directory(new File(dir));

    File log = new File(dir, "xia2_kill.txt");
    pb.redirectErrorStream(true);/*w w w  . j a  v a 2s  .co  m*/
    pb.redirectOutput(Redirect.appendTo(log));

    pb.command("bash", "-c", "pkill -9 -s " + pid);

    Process p = pb.start();
    p.waitFor();
}

From source file:dk.netarkivet.harvester.heritrix3.controller.HeritrixController.java

@Override
public void stopHeritrix() {
    log.debug("Stopping Heritrix3");
    try {//from  ww  w .j av a  2  s . c  o m
        // Check if a heritrix3 process still exists for this jobName
        ProcessBuilder processBuilder = new ProcessBuilder("pgrep", "-f", jobName);
        log.info("Looking up heritrix3 process with. " + processBuilder.command());
        if (processBuilder.start().waitFor() == 0) { // Yes, ask heritrix3 to shutdown, ignoring any jobs named jobName
            log.info("Heritrix running, requesting heritrix to stop and ignoring running job '{}'", jobName);
            h3wrapper.exitJavaProcess(Arrays.asList(new String[] { jobName }));
        } else {
            log.info("Heritrix3 process not running for job '{}'", jobName);
        }
        // Check again
        if (processBuilder.start().waitFor() == 0) { // The process is still alive, kill it
            log.info("Heritrix3 process still running, pkill'ing heritrix3 ");
            ProcessBuilder killerProcessBuilder = new ProcessBuilder("pkill", "-f", jobName);
            int pkillExitValue = killerProcessBuilder.start().exitValue();
            if (pkillExitValue != 0) {
                log.warn("Non xero exit value ({}) when trying to pkill Heritrix3.", pkillExitValue);
            } else {
                log.info("Heritrix process terminated successfully with the pkill command {}",
                        killerProcessBuilder.command());
            }
        } else {
            log.info("Heritrix3 stopped successfully.");
        }
    } catch (IOException e) {
        log.warn("Exception while trying to shutdown heritrix", e);
    } catch (InterruptedException e) {
        log.debug("stopHeritrix call interupted", e);
    }
}

From source file:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.java

private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName)
        throws InterruptedException, IOException {
    String dir = "";
    if (pb.directory() != null) {
        dir = pb.directory().getAbsolutePath();
    }/*from  ww w .j av  a 2s. com*/
    System.out.println("Running : " + pb.command() + " => directory: " + dir);
    Process processToRun = pb.start();
    int result = processToRun.waitFor();
    if (result != 0) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(processToRun.getErrorStream(), writer);
        System.out.println("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}

From source file:org.metaservice.core.utils.GitUtil.java

@NotNull
public Line[] getChangeList(@NotNull String relPath, @NotNull String revision, String revision2)
        throws GitException {
    try {//ww  w  .  j  av  a 2 s . c o m
        if (relPath.startsWith("/"))
            relPath = relPath.replaceFirst("/", "");

        ProcessBuilder builder = new ProcessBuilder("git", "difftool",
                "--extcmd=diff -d --old-line-format=-%L --new-line-format=+%L --unchanged-line-format=_%L",
                "-y", revision2, revision, relPath).directory(workdir);
        LOGGER.info(StringUtils.join(builder.command(), " "));
        Process p = builder.start();

        Line[] lines;

        ArrayList<Line> list = new ArrayList<>();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        int c;
        while ((c = in.read()) != -1) {
            Line l = new Line();
            switch (c) {
            case '+':
                l.changeType = Line.ChangeType.NEW;
                break;
            case '-':
                l.changeType = Line.ChangeType.OLD;
                break;
            case '_':
                l.changeType = Line.ChangeType.UNCHANGED;
                break;
            default:
                throw new RuntimeException("INVALID OUTPUT FORMAT '" + (char) c + "'" + in.readLine());
            }
            //readline alternative which does only halt on \n not \r
            //it also discards \r
            StringBuilder b = new StringBuilder(300);
            while ((c = in.read()) != '\n') {
                if (c == -1)
                    break;
                if (c == '\r')
                    continue;
                b.append((char) c);
            }
            l.line = b.toString();
            list.add(l);
        }
        debug(p);
        lines = list.toArray(new Line[list.size()]);
        LOGGER.debug("READ {} lines", lines.length);
        return lines;
    } catch (IOException e) {
        throw new GitException(e);
    }
}

From source file:com.pinterest.deployservice.scm.PhabricatorManager.java

private Map<String, Object> queryCLI(String input) throws Exception {
    ProcessBuilder builder;
    if (StringUtils.isEmpty(arcrcLocation)) {
        builder = new ProcessBuilder(arcLocation, "call-conduit", String.format("--conduit-uri=%s", urlPrefix),
                "diffusion.historyquery");
    } else {/*from   ww  w  .ja v a  2 s  . com*/
        builder = new ProcessBuilder(arcLocation, "call-conduit", String.format("--conduit-uri=%s", urlPrefix),
                "diffusion.historyquery", "--arcrc-file", arcrcLocation);
    }
    LOG.debug("Execute arc command: \n{}", builder.command());

    // Redirects error stream to output stream, so have only one input stream to read from
    builder.redirectErrorStream(true);

    // Run command
    Process process = builder.start();

    // Feed the input parameters
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    writer.write(input);
    writer.flush();
    writer.close();

    InputStream stdout = process.getInputStream();
    String line;
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    // Read response
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    reader.close();

    // We will remove "Waiting for JSON parameters on stdin..." from the output if exists
    String output = sb.toString();
    if (output.startsWith(ARC_OUTPUT_NOTICE)) {
        output = output.substring(ARC_OUTPUT_NOTICE_LEN);
    }
    LOG.debug("arc command output is: \n{}", output);

    GsonBuilder gson = new GsonBuilder();
    return gson.create().fromJson(output, new TypeToken<HashMap<String, Object>>() {
    }.getType());
}

From source file:au.com.permeance.liferay.portlet.patchingtoolinfo.cli.PatchingToolCommandRunner.java

public void runCommand() throws Exception {

    if (LOG.isDebugEnabled()) {
        LOG.debug("running patching tool command ...");
    }//from w w  w. j  a va  2  s  .co m

    try {

        ProcessBuilder processBuilder = configureProcessBuilder();

        // NOTE: ProcessBuilder#environent is initialised with System.getenv()
        // @see http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#environment%28%29

        if (LOG.isDebugEnabled()) {
            LOG.debug("processBuilder : " + processBuilder);
            List<String> commandList = processBuilder.command();
            LOG.debug("command environment : " + processBuilder.environment());
            LOG.debug("command list : " + commandList);
            LOG.debug("command directory : " + processBuilder.directory());
        }

        if (LOG.isDebugEnabled()) {
            List<String> commandList = processBuilder.command();
            String processCommandStr = StringHelper.flattenStringList(commandList);
            LOG.debug("running patching tool command : " + processCommandStr);
        }

        Process process = processBuilder.start();

        if (LOG.isDebugEnabled()) {
            LOG.debug("process : " + process);
        }

        // NOTE: Java 1.8 supports Process#waitFor with a timeout
        // eg. boolean finished = iostat.waitFor(100, TimeUnit.MILLISECONDS);

        int processExitValue = process.waitFor();

        List<String> processOutputLines = IOUtils.readLines(process.getInputStream());

        List<String> processErrorLines = IOUtils.readLines(process.getErrorStream());

        this.patchingToolResults = new PatchingToolResults(processExitValue, processOutputLines,
                processErrorLines);

        if (LOG.isDebugEnabled()) {
            LOG.debug("patchingToolResults: " + patchingToolResults);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("patching tool returned exit code " + this.patchingToolResults.getExitValue());
            LOG.debug("patching tool returned " + this.patchingToolResults.getOutputLines().size()
                    + " output lines");
            LOG.debug("--- COMMAND OUTPUT ---");
            LOG.debug(processOutputLines);
            LOG.debug("patching tool returned " + this.patchingToolResults.getErrorLines().size()
                    + " error lines");
            LOG.debug("--- COMMAND ERROR ---");
            LOG.debug(processErrorLines);
        }

        // NOTE: Command shell may return lines in the error stream that are warning messages, not errors.
        // Hence, we cannot rely upon content in the error stream as a valid error.

        if (this.patchingToolResults.getExitValue() != 0) {
            StringBuilder sb = new StringBuilder();
            String errorLine1 = null;
            if (this.patchingToolResults.hasErrorLines()) {
                errorLine1 = this.patchingToolResults.getErrorLines().get(0);
            }
            if (errorLine1 == null) {
                sb.append("Error running patching tool command.");
                sb.append(" See portal logs for more details.");
            } else {
                sb.append("Error running patching tool command : ");
                sb.append(errorLine1);
            }
            String errMsg = sb.toString();
            throw new Exception(errMsg);
        }

    } catch (Exception e) {

        String msg = "Error executing patching tool command : " + e.getMessage();
        LOG.error(msg, e);
        throw new Exception(msg, e);
    }
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Creates a symlink.//w w  w  .j  a v  a 2s. c om
 */
private void ln(String from, File to) throws InterruptedException, IOException {
    to.getParentFile().mkdirs();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-sf", from, to.getAbsolutePath());
    if (pb.start().waitFor() != 0) {
        throw new IOException("ln failed");
    }
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Generates symlink to the latest version.
 *///from   w w w.  j a v  a 2  s  .  c o  m
protected void createLatestSymlink(PluginHistory hpi, HPI latest) throws InterruptedException, IOException {
    File dir = new File(download, "plugins/" + hpi.artifactId);
    new File(dir, "latest").delete();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-s", latest.version, "latest");
    pb.directory(dir);
    int r = pb.start().waitFor();
    if (r != 0) {
        throw new IOException("ln failed: " + r);
    }
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Stages an artifact into the specified location.
 *///from w ww.  jav a 2 s .  com
protected void stage(MavenArtifact a, File dst) throws IOException, InterruptedException {
    File src = a.file;
    if (dst.exists() && dst.lastModified() == src.lastModified() && dst.length() == src.length()) {
        return; // already up to date
    }

    //        dst.getParentFile().mkdirs();
    //        FileUtils.copyFile(src,dst);

    // TODO: directory and the war file should have the release timestamp
    dst.getParentFile().mkdirs();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-f", src.getAbsolutePath(), dst.getAbsolutePath());
    if (pb.start().waitFor() != 0) {
        throw new IOException("ln failed");
    }

}

From source file:org.apache.tika.module.command.internal.Activator.java

public void forkProcess(String[] command) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.redirectOutput(Redirect.INHERIT);
    builder.redirectError(Redirect.INHERIT);
    List<String> forkCommand = new ArrayList<String>();
    forkCommand.add("java");
    forkCommand.add("-cp");
    forkCommand.add(System.getProperty("java.class.path"));
    forkCommand.add("org.apache.tika.main.Main");
    forkCommand.addAll(Arrays.asList(command));

    //Remove fork command when running process forked.
    forkCommand.remove("-f");
    forkCommand.remove("--fork");

    builder.command(forkCommand);
    Process process = builder.start();

    process.waitFor();/*  www.  j  a  v  a 2s  . co  m*/
}