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.thoughtworks.go.utils.CommandUtils.java

private static StringBuilder captureOutput(Process process) throws IOException, InterruptedException {
    BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    StringBuilder result = new StringBuilder();
    result.append("output:\n");
    dump(output, result);//  www . j av a  2  s  . co m
    result.append("error:\n");
    dump(error, result);
    process.waitFor();
    return result;
}

From source file:com.cloudera.sqoop.util.Executor.java

/**
 * Run a command via Runtime.exec(), with its stdout and stderr streams
 * directed to be handled by threads generated by AsyncSinks.
 * Block until the child process terminates. Allows the programmer to
 * specify an environment for the child program.
 *
 * @return the exit status of the ran program
 *//*from   www .  j ava2 s .  c  om*/
public static int exec(String[] args, String[] envp, AsyncSink outSink, AsyncSink errSink) throws IOException {

    // launch the process.
    Process p = Runtime.getRuntime().exec(args, envp);

    // dispatch its stdout and stderr to stream sinks if available.
    if (null != outSink) {
        outSink.processStream(p.getInputStream());
    }

    if (null != errSink) {
        errSink.processStream(p.getErrorStream());
    }

    // wait for the return value.
    while (true) {
        try {
            int ret = p.waitFor();
            return ret;
        } catch (InterruptedException ie) {
            continue;
        }
    }
}

From source file:org.ednovo.gooru.converter.service.ConversionServiceImpl.java

private static void convertHtmlToPdf(String srcFileName, String destFileName, long delayInMillsec) {
    try {//from www .j  a v a2s.  c  om
        String resizeCommand = new String("/usr/bin/wkhtmltopdf@" + srcFileName + "@--redirect-delay@"
                + delayInMillsec + "@" + destFileName);
        String cmdArgs[] = resizeCommand.split("@");
        Process thumsProcess = Runtime.getRuntime().exec(cmdArgs);
        thumsProcess.waitFor();

    } catch (Exception e) {
        logger.error("something went wrong while converting pdf", e);
    }
}

From source file:io.github.bonigarcia.wdm.Downloader.java

public static final File extractMsi(File msi) throws IOException {
    File tmpMsi = new File(Files.createTempDir().getAbsoluteFile() + File.separator + msi.getName());
    Files.move(msi, tmpMsi);/*from  w  w w . j a  v  a 2 s.  co m*/
    log.trace("Temporal msi file: {}", tmpMsi);

    Process process = Runtime.getRuntime()
            .exec(new String[] { "msiexec", "/a", tmpMsi.toString(), "/qb", "TARGETDIR=" + msi.getParent() });
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        log.error("Exception waiting to msiexec to be finished", e);
    } finally {
        process.destroy();
    }

    tmpMsi.delete();

    Collection<File> listFiles = FileUtils.listFiles(new File(msi.getParent()), new String[] { "exe" }, true);
    return listFiles.iterator().next();
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static String executeScript(ProcessBuilder pb, String scriptPath) throws Exception {
    pb.command(scriptPath);//from   w w  w . j a  v  a 2 s .c o m
    Process p = pb.start();
    p.waitFor();
    return getProcessOutput(p);
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static int executeCommandGetReturnCode(String cmd, String workingDir, String executeFrom) {
    if (workingDir == null) {
        workingDir = "/tmp";
    }//from  w ww. ja  v a2s  .  c  o  m
    logger.debug("Execute command: " + cmd + ". Working dir: " + workingDir);
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.debug(line);
        }
        p.waitFor();
        int returnCode = p.exitValue();
        logger.debug("Execute command done: " + cmd + ". Get return code: " + returnCode);
        return returnCode;
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return -1;
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private static List<String> system(String... command) {
    try {//from ww w.  j a  va 2  s.  co m
        final Process process = new ProcessBuilder(command).start();
        Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:elh.eus.absa.NLPpipelineWrapper.java

public static int eustaggerCall(String taggerCommand, String string, String fname) {

    try {/*from  w  w w .j a  v  a2 s  .c o  m*/
        File temp = new File(fname);
        //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(string + "\n");
        bw.close();

        String[] command = { taggerCommand, temp.getName() };
        System.err.println("Eustagger agindua: " + Arrays.toString(command));

        ProcessBuilder eustBuilder = new ProcessBuilder().command(command);
        eustBuilder.directory(new File(temp.getParent()));
        //.redirectErrorStream(true);
        Process eustagger = eustBuilder.start();
        int success = eustagger.waitFor();
        //System.err.println("eustagger succesful? "+success);
        if (success != 0) {
            System.err.println("eustaggerCall: eustagger error");
        } else {
            String tagged = fname + ".kaf";
            BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream()));
            //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu
            if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) {
                Files.copy(eustagger.getInputStream(), Paths.get(tagged));
            }
            // old eustagger (euslem)
            else {
                FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged);
            }
        }
        //
        // delete all temporal files used in the process.
        temp.delete();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    }

    return 0;
}

From source file:org.cloudifysource.usm.USMUtils.java

private static boolean markFileAsExecutableUsingChmod(final File file) throws USMException {
    try {//from   www  . ja  v a2s.  c o m
        logger.info("File " + file + " will be marked as executable using chmod command");
        final Process p = Runtime.getRuntime().exec(new String[] { "chmod", "+x", file.getAbsolutePath() });
        final int result = p.waitFor();
        logger.info("chmod command finished with result = " + result);
        if (result != 0) {
            final String msg = "chmod command did not terminate successfully. File " + file
                    + " may not be executable!";
            logger.warning(msg);
        }
        return result == 0;
    } catch (final IOException e) {
        throw new USMException("Failed to execute chmod command:  chmod +x " + file.getAbsolutePath(), e);
    } catch (final InterruptedException e) {
        throw new USMException("Failed to execute chmod command on file " + file, e);
    }
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * runSVNCommand runs an svn command in the specified directory.
 *
 * @param connection/*  w w  w. j a v a 2  s  .  com*/
 *            the connection storing the connection infos for the remote
 * @param svnCommand
 *            is the command to be executed. Each part of the command must
 *            be a string element. For example: "svn" "checkout"
 *            "file://some/path"
 * @param workingDir
 *            where the svn command should be executed (must be a
 *            repository).
 * @return A list of all output lines.
 * @throws IOException
 *             Thrown when process can't be started or an error occurs
 *             while reading its output
 */
private static SVNResultData runSVNCommand(Connection connection, List<String> svnCommand, Path workingDir)
        throws IOException {

    // add boilerplate to command
    svnCommand.add("--non-interactive");
    svnCommand.add("--no-auth-cache");
    svnCommand.add("--force");

    if ((connection.getUsername() != null) && !connection.getUsername().isEmpty()) {
        svnCommand.add("--username");
        svnCommand.add(connection.getUsername());
    }

    if ((connection.getPassword() != null) && !connection.getPassword().isEmpty()) {
        svnCommand.add("--password");
        svnCommand.add(connection.getPassword());
    }

    // build process: construct command and set working directory.
    Process svnProcess = null;
    ProcessBuilder svnProcessBuilder = new ProcessBuilder(svnCommand);
    svnProcessBuilder.directory(workingDir.toFile());

    svnProcess = svnProcessBuilder.start();
    try {
        svnProcess.waitFor();
    } catch (InterruptedException e) {
        LOGGER.severe("Interrupted while waiting for SVN. " + "Cannot guarantee clean command run!");
        return null;
    }

    InputStream svnOutputStream = svnProcess.getInputStream();
    InputStreamReader svnStreamReader = new InputStreamReader(svnOutputStream);
    BufferedReader svnOutputBuffer = new BufferedReader(svnStreamReader);
    String line;

    List<String> svnOutputLines = new LinkedList<>();

    while ((line = svnOutputBuffer.readLine()) != null) {
        svnOutputLines.add(line);
    }

    return new SVNResultData(svnProcess.exitValue(), svnOutputLines);
}