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:com.streamsets.datacollector.util.ClusterUtil.java

public static void killYarnApp(String testName) throws Exception {
    // TODO - remove this hack
    // We dont know app id, but yarn creates its data dir under $HOME/target/TESTNAME, so kill the process by
    // grep for the yarn testname
    String killCmd = signalCommand(testName, "SIGKILL");
    LOG.info("Signal kill command to yarn app " + killCmd);
    String[] killCommand = new String[] { "/usr/bin/env", "bash", "-c", killCmd };
    Process p = Runtime.getRuntime().exec(killCommand);
    p.waitFor();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = "";
    LOG.info("Process output is ");
    while ((line = reader.readLine()) != null) {
        LOG.debug(line + "\n");
    }/*from  www .j  av  a2s  .c  o  m*/
}

From source file:com.unresyst.DealRecommender.java

private static String runCommand(String... commands) throws IOException, InterruptedException {
    // generate a script file containg the command to run
    final File scriptFile = new File("/tmp/runcommand.sh");
    PrintWriter w = new PrintWriter(scriptFile);
    w.println("#!/bin/sh");
    for (String command : commands) {
        w.println(command);//from  w  w  w  . ja v a 2 s.c om
    }
    w.close();

    // make the script executable
    //System.out.println("absolute path: " + scriptFile.getAbsolutePath());
    Process p = Runtime.getRuntime().exec("chmod +x " + scriptFile.getAbsolutePath());
    p.waitFor();

    // execute the script
    p = Runtime.getRuntime().exec(scriptFile.getAbsolutePath());
    p.waitFor();
    BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String toReturn = "";
    String line = "";
    while ((line = stdin.readLine()) != null) {
        toReturn += line + "\n";
    }
    while ((line = stderr.readLine()) != null) {
        toReturn += "err: " + line + "\n";
    }

    scriptFile.delete();
    return toReturn;
}

From source file:Main.java

public static boolean copyFile(String src, String dest) {
    File test = new File(dest);
    if (!test.exists()) {
        test.mkdirs();//from  w  ww. jav  a2 s.  c om
    }
    Process p;
    try {
        p = Runtime.getRuntime().exec("cp " + src + " " + dest);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    try {
        p.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:net.floodlightcontroller.queuepusher.QueuePusherSwitchMapper.java

/**
 * Runs the given command//from w w w  . j a v a  2s  . co m
 * 
 * @param cmd Command to execute
 * @return 0: (int)exit code 1: (string)stdout 2: (string)stderr
 */

private static Object[] eval(String cmd) {

    Object[] rsp = new Object[3];
    Runtime rt = Runtime.getRuntime();
    Process proc = null;

    try {
        proc = rt.exec(cmd);
        proc.waitFor();
        rsp[0] = proc.exitValue();
    } catch (InterruptedException e) {
        rsp[0] = 1;
    } catch (IOException e) {
        rsp[0] = 1;
    } finally {
        if (proc == null) {
            rsp[0] = 1;
        } else {

            try {

                BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

                String temp;
                StringBuilder sb = new StringBuilder();
                while ((temp = stdout.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[1] = sb.toString();
                sb = new StringBuilder();
                while ((temp = stderr.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[2] = sb.toString();

            } catch (IOException e) {
                rsp[0] = 1;
            }

        }
    }

    return rsp;

}

From source file:com.ms.commons.standalone.utils.Shell.java

public static String exec(String cmd) {
    Process process = null;
    String[] cmds = { "/bin/bash", "-c", cmd, };
    try {//www  .ja  va  2 s.c o  m
        process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
        byte[] buffer = IOUtils.toByteArray(process.getInputStream());
        process.waitFor();
        return new String(buffer, "utf-8");
    } catch (Exception e) {
        logger.error("runtime.exec cmd: " + cmd + " failed", e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return "";
}

From source file:Main.java

public static void storeBuildPropertyBatched(Context c, String propArgument) {
    StringBuilder propName = new StringBuilder("");
    StringBuilder propValue = new StringBuilder("");
    StringBuilder commandLine = new StringBuilder("");
    boolean isValue = false;
    for (int i = 0; i < propArgument.length(); i++) {
        char ch = propArgument.charAt(i);
        if (ch == '=' && isValue == false) {
            isValue = true;//w w  w  .j ava  2s  .  c om
        } else if (ch == ';') {
            // Store the build property
            if (isBuildPropertyAvaliable(c, propName.toString())) {
                // Change build property manually.
                commandLine.append("busybox sed -i \"s/" + propName.toString() + "=.*/" + propName.toString()
                        + "=" + propValue.toString() + "/g\" /system/build.prop ; ");
            } else {
                // Write new build property manually.
                commandLine.append("echo " + propName.toString() + "=" + propValue.toString()
                        + " >> /system/build.prop ; ");
            }

            // Clear the value
            isValue = false;
            propName = new StringBuilder("");
            propValue = new StringBuilder("");
        } else {
            if (isValue)
                propValue.append(ch);
            else
                propName.append(ch);
        }
    }

    // Execute the process
    Process p = null;
    try {
        remountSystem(c);

        p = runSuCommandAsync(c, commandLine.toString());
        p.waitFor();
    } catch (Exception d) {
        Log.e("Helper", "Failed to batch store build.prop. errcode:" + d.toString());
    }
}

From source file:com.baifendian.swordfish.execserver.common.FunctionUtil.java

/**
 *  udf jar/*  ww w  . java 2 s  .  c  o  m*/
 */
private static void uploadUdfJars(Set<String> resources, String tarDir, String srcDir, Logger logger)
        throws IOException, InterruptedException {
    HdfsClient hdfsClient = HdfsClient.getInstance();

    if (!hdfsClient.exists(tarDir)) {
        hdfsClient.mkdir(tarDir);
    }

    for (String res : resources) {
        // ?, ?
        if (!hdfsClient.exists(String.format("%s/%s", tarDir, res))) {
            String cmd = String.format("hdfs dfs -put %s/%s %s", srcDir, res, tarDir);

            logger.debug("cmd:{}", cmd);

            Process process = Runtime.getRuntime().exec(cmd);
            int ret = process.waitFor();
            if (ret != 0) {
                logger.error("run cmd:" + cmd + " error");

                String msg = IOUtils.toString(process.getErrorStream(), Charset.forName("UTF-8"));

                logger.error(msg);

                throw new ExecException(msg);
            }
        }
    }
}

From source file:name.milesparker.gerrit.analysis.CollectGit.java

protected static void execOuput(String command, String directory, String outputFile) {
    try {//  ww  w . j  a  v  a  2 s  .  c  o  m
        Process process = new ProcessBuilder(StringUtils.split(command)).directory(new File(directory))
                .redirectError(Redirect.INHERIT).redirectOutput(new File(outputFile)).start();
        process.waitFor();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.o2d.pkayjava.editor.utils.Overlap2DUtils.java

private static String getMyDocumentsLocation() {
    String myDocuments = null;/*from   ww w  .j  a  va  2 s.  com*/
    try {
        if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
            myDocuments = System.getProperty("user.home") + File.separator + "Documents";
        }
        if (SystemUtils.IS_OS_WINDOWS) {
            Process p = Runtime.getRuntime().exec(
                    "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
            p.waitFor();

            InputStream in = p.getInputStream();
            byte[] b = new byte[in.available()];
            in.read(b);
            in.close();

            myDocuments = new String(b);
            myDocuments = myDocuments.split("\\s\\s+")[4];
        }
        if (SystemUtils.IS_OS_LINUX) {
            myDocuments = System.getProperty("user.home") + File.separator + "Documents";
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }

    return myDocuments;
}

From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java

public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome,
        int start, int end) {

    String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand");

    String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath");

    String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir");

    String tmpDir = RESOURCE_BUNDLE.getString("tmpDir");

    Mapping mapping = null;/*from w  w w . j  av  a2  s. com*/

    Runtime r = Runtime.getRuntime();

    String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8));

    String inputFilename = rootFilename + "-" + fromAssembly + ".bed";
    String outputFilename = rootFilename + "-" + toAssembly + ".bed";
    String unmappedFilename = rootFilename + "-" + "unmapped.bed";

    String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0)
            + toAssembly.toLowerCase().substring(1) + ".over.chain.gz";

    try {

        File tmpDirFile = new File(tmpDir);

        // if the directory does not exist, create it
        if (false == tmpDirFile.exists()) {
            System.out.println("creating directory: " + tmpDir);
            boolean result = tmpDirFile.mkdir();

            if (result) {
                System.out.println("DIR created");
            }
        }

        // Write input bed file
        File inputFile = new File(tmpDir + inputFilename);
        // if file doesnt exists, then create it
        if (!inputFile.exists()) {
            inputFile.createNewFile();
        }

        FileWriter fw = new FileWriter(inputFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(chromosome + "\t" + start + "\t" + end + "\n");
        bw.close();

        String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand,
                tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename,
                tmpDir + unmappedFilename);
        System.out.println(commandArgs);

        Process p = r.exec(commandArgs);

        p.waitFor();

        BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }
        b.close();

        b = new BufferedReader(new FileReader(tmpDir + outputFilename));

        while ((line = b.readLine()) != null) {
            String[] cells = line.split("\t");
            String newChromosome = cells[0];
            int newStart = Integer.parseInt(cells[1]);
            int newEnd = Integer.parseInt(cells[2]);
            mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd);
        }
        b.close();

        // delete
        File delete = new File(tmpDir + inputFilename);
        delete.delete();

        delete = new File(tmpDir + outputFilename);
        delete.delete();

        delete = new File(tmpDir + unmappedFilename);
        delete.delete();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return mapping;
}