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.google.gwt.benchmark.compileserver.server.manager.CliInteractor.java

private String runCommand(String command, boolean useErrorSteam) throws BenchmarkManagerException {
    InputStream stream = null;/*  w  ww .  ja  va  2 s  . com*/
    try {
        Process process = Runtime.getRuntime().exec(command);
        int exitValue = process.waitFor();

        if (exitValue != 0) {
            stream = useErrorSteam ? process.getErrorStream() : process.getInputStream();
            String error = "Command returned with " + exitValue + " " + IOUtils.toString(stream, "UTF-8");
            logger.warning(error);
            throw new BenchmarkManagerException(error);
        }

        stream = process.getInputStream();
        return IOUtils.toString(stream, "UTF-8");

    } catch (IOException | InterruptedException e) {
        logger.log(Level.WARNING, "Can not run command", e);
        throw new BenchmarkManagerException("Can not run command");
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

public static String getMyDocumentsLocation() {
    String myDocuments = null;/*  w  ww . j a va  2 s  . c om*/

    try {
        if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
            myDocuments = System.getProperty("user.home") + File.separator + "Documents";
        }
        if (SystemUtils.IS_OS_WINDOWS) {
            Process p = Runtime.getRuntime().exec(
                    "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal");
            p.waitFor();

            InputStream in = p.getInputStream();
            byte[] b = new byte[in.available()];
            in.read(b);
            in.close();

            myDocuments = new String(b);
            myDocuments = myDocuments.split("\\s\\s+")[4];
        }
        if (SystemUtils.IS_OS_LINUX) {
            myDocuments = System.getProperty("user.home") + File.separator + "Documents";
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }

    return myDocuments;
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean start() {
    Process child;// ww  w.  j  a v a  2  s  .c om
    try {
        child = Runtime.getRuntime().exec(agentConfig.getStartCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute Apache start command";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for Apache start";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}

From source file:fr.amap.amapvox.rxptolaz.RxpScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz)
        throws IOException, InterruptedException, UnsupportedOperationException, Exception {

    /***Convert rxp to txt***/

    Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix);

    Mat3D rotation = new Mat3D();
    rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2],
            transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8],
            transfMatrix.mat[9], transfMatrix.mat[10] };

    File outputTxtFile = new File(
            outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile));

    RxpExtraction extraction = new RxpExtraction();

    extraction.openRxpFile(scan.file, RxpExtraction.REFLECTANCE);

    Iterator<Shot> iterator = extraction.iterator();

    while (iterator.hasNext()) {

        Shot shot = iterator.next();/*from ww  w .  j  ava 2  s  .  c  o m*/

        Vec4D origin = Mat4D.multiply(transfMatrix,
                new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d));
        Vec3D direction = Mat3D.multiply(rotation,
                new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z));

        for (int i = 0; i < shot.nbEchos; i++) {

            double x = origin.x + direction.x * shot.ranges[i];
            double y = origin.y + direction.y * shot.ranges[i];
            double z = origin.z + direction.z * shot.ranges[i];

            writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.nbEchos + " "
                    + reflectanceToIntensity(shot.reflectances[i]) + "\n");
        }

    }

    extraction.close();
    writer.close();

    /***Convert txt to laz***/
    String propertyValue = System.getProperty("user.dir");
    System.out.println("Current jar directory : " + propertyValue);

    String txtToLasPath;

    String osName = getOSName();

    switch (osName) {
    case "windows":
    case "linux":
        txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator
                + "txt2las";
        break;
    default:
        throw new UnsupportedOperationException("Os architecture not supported");
    }

    if (osName.equals("windows")) {
        txtToLasPath = txtToLasPath + ".exe";
    }

    File outputLazFile;
    if (laz) {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz");
    } else {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las");
    }

    String[] commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
            outputLazFile.getAbsolutePath(), "-parse", "xyzrni" };

    System.out.println("Command line : "
            + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", ""));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

    Process p = pb.start();

    p.waitFor();

}

From source file:at.ait.dme.yuma.server.image.WebsiteCaptureServiceImpl.java

@Override
public String captureSite(String url) throws WebsiteCaptureException {
    String imageName = "";

    try {/* w  ww.  j  ava 2s  . co  m*/
        imageName = new Long(System.currentTimeMillis()).toString() + ".jpg";
        String filename = targetPath + "/" + imageName;
        Process p = Runtime.getRuntime()
                .exec("cutycapt --min-width=" + minWidth.toString() + " --url=" + url + " --out=" + filename);

        if (p.waitFor() != 0) {
            String errorMessage = "";
            InputStream errorStream = p.getErrorStream();
            if (errorStream != null)
                errorMessage = IOUtils.toString(errorStream, "UTF-8");

            throw new WebsiteCaptureException("failed to capture site: " + errorMessage);
        }
    } catch (Throwable t) {
        logger.fatal(t.getMessage(), t);
        throw new WebsiteCaptureException(t);
    }
    return RELATIVE_IMAGEURL_PATH + "/" + imageName;
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean restart() {
    Process child;//from  w ww.ja v a  2  s.c o m
    try {
        child = Runtime.getRuntime().exec(agentConfig.getRestartCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute restart command";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for restart";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}

From source file:ape.KillNodeCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    if (Main.VERBOSE) {
        System.out.println("NodeType: " + args[0]);
    }/*from   w w  w  .  j  a va2s.c  om*/

    String nodeType = args[0];

    if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker")
            || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) {
        System.out.println("Kill is about to execute the following command:");

        /**
         * The line of code below sends a very ugly bash command to kill the corresponding process.
         * It gets a list of running processes, then greps it for the node type, then 
         * removes the result generated by running grep, then it gets the process ID of that line 
         * 
         */
        String cmd = "echo \"kill -9 \\$(ps -ef | grep -i " + nodeType
                + " | grep -v grep | grep -v ape | awk -F ' '  '{print \\$2}')\" > /tmp/kill-node.sh && chmod +x /tmp/kill-node.sh && /tmp/./kill-node.sh && rm /tmp/kill-node.sh";

        System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        pb.redirectErrorStream(true);
        Process sh = pb.start();
        InputStream shIn = sh.getInputStream();
        try {
            if (sh.waitFor() != 0) {
                System.out.println("Executing Kill Command failed");
                return false;
            }
        } catch (InterruptedException e) {
            System.out.println(
                    "The kill command was killed before it could kill its target process.  Kind of ironic really...");
            e.printStackTrace();
            throw new RuntimeException();
        }
        int c;
        while ((c = shIn.read()) != -1) {
            System.out.write(c);
        }
        try {
            shIn.close();
        } catch (IOException e) {
            System.out.println("Could not close InputStream from the kill process.");
            e.printStackTrace();
            return false;
        }
    }

    else {
        System.out.println("Invalid node type: " + nodeType);
        System.out.println("Should be one of the following: DataNode, TaskTracker, NameNode, JobTracker.");
        return false;
    }
    return true;
}

From source file:net.pickapack.io.cmd.CommandLineHelper.java

/**
 *
 * @param cmd/*  ww  w .j  a v a2  s. com*/
 * @param waitFor
 * @return
 */
public static int invokeNativeCommand(String[] cmd, boolean waitFor) {
    try {
        Runtime r = Runtime.getRuntime();
        final Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            Process ps = pb.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getInputStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getErrorStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        if (waitFor) {
            int exitValue = ps.waitFor();
            if (exitValue != 0) {
                System.out.println("WARN: Process exits with non-zero code: " + exitValue);
            }

            ps.destroy();

            return exitValue;
        }

        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java

public ProcessOutput execute(String[] command, Map<String, String> envMap) {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    Process process = null;
    ProcessOutput processOutput = null;//from w  w  w  .  j  a  v a 2  s. c om
    try {
        processBuilder.environment().putAll(envMap);
        process = processBuilder.start();
        int returnCode = process.waitFor();
        List outputStream = IOUtils.readLines(process.getInputStream());
        List errorStream = IOUtils.readLines(process.getErrorStream());
        processOutput = new ProcessOutput(returnCode, outputStream, errorStream);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        if (process != null) {
            closeQuietly(process.getInputStream());
            closeQuietly(process.getErrorStream());
            closeQuietly(process.getOutputStream());
            process.destroy();
        }
    }
    return processOutput;
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean checkSyntax() {
    Process child;/*  ww w  .  ja va  2  s  .c o m*/
    try {
        child = Runtime.getRuntime().exec(agentConfig.getSyntaxCheckCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute syntax check";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for syntax check";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}