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:io.ingenieux.lambda.shell.LambdaShell.java

private static void runCommandArray(OutputStream os, String... args) throws Exception {
    PrintWriter pw = new PrintWriter(os, true);

    File tempPath = File.createTempFile("tmp-", ".sh");

    IOUtils.write(StringUtils.join(args, " "), new FileOutputStream(tempPath));

    List<String> processArgs = new ArrayList<>(Arrays.asList("/bin/bash", "-x", tempPath.getAbsolutePath()));

    ProcessBuilder psBuilder = new ProcessBuilder(processArgs).//
            redirectErrorStream(true);//

    final Process process = psBuilder.start();

    final Thread t = new Thread(() -> {
        try {//from w  w  w.  j a  v a2 s  .c o  m
            IOUtils.copy(process.getInputStream(), os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    t.start();

    process.waitFor();

    t.join();

    int resultCode = process.exitValue();
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static void readProxyVersion() {
    try {/*from www .  j  a v  a  2 s .  c o m*/
        String cmd;

        if (Files.exists(Paths.get("/etc/redhat-release"))) {
            cmd = "rpm -q --queryformat '%{VERSION}-%{RELEASE}' xroad-proxy";
        } else {
            cmd = "dpkg-query -f '${Version}' -W xroad-proxy";
        }

        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        version = IOUtils.toString(p.getInputStream()).replace("'", "");

        if (StringUtils.isBlank(version)) {
            version = "unknown";

            log.warn("Unable to read proxy version: {}", IOUtils.toString(p.getErrorStream()));
        }
    } catch (Exception ex) {
        version = "unknown";
        log.warn("Unable to read proxy version", ex);
    }
}

From source file:Main.java

public static boolean getRootPermission(Context context) {
    String packageCodePath = context.getPackageCodePath();
    Process process = null;
    DataOutputStream os = null;//from   w w w  .ja  v a 2s.  c  o m
    try {
        String cmd = "chmod 777 " + packageCodePath;
        process = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(cmd + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (Exception e) {
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return true;
}

From source file:Main.java

public static boolean executeAsRoot(String command) {
    try {/*from   www.  j  a  v a2  s  .  c  om*/

        Process suProcess = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

        os.writeBytes(command + "\n");
        os.flush();
        Log.d("ROOT", command);

        os.writeBytes("exit\n");
        os.flush();

        try {
            int suProcessRet = suProcess.waitFor();
            if (255 != suProcessRet)
                return true;
            else
                return false;
        } catch (Exception ex) {
            Log.w("ROOT-ERROR", ex);
        }
    } catch (IOException ex) {
        Log.w("ROOT", "Can't get root access", ex);
    } catch (SecurityException ex) {
        Log.w("ROOT", "Can't get root access", ex);
    } catch (Exception ex) {
        Log.w("ROOT", "Error executing internal operation", ex);
    }
    return false;
}

From source file:Main.java

public static List<String> execAsAdmin(String... commands) throws Exception {
    List<String> res = new ArrayList<String>();

    Process process = Runtime.getRuntime().exec("su");
    DataOutputStream os = new DataOutputStream(process.getOutputStream());
    for (String single : commands) {
        os.writeBytes(single + "\n");
        os.flush();//from  ww w .ja v  a 2s.  c om
        //res.add(osRes.readLine());
    }
    os.writeBytes("exit\n");
    os.flush();
    //process.destroy();
    process.waitFor();

    return res;
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }/*  ww w.ja  v a 2  s .co m*/

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}

From source file:com.yahoo.storm.yarn.TestIntegration.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static int execute(List<String> cmd) throws InterruptedException, IOException {
    LOG.info(Joiner.on(" ").join(cmd));
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map env = pb.environment();/*from  w  w w  .  ja v a 2s. c o  m*/
    env.putAll(System.getenv());
    env.put(Environment.PATH.name(),
            "bin:" + storm_home + File.separator + "bin:" + env.get(Environment.PATH.name()));
    String yarn_conf_dir = yarn_site_xml.getParent().toString();
    env.put("STORM_YARN_CONF_DIR", yarn_conf_dir);
    List<URL> logback_xmls = Utils.findResources("logback.xml");
    if (logback_xmls != null && logback_xmls.size() >= 1) {
        String logback_xml = logback_xmls.get(0).getFile();
        LOG.debug("logback_xml:" + yarn_conf_dir + File.separator + "logback.xml");
        FileUtils.copyFile(new File(logback_xml), new File(yarn_conf_dir + File.separator + "logback.xml"));
    }
    List<URL> log4j_properties = Utils.findResources("log4j.properties");
    if (log4j_properties != null && log4j_properties.size() >= 1) {
        String log4j_properties_file = log4j_properties.get(0).getFile();
        LOG.debug("log4j_properties_file:" + yarn_conf_dir + File.separator + "log4j.properties");
        FileUtils.copyFile(new File(log4j_properties_file),
                new File(yarn_conf_dir + File.separator + "log4j.properties"));
    }

    Process proc = pb.start();
    Util.redirectStreamAsync(proc.getInputStream(), System.out);
    Util.redirectStreamAsync(proc.getErrorStream(), System.err);
    int status = proc.waitFor();
    return status;
}

From source file:net.mamian.mySpringboot.utils.ShellUtils.java

/**
 * /*from   w  w  w.  j a va 2 s  . com*/
 * 
 * @param shPath shell
 * @param param ?
 * @return 
 */
public static int exe(String shPath, String... param) {
    if (StringUtils.isEmpty(shPath)) {
        log.info("shell?shpath={}", shPath);
        return -1;
    }
    Process p;
    try {
        shPath = "chmod 755 " + shPath;
        if (null != param) {
            for (String paramItem : param) {
                shPath += " " + paramItem;
            }
        }
        log.info("shellshpath={}", shPath);
        p = Runtime.getRuntime().exec(shPath);
        p.waitFor();
        log.info("shellshpath={}", shPath);
    } catch (IOException | InterruptedException ex) {
        log.info("shellshpath={} exception={}", shPath, ex);
        return -1;
    }
    return 0;
}

From source file:javadepchecker.Main.java

/**
 * Get jar names from the Gentoo package and store in a collection
 *
 * @param pkg Gentoo package name/* w  ww  . ja va2  s  .com*/
 * @return a collection of jar names
 */
private static Collection<String> getPackageJars(String pkg) {
    ArrayList<String> jars = new ArrayList<>();
    try {
        Process p = Runtime.getRuntime().exec("java-config -p " + pkg);
        p.waitFor();
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String output = in.readLine();
        if (output != null/* package somehow missing*/ && !output.trim().isEmpty()) {
            jars.addAll(Arrays.asList(output.split(":")));
        }
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jars;
}

From source file:com.crushpaper.ThreadedSynchronousStreamReader.java

/**
 * Synchronously forks a child process capturing its standard out and err
 * into StringBuffers. Returns the child process's exit code or -1 if it is
 * not available. It creates threads for each stream because that is
 * required in Java to avoid the possibility of deadlock.
 *///  www .j  a  va  2  s.  co m
public static int exec(StringBuffer output, StringBuffer error, String args[]) {
    try {
        String osName = System.getProperty("os.name");
        if (osName.equals("Windows 95")) {
            String[] prefix = new String[2];
            prefix[0] = "command.com";
            prefix[1] = "/C";
            args = ArrayUtils.addAll(prefix, args);
        } else if (osName.startsWith("Windows")) {
            String[] prefix = new String[2];
            prefix[0] = "cmd.exe";
            prefix[1] = "/C";
            args = ArrayUtils.addAll(prefix, args);
        }

        Runtime runtime = Runtime.getRuntime();
        Process childProcess = runtime.exec(args);
        ReaderThread errorReader = new ReaderThread(childProcess.getErrorStream(), output);
        ReaderThread outputReader = new ReaderThread(childProcess.getInputStream(), error);
        errorReader.start();
        outputReader.start();
        int exitValue = childProcess.waitFor();
        return exitValue;
    } catch (Throwable t) {
        t.printStackTrace();
    }

    return -1;
}