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:cz.cas.lib.proarc.common.process.AsyncProcess.java

@Override
public void run() {
    done.set(false);//from ww w  . ja  va 2  s . c  om
    outputConsumer = null;
    exitCode = -1;
    ProcessBuilder pb = new ProcessBuilder(cmdLine);
    // for now redirect outputs into a single stream to eliminate
    // the need to run multiple threads to read each output
    pb.redirectErrorStream(true);
    pb.environment().putAll(env);
    try {
        Process process = pb.start();
        refProcess.set(process);
        outputConsumer = new OutputConsumer(process.getInputStream());
        outputConsumer.start();
        exitCode = process.waitFor();
        LOG.fine("Done " + cmdLine);
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, cmdLine.toString(), ex);
    } finally {
        done.set(true);
    }
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {//from w  ww .  j  a  v a  2  s.  com
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}

From source file:com.googlecode.flyway.commandline.largetest.CommandLineLargeTest.java

/**
 * Runs the Flyway Command Line tool.//from  ww  w .j a v  a  2 s .  co  m
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param configFileName     The config file name. {@code null} for default.
 * @param operation          The operation {@code null} for none.
 * @param extraArgs          The extra arguments to pass to the tool.
 * @return The standard output produced by the tool.
 * @throws Exception thrown when the invocation failed.
 */
private String runFlywayCommandLine(int expectedReturnCode, String configFileName, String operation,
        String... extraArgs) throws Exception {
    List<String> args = new ArrayList<String>();

    String installDir = System.getProperty("installDir");
    args.add(installDir + "/flyway." + flywayCmdLineExtensionForCurrentSystem());

    if (operation != null) {
        args.add(operation);
    }
    if (configFileName != null) {
        String configFile = new ClassPathResource("largeTest.properties").getFile().getPath();
        args.add("-configFile=" + configFile);
    }
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}

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

@Test
@SuppressWarnings("unchecked")
public void executeCommandTestDealingWithInterruptedException() throws IOException, InterruptedException {
    shellCommandUtils.logger = Mockito.mock(Logger.class);

    Process processMock = Mockito.mock(Process.class);
    Runtime runtimeMock = configureAndGetRuntimeMock();
    Mockito.when(runtimeMock.exec(command)).thenReturn(processMock);
    Mockito.when(processMock.waitFor()).thenThrow(InterruptedException.class);

    String commandOutput = shellCommandUtils.executeCommand(command);

    Mockito.verify(processMock).waitFor();
    executeChecksForExceptionTests(commandOutput, InterruptedException.class);
}

From source file:com.thoughtworks.go.server.database.Migrate.java

private int exec(String[] command) {
    try {//from  www .  java  2s  .  co m
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("About to execute commands:");
            for (String c : command) {
                LOGGER.debug(c);
            }
        }
        Process p = Runtime.getRuntime().exec(command);
        copyInThread(p.getInputStream(), quiet ? null : sysOut);
        copyInThread(p.getErrorStream(), quiet ? null : sysOut);
        p.waitFor();
        return p.exitValue();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {//from  w  w  w.  j a  va  2s. c  o  m
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:Main.java

public static int doShellCommand(String cmd, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else//  www  . ja v  a2 s.  co m
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    //   TorService.logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

    out.write(cmd);
    out.write("\n");

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:com.mbrlabs.mundus.utils.FbxConv.java

public FbxConvResult execute() {
    FbxConvResult result = new FbxConvResult();
    if (input == null || output == null) {
        result.setSuccess(false);//  ww w.j a  v a 2s  .c o m
        result.setResultCode(FbxConvResult.RESULT_CODE_PARAM_ERROR);
        Log.error("FbxCov input or output not defined");
        return result;
    }

    if (!input.endsWith("fbx")) {
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_WRONG_INPUT_FORMAT);
        Log.error("FbxCov input format not supported");
    }

    // build arguments
    String outputFilename = FilenameUtils.getBaseName(input);
    List<String> args = new ArrayList<String>(6);
    if (flipTexture)
        args.add("-f");
    if (verbose)
        args.add("-v");
    if (outputFormat == OUTPUT_FORMAT_G3DJ) {
        args.add("-o");
        args.add("g3dj");
        outputFilename += ".g3dj";
    } else {
        outputFilename += ".g3db";
    }

    args.add(input);
    String path = FilenameUtils.concat(output, outputFilename);
    args.add(path);
    Log.debug("FbxConv", "Command: " + args);
    pb.command().addAll(args);

    // execute fbx-conv process
    try {
        Process process = pb.start();
        int exitCode = process.waitFor();
        String log = IOUtils.toString(process.getInputStream());

        if (exitCode == 0 && !log.contains("ERROR")) {
            result.setSuccess(true);
            result.setOutputFile(path);
        }
        result.setLog(log);

    } catch (IOException e) {
        e.printStackTrace();
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_IO_ERROR);
    } catch (InterruptedException e) {
        e.printStackTrace();
        result.setSuccess(false);
        result.setResultCode(FbxConvResult.RESULT_CODE_INTERRUPTED);
    }

    return result;
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

/**
 * Runs the parser on the given text/* ww w  .j av  a  2  s  .  c  o  m*/
 *
 * @param originalText text
 * @return parse tree
 * @throws IOException exception
 */
public String parseWithRST(String originalText) throws IOException {
    // temporary file in
    File tmpFileIn = File.createTempFile("rst_tmp", ".txt");
    // output of RST parser is a .tree file
    File tmpFileOut = new File(tmpFileIn.getAbsolutePath() + ".tree");
    // tmp log
    File tmpFileLog = new File(tmpFileIn.getAbsolutePath() + ".log");

    try {
        // write the text into a temporary file
        FileUtils.writeStringToFile(tmpFileIn, originalText);

        String tmpDirName = System.getProperty("java.io.tmpdir");

        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // log to file
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.to(tmpFileLog));

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "parse.py").getAbsolutePath(), "-t",
                tmpDirName, tmpFileIn.getAbsolutePath(), "-g");
        Process process = processBuilder.start();

        // and wait
        int returnValue = process.waitFor();

        if (returnValue != 0) {
            throw new RuntimeException("Process exited with code " + returnValue);
        }

        // read the log
        if (this.debugRSTOutput) {
            getLogger().debug(FileUtils.readFileToString(tmpFileLog));
        }

        // read the output
        if (tmpFileOut.exists()) {
            return FileUtils.readFileToString(tmpFileOut);
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    } finally {
        // clean up
        if (!keepTmpFiles) {
            FileUtils.deleteQuietly(tmpFileIn);
            FileUtils.deleteQuietly(tmpFileOut);
            FileUtils.deleteQuietly(tmpFileLog);
        }
    }

    return null;
}