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:net.opentsdb.tsd.GraphHandler.java

/**
 * Runs Gnuplot in a subprocess to generate the graph.
 * <strong>This function will block</strong> while Gnuplot is running.
 * @param query The query being handled (for logging purposes).
 * @param basepath The base path used for the Gnuplot files.
 * @param plot The plot object to generate Gnuplot's input files.
 * @return The number of points plotted by Gnuplot (0 or more).
 * @throws IOException if the Gnuplot files can't be written, or
 * the Gnuplot subprocess fails to start, or we can't read the
 * graph from the file it produces, or if we have been interrupted.
 * @throws GnuplotException if Gnuplot returns non-zero.
 *//*from w  ww .j  a va 2 s . c om*/
static int runGnuplot(final HttpQuery query, final String basepath, final Plot plot) throws IOException {
    final int nplotted = plot.dumpToFiles(basepath);
    final long start_time = System.nanoTime();
    final Process gnuplot = new ProcessBuilder(GNUPLOT, basepath + ".out", basepath + ".err",
            basepath + ".gnuplot").start();
    final int rv;
    try {
        rv = gnuplot.waitFor(); // Couldn't find how to do this asynchronously.
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // Restore the interrupted status.
        throw new IOException("interrupted", e); // I hate checked exceptions.
    } finally {
        // We need to always destroy() the Process, otherwise we "leak" file
        // descriptors and pipes.  Unless I'm blind, this isn't actually
        // documented in the Javadoc of the !@#$%^ JDK, and in Java 6 there's no
        // way to ask the stupid-ass ProcessBuilder to not create fucking pipes.
        // I think when the GC kicks in the JVM may run some kind of a finalizer
        // that closes the pipes, because I've never seen this issue on long
        // running TSDs, except where ulimit -n was low (the default, 1024).
        gnuplot.destroy();
    }
    gnuplotlatency.add((int) ((System.nanoTime() - start_time) / 1000000));
    if (rv != 0) {
        final byte[] stderr = readFile(query, new File(basepath + ".err"), 4096);
        // Sometimes Gnuplot will error out but still create the file.
        new File(basepath + ".png").delete();
        if (stderr == null) {
            throw new GnuplotException(rv);
        }
        throw new GnuplotException(new String(stderr));
    }
    // Remove the files for stderr/stdout if they're empty.
    deleteFileIfEmpty(basepath + ".out");
    deleteFileIfEmpty(basepath + ".err");
    return nplotted;
}

From source file:br.com.autonomiccs.autonomic.plugin.common.utils.ShellCommandUtils.java

/**
 * It executes the specified shell command and wait for the
 * end of command execution to continue with the application
 * flow./*from   www  .  jav a  2  s  .c om*/
 *
 * If an exception happens, it will get logged and the flow of execution continues.
 * This method will not break the flow of execution if an expected exception happens.
 *
 * @param command
 *            The command that will be executed.
 * @return
 *         A <code>String</code> that is the result from
 *         command executed.
 */
public String executeCommand(String command) {
    Writer output = new StringWriter();
    try {
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        IOUtils.copy(p.getInputStream(), output);
    } catch (IOException | InterruptedException e) {
        logger.error(String.format("An error happened while executing command[%s]", command), e);
    }
    return output.toString();
}

From source file:org.segator.plex.cloud.transcoding.NFSConfigurerBO.java

private void refreshExport() throws IOException, InterruptedException {
    String exportPermission = "";
    for (String ip : ipList) {
        exportPermission += ip + "(rw,sync,secure,no_subtree_check,root_squash) ";
    }//  w  w w  .j ava 2 s  . com
    String exportFileString = "/transcode " + exportPermission + "\n/usr/lib/plexmediaserver "
            + exportPermission + "\n" + "\"/config/Library/Application Support\" " + exportPermission + "\n"
            + applicationParameters.getMediaDirectory() + " " + exportPermission;
    File exportsFile = new File("/etc/exports");
    if (exportsFile.exists()) {
        exportsFile.delete();
    }
    FileUtils.writeStringToFile(exportsFile, exportFileString, "UTF-8");
    Process process = new ProcessBuilder("exportfs", "-r").start();
    process.waitFor();
}

From source file:com.thoughtworks.go.util.command.ProcessRunner.java

public int run() throws IOException, InterruptedException {
    File workingDir = builder.directory() == null ? new File(".") : builder.directory();
    System.out.println(String.format("Trying to run command: %s from %s",
            Arrays.toString(builder.command().toArray()), workingDir.getAbsolutePath()));
    Process process = builder.start();
    int exitCode = process.waitFor();
    System.out.println(/* w w w.jav  a 2s.  c o m*/
            "Finished command: " + Arrays.toString(builder.command().toArray()) + ". Exit code: " + exitCode);
    if (exitCode != 0) {
        if (failOnError) {
            throw new RuntimeException(String.format("Command exited with code %s. \n Exception: %s", exitCode,
                    IOUtils.toString(process.getErrorStream())));
        } else {
            LOGGER.error("Command exited with code {}. \n Exception: {}", exitCode,
                    IOUtils.toString(process.getErrorStream()));
        }
    }
    return exitCode;
}

From source file:Main.java

public static int shellExecute(String strCommand, boolean bDisplayProgramOutput) {
    Process p = null;
    try {//from  w ww.  j a va  2  s. c om
        p = Runtime.getRuntime().exec(strCommand);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (p != null) {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        try {
            line = input.readLine();
            if (bDisplayProgramOutput && line != null)
                System.out.println(line);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        while (line != null) {
            try {
                line = input.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (bDisplayProgramOutput && line != null)
                System.out.println(line);
        }

        try {
            p.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return p.exitValue();
    }

    return -1;
}

From source file:com.wenzani.maven.mongodb.StartMongoDb.java

private void chmodMongoD() throws IOException, InterruptedException {
    String chmod = new StringBuilder("chmod +x ").append(getMongoD()).toString();
    Process process = Runtime.getRuntime().exec(chmod);
    process.waitFor();
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

private static String executeVagrantScript(ProcessBuilder pb, String node, String scriptName) throws Exception {
    pb.command("vagrant", "ssh", node, "--", pb.environment().get("SCRIPT_HOME") + scriptName);
    Process p = pb.start();//w w  w .  j a  v  a2 s.  co m
    p.waitFor();
    InputStream input = p.getInputStream();
    return IOUtils.toString(input, StandardCharsets.UTF_8.name());
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

private static String executeVagrantManagix(ProcessBuilder pb, String command) throws Exception {
    pb.command("vagrant", "ssh", "cc", "--", pb.environment().get("MANAGIX_HOME") + command);
    Process p = pb.start();/*from  w w  w .  j  ava2 s  . com*/
    p.waitFor();
    InputStream input = p.getInputStream();
    return IOUtils.toString(input, StandardCharsets.UTF_8.name());
}

From source file:io.pcp.parfait.dxm.PcpClient.java

String getMetric(String metricName) throws Exception {
    Process exec = Runtime.getRuntime().exec("pmdumptext -s 1 -t 0.001 -r " + metricName);
    exec.waitFor();
    if (exec.exitValue() != 0) {
        throw new PcpFetchException(exec);
    }//ww w .  j av a2 s . c om

    String result = IOUtils.toString(exec.getInputStream());
    Pattern pattern = Pattern.compile("\t(.*?)\n");
    Matcher matcher = pattern.matcher(result);
    if (matcher.find()) {
        return matcher.group(1);
    }
    throw new PcpFetchException("Could not find metric in the output: " + result);
}

From source file:com.formkiq.core.service.sign.MacWrapperConfig.java

/**
 * Attempts to find an executable in the system path.
 * @param executable {@link String}//from   w w w  .j a v  a2s  .  c o  m
 * @return {@link String}
 */
public String findExecutable(final String executable) {
    try {
        String osname = System.getProperty("os.name").toLowerCase();

        String cmd = osname.contains("windows") ? "where " + executable : "which " + executable;

        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();

        String text = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());

        if (text.isEmpty()) {
            throw new RuntimeException();
        }

        return text;

    } catch (InterruptedException e) {
        return null;
    } catch (IOException e) {
        return null;
    } catch (RuntimeException e) {
        return null;
    }
}