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:io.github.retz.executor.FileManager.java

private static void decompress(File file, String dir) throws IOException {
    LOG.info("{} needs decompression: starting", file);
    String[] cmd = { "tar", "xf", file.getAbsolutePath(), "-C", dir };
    ProcessBuilder pb = new ProcessBuilder().command(cmd).inheritIO();
    try {/*from   w w w . j  av a2 s.  c  om*/
        Process p = pb.start();
        int r = p.waitFor();
        if (r == 0) {
            LOG.info("file {} successfully decompressed", file);
        } else {
            LOG.error("Failed decompression of file {}: {}", file, r);
        }
    } catch (InterruptedException e) {
        LOG.error(e.getMessage());
    }
}

From source file:jp.co.tis.gsp.tools.dba.util.ProcessUtil.java

public static void exec(Map<String, String> environment, String... args)
        throws IOException, InterruptedException {

    Process process = null;/*from w ww  .  j a  v a 2  s  . co  m*/
    InputStream stdout = null;
    BufferedReader br = null;

    try {
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.redirectErrorStream(true);
        if (environment != null) {
            pb.environment().putAll(environment);
        }

        process = pb.start();
        stdout = process.getInputStream();
        br = new BufferedReader(new InputStreamReader(stdout));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(stdout);

        if (process != null) {
            process.destroy();
        }
    }
}

From source file:com.frostwire.desktop.DesktopVPNMonitor.java

private static String readProcessOutput(String command, String arguments) {
    String result = "";
    ProcessBuilder pb = new ProcessBuilder(command, arguments);
    pb.redirectErrorStream(true);/*ww  w. ja v  a2  s.c o m*/
    try {
        Process process = pb.start();
        InputStream stdout = process.getInputStream();
        final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout));
        String line;

        try {
            StringBuilder sb = new StringBuilder();
            while ((line = brstdout.readLine()) != null) {
                sb.append(line + "\r\n");
            }

            result = sb.toString();
        } catch (Throwable e) {
            LOG.error("Error reading routing table command output", e);
        } finally {
            IOUtils.closeQuietly(brstdout);
            IOUtils.closeQuietly(stdout);
        }

    } catch (Throwable e) {
        LOG.error("Error executing routing table command", e);
    }
    return result;
}

From source file:io.github.retz.executor.FileManager.java

private static void fetchHDFSFile(String file, String dest) throws IOException {
    LOG.debug("Downloading {} to {} as HDFS file", file, dest);
    // TODO: make 'hadoop' command arbitrarily specifiable, but given that mesos-agent (slave) can fetch hdfs:// files, it should be also available, too
    String[] hadoopCmd = { "hadoop", "fs", "-copyToLocal", file, dest };
    LOG.debug("Command: {}", String.join(" ", hadoopCmd));
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(hadoopCmd).inheritIO();/* w w w  . j ava2s . com*/

    Process p = pb.start();
    while (true) {
        try {
            int result = p.waitFor();
            if (result != 0) {
                LOG.error("Downloading {} failed: {}", file, result);
            } else {
                LOG.info("Download finished: {}", file);
            }
            return;
        } catch (InterruptedException e) {
            LOG.error("Download process interrupted: {}", e.getMessage()); // TODO: debug?
        }
    }
}

From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java

private static void runLinter(List<String> command) throws IOException {
    LOG.finer("checkstyle command: " + command);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process pylint = processBuilder.start();

    try {//from  w  ww.  jav a2s.  com
        pylint.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException("python checkstyle command was interrupted: " + command, e);
    }

    if (pylint.exitValue() == 30) {
        LOG.warning("python checkstyle detected bad styles.");
        // SUPPRESS CHECKSTYLE RegexpSinglelineJava
        System.exit(1);
    }

    if (pylint.exitValue() != 0) {
        throw new RuntimeException("python checkstyle command failed with status " + pylint.exitValue());
    }
}

From source file:Main.java

public static long getNetSpeed() {
    ProcessBuilder cmd;
    long readBytes = 0;
    BufferedReader rd = null;/*ww  w . j  a v  a2 s. c  o  m*/
    try {
        String[] args = { "/system/bin/cat", "/proc/net/dev" };
        cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        rd = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            if (line.contains("lan0") || line.contains("eth0")) {
                String[] delim = line.split(":");
                if (delim.length >= 2) {
                    readBytes = parserNumber(delim[1].trim());
                    break;
                }
            }
        }
        rd.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return readBytes;
}

From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java

private static void runLinter(List<String> command) throws IOException {
    LOG.fine("checkstyle command: " + command);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process cpplint = processBuilder.start();

    try {/*from   www . j  a v a 2s  .c  o  m*/
        cpplint.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException("cpp checkstyle command was interrupted: " + command, e);
    }

    if (cpplint.exitValue() == 1) {
        LOG.warning("cpp checkstyle detected bad styles.");
        // SUPPRESS CHECKSTYLE RegexpSinglelineJava
        System.exit(1);
    }

    if (cpplint.exitValue() != 0) {
        throw new RuntimeException("cpp checkstyle command failed with status " + cpplint.exitValue());
    }
}

From source file:com.act.utils.ProcessRunner.java

/**
 * Run's a child process using the specified command and arguments, timing out after a specified number of seconds
 * if the process does not terminate on its own in that time.
 * @param command The process to run.//from  ww  w.  ja v  a2 s  . c o m
 * @param args The arguments to pass to that process.
 * @param timeoutInSeconds A timeout to impose on the child process; an InterruptedException is likely to occur
 *                         when the child process times out.
 * @return The exit code of the child process.
 * @throws InterruptedException
 * @throws IOException
 */
public static int runProcess(String command, List<String> args, Long timeoutInSeconds)
        throws InterruptedException, IOException {
    /* The ProcessBuilder doesn't differentiate the command from its arguments, but we do in our API to ensure the user
     * doesn't just pass us a single string command, which invokes the shell and can cause all sorts of bugs and
     * security issues. */
    List<String> commandAndArgs = new ArrayList<String>(args.size() + 1) {
        {
            add(command);
            addAll(args);
        }
    };
    ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs);
    LOGGER.info("Running child process: %s", StringUtils.join(commandAndArgs, " "));

    Process p = processBuilder.start();
    // Log whatever the child writes.
    new StreamLogger(p.getInputStream(), l -> LOGGER.info("[child STDOUT]: %s", l)).run();
    new StreamLogger(p.getErrorStream(), l -> LOGGER.warn("[child STDERR]: %s", l)).run();
    // Wait for the child process to exit, timing out if it takes to long to finish.
    if (timeoutInSeconds != null) {
        p.waitFor(timeoutInSeconds, TimeUnit.SECONDS);
    } else {
        p.waitFor();
    }

    // 0 is the default success exit code in *nix land.
    if (p.exitValue() != 0) {
        LOGGER.error("Child process exited with non-zero status code: %d", p.exitValue());
    }

    return p.exitValue();
}

From source file:Main.java

private static void killprocessNormal(String proc, int killMethod) {
    try {/* www  .  j av  a  2  s . com*/
        ArrayList<String> pid_list = new ArrayList<String>();

        ProcessBuilder execBuilder = null;

        execBuilder = new ProcessBuilder("sh", "-c", "ps |grep " + proc);

        execBuilder.redirectErrorStream(true);

        Process exec = null;
        exec = execBuilder.start();
        InputStream is = exec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            String regEx = "\\s[0-9][0-9]*\\s";
            Pattern pat = Pattern.compile(regEx);
            Matcher mat = pat.matcher(line);
            if (mat.find()) {
                String temp = mat.group();
                temp = temp.replaceAll("\\s", "");
                pid_list.add(temp);
            }
        }

        for (int i = 0; i < pid_list.size(); i++) {
            execBuilder = new ProcessBuilder("su", "-c", "kill", "-" + killMethod, pid_list.get(i));
            exec = null;
            exec = execBuilder.start();

            execBuilder = new ProcessBuilder("su", "-c", "kill" + " -" + killMethod + " " + pid_list.get(i));
            exec = null;
            exec = execBuilder.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.frederikam.fredboat.bootloader.Bootloader.java

private static Process boot() throws IOException {
    //Check that we are not booting too quick (we could be stuck in a login loop)
    if (System.currentTimeMillis() - lastBoot > 3000 * 1000) {
        recentBoots = 0;/*from  w ww .  jav a 2 s .  c  o  m*/
    }

    recentBoots++;
    lastBoot = System.currentTimeMillis();

    if (recentBoots >= 4) {
        System.out.println("[BOOTLOADER] Failed to restart 3 times, probably due to login errors. Exiting...");
        System.exit(-1);
    }

    //ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + "/bin/java -jar "+new File("FredBoat-1.0.jar").getAbsolutePath())
    ProcessBuilder pb = new ProcessBuilder().inheritIO();
    ArrayList<String> list = new ArrayList<>();
    command.forEach((Object str) -> {
        list.add((String) str);
    });

    pb.command(list);

    Process process = pb.start();
    return process;
}