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:gr.aueb.dmst.istlab.unixtools.actions.impl.ExecuteCustomCommandAction.java

@Override
public void execute(ActionExecutionCallback<DataActionResult<InputStream>> callback)
        throws IOException, InterruptedException {
    DataActionResult<InputStream> result;
    List<String> arguments = EclipsePluginUtil.getSystemShellInfo();

    ProcessBuilder pb;//from w w  w .  j  a v  a  2 s  .c  o m

    if (SystemUtils.IS_OS_WINDOWS) {
        pb = new ProcessBuilder(arguments.get(0), arguments.get(1), arguments.get(2) + "\"cd "
                + this.commandToExecute.getShellDirectory() + ";" + this.commandToExecute.getCommand() + "\"");
    } else {
        arguments.add(this.commandToExecute.getCommand());
        pb = new ProcessBuilder(arguments);
        pb.directory(new File(this.commandToExecute.getShellDirectory()));
    }
    pb.redirectErrorStream(true);

    Process p;
    try {
        p = pb.start();
        p.waitFor();
        InputStream cmdStream = p.getInputStream();
        result = new DataActionResult<>(cmdStream);
    } catch (IOException e) {
        logger.fatal("IO problem occurred while executing the command");
        result = new DataActionResult<>(e);
        throw new IOException(e);
    } catch (InterruptedException e) {
        logger.fatal("The current thread has been interrupted while executing the command");
        result = new DataActionResult<>(e);
        throw new InterruptedException();
    }

    callback.onCommandExecuted(result);
}

From source file:edu.illinois.cs.cogcomp.CompileMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//from   w w  w  .j av a2 s. c  o m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-d",
                    dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:edu.illinois.cs.cogcomp.GenerateMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//ww  w .ja v a 2s  .  c o  m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-step parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-c",
                    "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:husky.server.HuskyMaster.java

@Override
public void run() {
    try {/* w ww  .j a va 2  s  .c  o m*/
        LOG.info("Starting husky master process");
        ProcessBuilder mHuskyMasterProcess = new ProcessBuilder(getCommands());
        if (!mAppMaster.getLdLibraryPath().isEmpty()) {
            mHuskyMasterProcess.environment().put("LD_LIBRARY_PATH", mAppMaster.getLdLibraryPath());
        }
        mHuskyMasterProcess.redirectOutput(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"));
        mHuskyMasterProcess.redirectError(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr"));
        Process p = mHuskyMasterProcess.start();
        p.waitFor();
        if (p.exitValue() == 0) {
            LOG.info("Husky master exits successfully");
        } else {
            LOG.info("Husky master exits with code " + p.exitValue());
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, " Failed to start c++ husky master process: ", e);
    } finally {
        if (!mAppMaster.getLogPathToHDFS().isEmpty()) {
            try {
                mAppMaster.getFileSystem().copyFromLocalFile(false, true,
                        new Path[] { new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"),
                                new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr") },
                        new Path(mAppMaster.getLogPathToHDFS()));
            } catch (IOException e) {
                LOG.log(Level.INFO, "Failed to upload logs of husky master to hdfs", e);
            }
        }
    }
}

From source file:com.github.born2snipe.project.setup.scm.GitRepoInitializer.java

private void executeCommandIn(File projectDir, String... commands) {
    try {//w  w  w.j ava 2 s .  co m
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.directory(projectDir);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        System.out.println(IOUtils.toString(process.getInputStream()));
        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cloudworker.Animoto.java

@SuppressWarnings("unchecked")
public void run() {
    //Get queue url   
    GetQueueUrlResult urlResult = sqs.getQueueUrl(responseQName);
    String QueueUrl = urlResult.getQueueUrl();
    JSONObject result = new JSONObject();

    Runtime runtime = Runtime.getRuntime();

    try {//from   www.ja  v  a  2  s .  com
        String[] urls = task.split(" ");

        for (String url : urls) {
            //System.out.println(url);
            Process p = runtime.exec("wget " + url);
            p.waitFor();
        }

        Process rename = runtime.exec("./rename.sh");
        rename.waitFor();

        runtime.exec("ffmpeg -f image2 -i img%03d.jpg movie.mpg");

        File movie = new File("movie.mpg");

        S3Service s3 = new S3Service();
        URL url = s3.put(movie.getName(), movie);

        //result.put("task_id", task_id);
        result.put("URL", url.toString());

        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));
        //System.out.println(Thread.currentThread().getName()+" sleep done!");

    } catch (Exception e) {
        //result.put("task_id", task_id);
        result.put("URL", "Failed!");
        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));

    }
}

From source file:edu.illinois.cs.cogcomp.CleanMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);/*from   w w w . j a v  a 2s.c  o m*/
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // We need to reverse the order we do the cleaning since there might be dependencies across
    // files
    List<String> fileList = Arrays.asList(lbjavaInputFileList);
    Collections.reverse(fileList);
    for (String lbjInputFile : fileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-step parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main with the -x flag (for cleaning)...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            // The -x flag makes all the difference.
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-x",
                    "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:com.excella.deploy.agent.core.UnixShellCommand.java

/**
 * {@inheritDoc}/*from   www  .j  a v  a 2  s .c  o  m*/
 */
public String execute(String argument) throws FailedCommandException {
    String line = "";
    StringBuffer buffer = new StringBuffer();
    String command = getJBossHome() + "/bin/appdeploy.sh " + argument + " 2>/dev/null";
    InputStreamReader inputStream = null;
    BufferedReader input = null;

    log.info("Running an RSM Deployment using the following command: " + command);
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        int exitValue = process.waitFor();
        inputStream = new InputStreamReader(process.getInputStream());
        input = new BufferedReader(inputStream);
        while ((line = input.readLine()) != null) {
            log.debug("> " + line);
            buffer.append(line);
            buffer.append("<br/>");
        }

        log.info("RSM Deployment Kicked off.  Exited with [" + exitValue + "]");
    } catch (Exception e) {
        throw new FailedCommandException("Unable to execute the command.", e);
    } finally {
        close(inputStream);
        close(input);
    }
    return buffer.toString();
}

From source file:io.ballerina.plugins.idea.preloading.TerminatorMac.java

/**
 * Terminate running ballerina program.//  w  w w  .  j ava  2s  . co  m
 */
public void terminate() {
    int processID;
    String[] findProcessCommand = getFindProcessCommand(processIdentifier);
    BufferedReader reader = null;
    try {
        Process findProcess = Runtime.getRuntime().exec(findProcessCommand);
        findProcess.waitFor();
        reader = new BufferedReader(
                new InputStreamReader(findProcess.getInputStream(), Charset.defaultCharset()));

        String line;
        while ((line = reader.readLine()) != null) {
            try {
                processID = Integer.parseInt(line);
                killChildProcesses(processID);
                kill(processID);
            } catch (Throwable e) {
                LOGGER.error("Launcher was unable to kill process " + line + ".");
            }
        }
    } catch (Throwable e) {
        LOGGER.error("Launcher was unable to find the process ID for " + processIdentifier + ".");
    } finally {
        if (reader != null) {
            IOUtils.closeQuietly(reader);
        }
    }
}

From source file:ee.ria.xroad.monitor.executablelister.AbstractExecLister.java

/**
 * Method for testability//  w  ww .  j ava2 s.  c om
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
ProcessOutputs executeProcess() throws IOException, InterruptedException {

    ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", getCommand());

    Process p = b.start();
    p.waitFor();
    ProcessOutputs outputs = new ProcessOutputs();
    // need to read all of output everytime, reading it partially causes bad problems
    outputs.setOut(CharStreams.toString(new InputStreamReader(p.getInputStream())).replace("'", ""));
    outputs.setErr(CharStreams.toString(new InputStreamReader(p.getErrorStream())));
    return outputs;
}