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:fish.payara.maven.plugins.micro.StopMojo.java

private void killProcess(String processId) throws MojoExecutionException {
    String command = null;//w w w.ja va 2  s. c  o m
    try {
        final Runtime re = Runtime.getRuntime();
        if (isUnix()) {
            command = "kill " + processId;
        } else if (isWindows()) {
            command = "taskkill /PID " + processId + " /F";
        }
        if (command == null) {
            throw new MojoExecutionException("Operation system not supported!");
        }
        Process killProcess = re.exec(command);
        int result = killProcess.waitFor();
        if (result != 0) {
            getLog().error(ERROR_MESSAGE);
        }
    } catch (IOException | InterruptedException e) {
        getLog().error(ERROR_MESSAGE, e);
    }
}

From source file:dpcs.AppPackagesList.java

@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public AppPackagesList() {
    setResizable(false);/*from   w w w. java  2s .  c  o  m*/
    setTitle("App Packages List");
    setIconImage(Toolkit.getDefaultToolkit().getImage(AppPackagesList.class.getResource("/graphics/Icon.png")));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 479, 451);
    contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(22, 12, 428, 333);
    contentPane.add(scrollPane);

    JButton btnRefresh = new JButton("Refresh");
    btnRefresh.setToolTipText("Refresh the apps list");
    btnRefresh.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb shell pm list packages > /sdcard/.allapps.txt");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/.allapps.txt");
                p2.waitFor();
                Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/.allapps.txt");
                p3.waitFor();
                lines = IOUtils.readLines(new FileInputStream(".allapps.txt"));
                values = new String[lines.size()];
                values = lines.toArray(values);
                moddedvalues = new String[values.length];
                for (int i = 0; i < values.length; i++) {
                    moddedvalues[i] = values[i].substring(8);
                }
                applist = new JList();
                applist.setModel(new AbstractListModel() {
                    public int getSize() {
                        return moddedvalues.length;
                    }

                    public Object getElementAt(int index) {
                        return moddedvalues[index];
                    }
                });
                scrollPane.setViewportView(applist);
                File file = new File(".allapps.txt");
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                }
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });
    btnRefresh.setBounds(125, 357, 220, 47);
    contentPane.add(btnRefresh);

    try {
        Process p1 = Runtime.getRuntime().exec("adb shell pm list packages > /sdcard/.allapps.txt");
        p1.waitFor();
        Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/.allapps.txt");
        p2.waitFor();
        Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/.allapps.txt");
        p3.waitFor();
        lines = IOUtils.readLines(new FileInputStream(".allapps.txt"));
        values = new String[lines.size()];
        values = lines.toArray(values);
        moddedvalues = new String[values.length];
        for (int i = 0; i < values.length; i++) {
            moddedvalues[i] = values[i].substring(8);
        }
        applist = new JList();
        applist.setModel(new AbstractListModel() {
            public int getSize() {
                return moddedvalues.length;
            }

            public Object getElementAt(int index) {
                return moddedvalues[index];
            }
        });
        scrollPane.setViewportView(applist);
        File file = new File(".allapps.txt");
        if (file.exists() && !file.isDirectory()) {
            file.delete();
        }
    } catch (Exception e1) {
        System.err.println(e1);
    }
}

From source file:com.imos.sample.pi.PythonTemperatureSensor.java

public void pythonTemperatureSensor() {

    try {// w  ww  . jav a 2s .c  o m
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (result != null && !result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                String name = builder.toString();
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name);
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("./" + dirName);
                    newDir.mkdir();

                    File files = new File("./");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("./" + dirName + File.separator + file.getName()));
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.mdsh.test.media.encoding.process.AbstractProcess.java

/**
 * Waits for the given process to end./*from   ww w .j a  v a2s  .c om*/
 * <p>Warning: will throw an IOException if an InterruptedException
 * is caught.
 * @param process
 * @throws IOException when the process exit value is non-zero or when
 * the current thread is interrupted before the process has ended.
 */
protected void waitForProcess(final Process process) throws IOException {
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new IOException("interrupted while waiting for process: " + e.toString(), e);
    }

    final int ret = process.exitValue();

    if (0 != ret)
        throw new IOException("precess exit value was: " + ret);
}

From source file:de.sandroboehme.lesscss.mojo.NodeJsLessCompiler.java

private String compile(String input) throws LessException, IOException, InterruptedException {
    long start = System.currentTimeMillis();

    File inputFile = File.createTempFile("lessc-input-", ".less");
    FileOutputStream out = new FileOutputStream(inputFile);
    IOUtils.write(input, out);//  w ww  . ja  va 2 s  . co m
    out.close();
    File outputFile = File.createTempFile("lessc-output-", ".css");
    File lesscJsFile = new File(tempDir, "lessc.js");

    ProcessBuilder pb = new ProcessBuilder(nodeExecutablePath, lesscJsFile.getAbsolutePath(),
            inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress));
    pb.redirectErrorStream(true);
    Process process = pb.start();
    IOUtils.copy(process.getInputStream(), System.out);

    int exitStatus = process.waitFor();

    FileInputStream in = new FileInputStream(outputFile);
    String result = IOUtils.toString(in);
    in.close();
    if (!inputFile.delete()) {
        log.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        log.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

    log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms.");

    return result;
}

From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java

/**
 * Runs Maven in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir                The directory below src/test/resources to run maven in.
 * @param extraArgs          The extra arguments (if any) for Maven.
 * @return The standard output./* ww  w.j a va  2  s  . co  m*/
 * @throws Exception When the execution failed.
 */
private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String m2Home = System.getenv("M2_HOME");
    String flywayVersion = System.getProperty("flywayVersion");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(m2Home + "/bin/mvn" + extension);
    args.add("-Dflyway.version=" + flywayVersion);
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    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:com.googlecode.flyway.ant.AntLargeTest.java

/**
 * Runs Ant in this directory with these extra arguments.
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param dir       The directory below src/test/resources to run maven in.
 * @param extraArgs The extra arguments (if any) for Maven.
 * @return The standard output./*from   w w w  . j  a v  a  2s . c  o  m*/
 * @throws Exception When the execution failed.
 */
private String runAnt(int expectedReturnCode, String dir, String... extraArgs) throws Exception {
    String antHome = System.getenv("ANT_HOME");

    String extension = "";
    if (System.getProperty("os.name").startsWith("Windows")) {
        extension = ".bat";
    }

    List<String> args = new ArrayList<String>();
    args.add(antHome + "/bin/ant" + extension);
    args.add("-DlibDir=" + System.getProperty("libDir"));
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir + "/" + dir));
    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:com.samsung.sjs.SJSTest.java

public void assertSameProcessOutput(Process a, Process b) throws IOException, InterruptedException {
    a.waitFor();
    b.waitFor();//from w  w w.  jav  a  2  s. co m
    System.out.println("result of process a: " + a.exitValue());
    System.out.println("result of process b: " + b.exitValue());
    //assertTrue(a.exitValue() == b.exitValue());
    // Requiring the same exit value and output is usually too strong when we're testing error/exception
    // code.  Both node and our compiled code will return 0 when everything is okay, and should
    // then produce the same output.  But when there's an assertion failure or exception,
    // the C standard library semantics and node's semantics differ, in both return code and
    // process output.  So we enforce a more relaxed check here:
    // - If both processes return 0, assert both output streams match for the two processses
    // - Otherwise, assert both processes are non-zero exits (both failed), and ignore the stream contents.
    // This leaves open the possibility that a test will pass when the processes fail for
    // different reasons.
    int exita = a.exitValue();
    int exitb = b.exitValue();
    StringWriter a_stdout = new StringWriter(), b_stdout = new StringWriter(), a_stderr = new StringWriter(),
            b_stderr = new StringWriter();
    IOUtils.copy(a.getInputStream(), a_stdout, Charset.defaultCharset());
    IOUtils.copy(b.getInputStream(), b_stdout, Charset.defaultCharset());
    IOUtils.copy(a.getErrorStream(), a_stderr, Charset.defaultCharset());
    IOUtils.copy(b.getErrorStream(), b_stderr, Charset.defaultCharset());
    // Trim trailing newlines from output
    String a_stdout_str = a_stdout.toString().trim();
    String b_stdout_str = b_stdout.toString().trim();
    String a_stderr_str = a_stderr.toString().trim();
    String b_stderr_str = b_stderr.toString().trim();
    // HACK get rid of GC warning message from SJS stderr
    b_stderr_str = b_stderr_str.replaceAll(
            "GC Warning: Repeated allocation of very large block \\(appr\\. size .*\\):\\n\\tMay lead to memory leak and poor performance.",
            "");
    boolean same_stdout = a_stdout_str.equals(b_stdout_str);
    boolean same_stderr = a_stderr_str.equals(b_stderr_str);
    if (0 == exita && 0 == exitb) {
        if (!same_stdout) {
            System.err.println("FAILURE: stdout mismatch");
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
        }
        assertTrue(same_stdout);
        if (!same_stderr) {
            System.err.println("FAILURE: stderr mismatch");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(same_stderr);
    } else {
        if (exita == 0 || exitb == 0) {
            System.err.println("FAILURE: Process A returned " + exita + ", Process B returned " + exitb);
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(exita != 0 && exitb != 0);
    }
}

From source file:com.torodb.integration.mongo.v3m0.jstests.AbstractIntegrationTest.java

protected void runMongoTest(String toroConnectionString, URL mongoMocksUrl, boolean expectedZeroResult,
        boolean exceptionsExpected, String... parameters)
        throws IOException, InterruptedException, UnsupportedEncodingException, AssertionError {
    Process mongoProcess = runMongoProcess(toroConnectionString, mongoMocksUrl, parameters);

    int result = mongoProcess.waitFor();

    List<Throwable> uncaughtExceptions = TORO_RUNNER_CLASS_RULE.getUcaughtExceptions();

    ByteArrayOutputStream byteArrayOutputStream = readOutput(result, mongoProcess);

    checkResults(expectedZeroResult, exceptionsExpected, result, uncaughtExceptions, byteArrayOutputStream);
}

From source file:com.collective.celos.FileSystemStateDatabaseTest.java

/**
 * Returns true if diff reports a difference between the two files/dirs.
 *///  w  ww  .ja v a  2 s  .co m
private boolean diff(File a, File b) throws Exception {
    Process diff = new ProcessBuilder("diff", "-r", a.getAbsolutePath(), b.getAbsolutePath()).start();
    int exitValue = diff.waitFor();
    if (exitValue != 0) {
        String diffOut = IOUtils.toString(diff.getInputStream(), "UTF-8");
        System.err.print(diffOut);
    }
    return (exitValue != 0);
}