Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

In this page you can find the example usage for java.lang Process waitFor.

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:SwiftWork.java

/**
 * LINUX Operations//from w w w  .  j a v  a2s  .  com
 */

private static void linuxDeleteFile(String file) {
    String command = "/bin/rm -f " + file;
    Process p;
    try {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        System.out.println("File :" + file + " is deleted successfully");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("File :" + file + " is NOT deleted successfully");
    }

}

From source file:com.dtolabs.rundeck.core.utils.ScriptExecUtil.java

/**
 * Run a command with environment variables in a working dir, and copy the streams
 *
 * @param command      the command array to run
 * @param envMap       the environment variables to pass in
 * @param workingdir   optional working dir location (or null)
 * @param outputStream stream for stdout
 * @param errorStream  stream for stderr
 *
 * @return the exit code of the command//w  w w.  j  a  v  a2 s .c om
 *
 * @throws IOException          if any IO exception occurs
 * @throws InterruptedException if interrupted while waiting for the command to finish
 */
public static int runLocalCommand(final String[] command, final Map<String, String> envMap,
        final File workingdir, final OutputStream outputStream, final OutputStream errorStream)
        throws IOException, InterruptedException {
    final String[] envarr = createEnvironmentArray(envMap);

    final Runtime runtime = Runtime.getRuntime();
    final Process exec = runtime.exec(command, envarr, workingdir);
    final Streams.StreamCopyThread errthread = Streams.copyStreamThread(exec.getErrorStream(), errorStream);
    final Streams.StreamCopyThread outthread = Streams.copyStreamThread(exec.getInputStream(), outputStream);
    errthread.start();
    outthread.start();
    exec.getOutputStream().close();
    final int result = exec.waitFor();
    errthread.join();
    outthread.join();
    if (null != outthread.getException()) {
        throw outthread.getException();
    }
    if (null != errthread.getException()) {
        throw errthread.getException();
    }
    return result;
}

From source file:com.yahoo.sql4dclient.Main.java

/**
 * Run the command synchronously and return clubbed standard error and 
 * output stream's data.//from w w  w.j  a v a2 s .c o  m
 */
private static String runCommand(final String[] cmd) throws IOException, InterruptedException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Process process = Runtime.getRuntime().exec(cmd);
    int c;
    InputStream in = process.getInputStream();
    while ((c = in.read()) != -1) {
        baos.write(c);
    }
    in = process.getErrorStream();
    while ((c = in.read()) != -1) {
        baos.write(c);
    }
    process.waitFor();
    return new String(baos.toByteArray());
}

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;
    DataOutputStream out = null;//  w  w w . j ava2 s .  c om
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
        shell = Runtime.getRuntime().exec(startCommand);
        out = new DataOutputStream(shell.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
        for (String command : commands) {
            out.writeBytes(command + "\n");
            out.flush();
        }
        out.writeBytes("exit\n");
        out.flush();
        shell.waitFor();
    } catch (Exception e) {
        Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {

        }
    }
    return reader;
}

From source file:Main.java

public static String execRootCmd(String[] cmds) {
    String result = "";
    DataOutputStream dos = null;//from w w  w .ja  v  a2s.c om
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        for (String cmd : cmds) {
            Log.i("CmdUtils", cmd);
            dos.writeBytes(cmd + "\n");
            dos.flush();
        }
        dos.writeBytes("exit\n");
        dos.flush();
        String line;
        while ((line = dis.readLine()) != null) {
            Log.d("result", line);
            result += line;
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:ca.uqac.dim.net.verify.NetworkChecker.java

/**
 * Runs the NuSMV program as a spawned command-line process, and passes the
 * file to process through that process' standard input
 * @param file_contents A String containing the NuSMV model to process
 *///  w  w w.  ja v a2  s .  co  m
private static RuntimeInfos runNuSMV(String file_contents) throws IOException, InterruptedException {
    StringBuilder sb = new StringBuilder();
    Runtime rt = Runtime.getRuntime();
    long time_start = 0, time_end = 0;
    // Start NuSMV, and feed the model through its standard input
    time_start = System.currentTimeMillis();
    Process p = rt.exec(NUSMV_EXEC);
    OutputStream o = p.getOutputStream();
    InputStream i = p.getInputStream();
    InputStream e = p.getErrorStream();
    Writer w = new PrintWriter(o);
    w.write(file_contents);
    w.close(); // Close stdin so NuSMV can start processing it
    // Wait for NuSMV to be done, then collect its standard output
    int exitVal = p.waitFor();
    if (exitVal != 0)
        throw new IOException("NuSMV's return value indicates an error in processing its input");
    BufferedReader br = new BufferedReader(new InputStreamReader(i));
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    time_end = System.currentTimeMillis();
    i.close(); // Close stdout
    e.close(); // Close stderr
    return new RuntimeInfos(sb.toString(), time_end - time_start);
}

From source file:ee.ria.xroad.proxy.messagelog.LogArchiver.java

private static void runTransferCommand(String transferCommand) {
    if (isBlank(transferCommand)) {
        return;/*from ww  w .  j av  a  2  s.  c  om*/
    }

    log.info("Transferring archives with shell command: \t{}", transferCommand);

    try {
        String[] command = new String[] { "/bin/bash", "-c", transferCommand };

        Process process = new ProcessBuilder(command).start();

        StandardErrorCollector standardErrorCollector = new StandardErrorCollector(process);

        new StandardOutputReader(process).start();

        standardErrorCollector.start();
        standardErrorCollector.join();

        process.waitFor();

        int exitCode = process.exitValue();
        if (exitCode != 0) {
            String errorMsg = String.format(
                    "Running archive transfer command '%s' " + "exited with status '%d'", transferCommand,
                    exitCode);

            log.error("{}\n -- STANDARD ERROR START\n{}\n" + " -- STANDARD ERROR END", errorMsg,
                    standardErrorCollector.getStandardError());
        }
    } catch (Exception e) {
        log.error("Failed to execute archive transfer command '{}'", transferCommand, e);
    }
}

From source file:edu.cwru.jpdg.Dotty.java

/**
 * Compiles the graph to dotty./*w  w  w.j  a v a 2  s . c  o  m*/
 */
public static String dotty(String graph) {

    byte[] bytes = graph.getBytes();

    try {
        ProcessBuilder pb = new ProcessBuilder("dotty");
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        Process p = pb.start();
        OutputStream stdin = p.getOutputStream();
        stdin.write(bytes);
        stdin.close();

        String line;
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        List<String> stdout_lines = new ArrayList<String>();
        line = stdout.readLine();
        while (line != null) {
            stdout_lines.add(line);
            line = stdout.readLine();
        }
        if (p.waitFor() != 0) {
            throw new RuntimeException("javac failed");
        }

        return StringUtils.join(stdout_lines, "\n");
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static void revokeCert(Settings settings, String certFile, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Revoking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
    } else {/*from   w  w  w. j  ava  2  s  . c  o  m*/
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-revoke");
    cmds.add(certFile);

    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to revoke certificate. Exit value: " + exitValue);
    }
    logger.info("Revoked certificate.");
    //update the crl
    createCRL(settings, intermediate);
}

From source file:Main.java

public static String RunExecCmd(StringBuilder sb, Boolean su) {

    String shell;//from  w  w  w  .ja va2 s  . com
    if (su) {
        shell = "su";
    } else {
        shell = "sh";
    }

    Process process = null;

    DataOutputStream processOutput = null;
    InputStream processInput = null;
    String outmsg = new String();

    try {

        process = Runtime.getRuntime().exec(shell);
        processOutput = new DataOutputStream(process.getOutputStream());
        processOutput.writeBytes(sb.toString() + "\n");
        processOutput.writeBytes("exit\n");
        processOutput.flush();
        processInput = process.getInputStream();
        outmsg = inputStream2String(processInput, "UTF-8");
        process.waitFor();

    } catch (Exception e) {
        //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
        //return;
    }

    finally {
        try {
            if (processOutput != null) {
                processOutput.close();
            }
            process.destroy();
        } catch (Exception e) {
        }

    }
    return outmsg;
}