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.teradata.benchto.driver.macro.shell.ShellMacroExecutionDriver.java

public void runBenchmarkMacro(String macroName, Map<String, String> environment) {
    try {/*from   ww w .ja v a 2  s . c o  m*/
        String macroCommand = getMacroCommand(macroName);
        ProcessBuilder processBuilder = new ProcessBuilder(SHELL, "-c", macroCommand);
        processBuilder.environment().putAll(environment);
        Process macroProcess = processBuilder.start();
        LOGGER.info("Executing macro: '{}'", macroCommand);
        macroProcess.waitFor();
        boolean completedSuccessfully = macroProcess.exitValue() == 0;
        printOutput(macroProcess, !completedSuccessfully);
        checkState(completedSuccessfully, "Macro %s exited with code %s", macroName, macroProcess.exitValue());
    } catch (IOException | InterruptedException e) {
        throw new BenchmarkExecutionException("Could not execute macro " + macroName, e);
    }
}

From source file:com.uber.hoodie.cli.commands.RepairsCommand.java

@CliCommand(value = "repair deduplicate", help = "De-duplicate a partition path contains duplicates & produce repaired files to replace with")
public String deduplicate(@CliOption(key = {
        "duplicatedPartitionPath" }, help = "Partition Path containing the duplicates", mandatory = true) final String duplicatedPartitionPath,
        @CliOption(key = {// w  w w .j  av a2 s.com
                "repairedOutputPath" }, help = "Location to place the repaired files", mandatory = true) final String repairedOutputPath,
        @CliOption(key = {
                "sparkProperties" }, help = "Spark Properites File Path", mandatory = true) final String sparkPropertiesPath)
        throws Exception {
    SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath);
    sparkLauncher.addAppArgs(SparkMain.SparkCommand.DEDUPLICATE.toString(), duplicatedPartitionPath,
            repairedOutputPath, HoodieCLI.tableMetadata.getBasePath());
    Process process = sparkLauncher.launch();
    InputStreamConsumer.captureOutput(process);
    int exitCode = process.waitFor();

    if (exitCode != 0) {
        return "Deduplicated files placed in:  " + repairedOutputPath;
    }
    return "Deduplication failed ";
}

From source file:drm.taskworker.workers.ExecuteWorker.java

/**
 * Archive the result of the previous task
 *///  ww  w  . java2  s  .  com
public TaskResult work(Task task) {
    logger.info("Executing");
    TaskResult result = new TaskResult();

    String command = null;
    try {
        command = (String) task.getParam("command");
    } catch (ParameterFoundException e) {
        return result.setResult(TaskResult.Result.ARGUMENT_ERROR);
    }

    Set<String> names = task.getParamNames();

    try {
        // create the temp files, and execute the command
        String[] exe = { command };

        File inputFile = File.createTempFile("execute", "dat");
        File outputFile = File.createTempFile("execute", "dat");

        String[] envp = { "INPUT_FILE=" + inputFile.getAbsolutePath(),
                "OUTPUT_FILE=" + outputFile.getAbsolutePath() };

        FileOutputStream fos = new FileOutputStream(inputFile);
        for (String name : names) {
            try {
                fos.write((name + "=" + task.getParam(name) + "\n").getBytes());
            } catch (ParameterFoundException e) {
                // cannot happen
            }
        }
        fos.close();

        Process p = Runtime.getRuntime().exec(exe, envp);
        p.waitFor();

        // read the output data back and report
        FileInputStream fis = new FileInputStream(outputFile);
        byte[] outputData = IOUtils.toByteArray(fis);

        Task newTask = new Task(task, this.getNextWorker(task.getJobId()));
        newTask.addParam("result", outputData);

        // also add original parameters
        for (String name : names) {
            try {
                newTask.addParam(name, task.getParam(name));
            } catch (ParameterFoundException e) {
                // cannot happen
            }
        }

        result.addNextTask(newTask);
        result.setResult(TaskResult.Result.SUCCESS);

    } catch (IOException | InterruptedException e) {
        result.setResult(TaskResult.Result.EXCEPTION);
        result.setException(e);
    }

    return result;
}

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

/**
 * Terminate running all child processes for a given pid.
 *
 * @param pid - process id/*from w ww.  j a v  a 2 s.  c  o  m*/
 */
void killChildProcesses(int pid) {
    BufferedReader reader = null;
    try {
        Process findChildProcess = Runtime.getRuntime().exec(String.format("pgrep -P %d", pid));
        findChildProcess.waitFor();
        reader = new BufferedReader(
                new InputStreamReader(findChildProcess.getInputStream(), Charset.defaultCharset()));
        String line;
        int childProcessID;
        while ((line = reader.readLine()) != null) {
            childProcessID = Integer.parseInt(line);
            kill(childProcessID);
        }
    } catch (Throwable e) {
        LOGGER.error("Launcher was unable to find parent for process:" + pid + ".");
    } finally {
        if (reader != null) {
            IOUtils.closeQuietly(reader);
        }
    }
}

From source file:edu.hm.muse.controller.AdminController.java

@RequestMapping(value = "/admininternpic.secu", method = RequestMethod.GET)
private ModelAndView showAllPictures(HttpSession session,
        @CookieValue(value = "admintoken", required = false) String adminToken,
        @RequestParam(value = "path", required = false) String pathToWatch) {
    if (!checkToken(session, adminToken)) {
        throw new SuperFatalAndReallyAnnoyingException("Already bad...");
    }/*  ww w  .  j  a  v a 2 s .  c o m*/

    if (pathToWatch == null || pathToWatch.isEmpty()) {
        pathToWatch = "webapps/secu/img";
    }

    StringBuilder builder = new StringBuilder();
    //just works in linux or??
    try {

        ProcessBuilder procBuilder = new ProcessBuilder("bash", "-c", String.format("ls -gGH %s", pathToWatch));

        Process proc = procBuilder.start();
        proc.waitFor();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String readLine = bReader.readLine();

        while (readLine != null) {
            builder.append(readLine).append("<br/>");
            readLine = bReader.readLine();
        }
        builder.append("Thats All...");

    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    ModelAndView mv = new ModelAndView("admininterndic");
    String result = builder.toString();

    mv.addObject("files", result);
    return mv;

}

From source file:io.fabric8.kit.common.ExternalCommand.java

private void checkProcessExit(Process process) {
    try {/*from w  ww  .  j  ava  2s  .c  om*/
        statusCode = process.waitFor();
        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.SECONDS);
    } catch (IllegalThreadStateException | InterruptedException e) {
        process.destroy();
        statusCode = -1;
    }
}

From source file:net.landora.video.programs.ProgramsAddon.java

public boolean isAvaliable(Program program) {
    String path = getConfiguredPath(program);
    if (path == null) {
        return false;
    }/*  w  ww.ja  va 2  s  .  co  m*/

    ArrayList<String> command = new ArrayList<String>();
    command.add(path);
    command.addAll(program.getTestArguments());
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.redirectErrorStream(true);

    try {
        Process p = builder.start();
        IOUtils.copy(p.getInputStream(), new NullOutputStream());
        p.waitFor();
        return true;
    } catch (Exception e) {
        log.info("Error checking for program: " + program, e);
        return false;
    }
}

From source file:jenkins.plugins.asqatasun.AsqatasunRunner.java

public void callService() throws IOException, InterruptedException {
    File logFile = AsqatasunRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");//from ww w .  j  a va2  s. co m
    File scenarioFile = AsqatasunRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    listener.getLogger().print("Launching asqatasun runner with the following options : ");
    listener.getLogger().print(pb.command());
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.forceDelete(logFile);
    }

    FileUtils.forceDelete(scenarioFile);
}

From source file:com.nominum.build.LinkAssetsMojo.java

public void execute() throws MojoExecutionException {

    File outputDir = absolutePath(outputDirectory);
    File assetDir = absolutePath(assetDirectory);

    if (!outputDir.exists()) {
        boolean created = outputDir.mkdirs();
        if (!created)
            throw new MojoExecutionException("Failed to create output directory");
    }//from ww w  .j a  va  2 s . co  m

    String linkName = assetDir.getAbsolutePath().substring(assetDir.getParent().length() + 1);
    File linkTarget = new File(outputDir, linkName);

    // recreate link if it exists
    if (linkTarget.exists()) {
        boolean deleted = linkTarget.delete();
        if (!deleted) {
            throw new MojoExecutionException(
                    "Failed to delete " + linkName + " prior to linking asset directory");
        }
    }

    String[] command;
    getLog().info("OS name:" + System.getProperty("os.name"));
    if (System.getProperty("os.name").indexOf("indows") > 0) {
        command = new String[] { "cmd", "/c", "mklink", "/D", linkTarget.getAbsolutePath(),
                assetDir.getAbsolutePath() };
    } else {
        command = new String[] { "ln", "-s", assetDir.getAbsolutePath(), linkTarget.getAbsolutePath() };
    }

    try {
        getLog().info("Linking " + assetDirectory + " to " + linkTarget);

        Process proc = Runtime.getRuntime().exec(command, null, new File("."));

        int exitVal = proc.waitFor();
        if (exitVal != 0) {
            throw new MojoExecutionException(
                    "linking assets directory failed. Command: \"" + StringUtils.join(command, " ") + "\"");
        }
        getLog().info("Linking " + assetDirectory + " to " + linkTarget + " done");
    } catch (InterruptedException e) {
        throw new MojoExecutionException("link command failed", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to execute link command, run as administrator.", e);
    }
}

From source file:org.energyos.espi.datacustodian.web.api.ManageRESTController.java

/**
 * Provides access to administrative commands through the pattern:
 * DataCustodian/manage?command=[resetDataCustodianDB |
 * initializeDataCustodianDB]/*from  ww w. j  a v a  2s. c o m*/
 * 
 * @param response
 *            Contains text version of stdout of the command
 * @param params
 *            [["command" . ["resetDataCustodianDB" |
 *            "initializeDataCustodianDB"]]]
 * @param stream
 * @throws IOException
 */
@RequestMapping(value = Routes.DATA_CUSTODIAN_MANAGE, method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public void doCommand(HttpServletResponse response, @RequestParam Map<String, String> params,
        InputStream stream) throws IOException {

    response.setContentType(MediaType.TEXT_PLAIN_VALUE);

    try {
        try {
            String commandString = params.get("command");
            System.out.println("[Manage] " + commandString);
            ServletOutputStream output = response.getOutputStream();

            output.println("[Manage] Restricted Management Interface");
            output.println("[Manage] Request: " + commandString);

            String command = null;

            // parse command
            if (commandString.contains("resetDataCustodianDB")) {
                command = "/etc/OpenESPI/DataCustodian/resetDatabase.sh";
            } else if (commandString.contains("initializeDataCustodianDB")) {
                command = "/etc/OpenESPI/DataCustodian/initializeDatabase.sh";

            }

            if (command != null) {
                Process p = Runtime.getRuntime().exec(command);
                p.waitFor();
                output.println("[Manage] Result: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = reader.readLine();

                while (line != null) {
                    System.out.println("[Manage] " + line);
                    output.println("[Manage]: " + line);
                    line = reader.readLine();
                }
                reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                output.println("[Manage] Errors: ");
                line = reader.readLine();
                while (line != null) {
                    System.out.println("[Manage] " + line);
                    output.println("[Manage]: " + line);
                    line = reader.readLine();
                }
            }

        } catch (IOException e1) {
        } catch (InterruptedException e2) {
        }

        System.out.println("[Manage] " + "Done");

    } catch (Exception e) {
        System.out.printf("**** [Manage] Error: %s\n", e.toString());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}