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:localization.split.java

public static boolean checkLPU(String filepath, String passoloPath) {
    File logfile = new File(filepath.substring(0, filepath.lastIndexOf("\\") + 1) + "error.log");
    try {/*from  w  w  w.  j  a  va2  s.co m*/
        String cmd = "cmd.exe /c " + passoloPath + " /openproject:" + filepath;
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd);
        InputStreamReader isr = new InputStreamReader(proc.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.contains("Opening in read-only mode")) {
                if (!logfile.exists()) {
                    logfile.createNewFile();
                }
                String content = filepath
                        + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2011."
                        + "\n";
                FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);
                bw.close();
                return false;
            }
        }
        int exitVal = proc.waitFor();
        if (exitVal == 10) {
            if (!logfile.exists()) {
                logfile.createNewFile();
            }
            String content = filepath
                    + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2015."
                    + "\n";
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            return false;
        }

    } catch (Exception e) {
        try {
            String content = e.getMessage();
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (Exception e1) {

        }

        return false;
    }
    return true;
}

From source file:es.ehu.si.ixa.qwn.ppv.UKBwrapper.java

public void propagate(String ctxtFile) throws IOException {
    try {/*from w  w w  .j  a  va  2 s . c  o  m*/
        String[] command = { ukbPath + "/ukb_ppv", "-K", this.graph, "-D", this.langDict, "--variants", "-O",
                this.outDir, ctxtFile };
        System.err.println("UKB komandoa: " + Arrays.toString(command));

        ProcessBuilder ukbBuilder = new ProcessBuilder().command(command);
        //.redirectErrorStream(true);
        Process ukb_ppv = ukbBuilder.start();
        int success = ukb_ppv.waitFor();
        System.err.println("ukb_ppv succesful? " + success);
        if (success != 0) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ukb_ppv.getErrorStream()),
                    1);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.err.println(line);
            }
        }
    } catch (Exception e) {
        System.err.println("PropagationUKB class: error when calling ukb_ppv\n.");
        e.printStackTrace();
    }
    //"$UKB_PATH"/bin/ukb_ppv -K "$PROPAGATION_PATH"/lkb_resources/wnet30_enSyn.bin -D "$UKB_PATH"/lkb_sources/30/wnet30_dict.txt --variants -O "$PPV_OUT_DIR" $TMP_DIR/propag_posSeeds_syn.ctx  
    //mv "$PPV_OUT_DIR"/ctx_01.ppv "$PPV_OUT_DIR"/pos_syn.ppv

}

From source file:com.delphix.appliance.host.example.client.ExampleClient.java

public void executeRemoteCommand() {
    // Execute remote command
    String[] remoteArgs = { "ls", "-l", "/" };
    Process remote = remoteManager.executeCommand(remoteArgs, null, null, false, null);

    int exitCode;
    try {// w w w.  j a  v a 2  s .c om
        exitCode = remote.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (exitCode != 0)
        throw new RuntimeException("Remote command execution failed");

    // Parse remote output
    try {
        InputStream remoteStdout = remote.getInputStream();
        BufferedReader remoteReader = new BufferedReader(new InputStreamReader(remoteStdout, "UTF-8"));
        String line;
        while ((line = remoteReader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    remote.destroy();
}

From source file:hu.bme.mit.trainbenchmark.generator.sql.SQLGenerator.java

public void compact() throws IOException, InterruptedException {
    MySQLProcess.stopSQLProcess();/*from www  . j  a v  a2 s  .c o  m*/
    MySQLProcess.startSQLProcess();

    final Runtime rt = Runtime.getRuntime();
    final String[] commandLoad = { "/bin/bash", "-c", "mysql -u " + USER + " < " + sqlRawPath };
    final Process processLoad = rt.exec(commandLoad);
    processLoad.waitFor();

    final String[] commandDump = { "/bin/bash", "-c",
            "mysqldump -u " + USER + " --databases trainbenchmark --skip-dump-date > " + sqlDumpPath };
    final Process processDump = rt.exec(commandDump);
    processDump.waitFor();
}

From source file:com.opensmile.maven.openSMILEclassifier.java

@Override
public JSONObject classify(String audioFile) {
    String line = "";
    String fullLine = "";
    try {//from   www  .  j  ava  2 s. c  o  m
        String str = paths.SMILExtractDir + "SMILExtract " + " -C " + paths.SMILExtractDir + configFile + " -I "
                + audioFile + " -l 1";
        Process p = Runtime.getRuntime().exec(str, null, new File(paths.SMILExtractDir));
        logger_instance.write(1, "opensmile command: " + str);
        p.waitFor();
        logger_instance.write(1, "opensmile command performed");
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = in.readLine()) != null)
            fullLine = fullLine + line;
        in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = in.readLine()) != null)
            fullLine = fullLine + line;
        logger_instance.write(1, "opensmile output:" + fullLine);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    JSONObject jo = new JSONObject(fullLine);

    JSONObject jop = new JSONObject();
    switch ((String) jo.get("TYPE")) {
    case "regression":
        double out = jo.getDouble("VALUE");
        double conf = (double) ((JSONObject) jo.getJSONArray("PROB").get(0)).get("CONFIDENCE");
        jop = createJsonEntry(entry, out);
        break;
    case "classification":
        jop = createJsonEntry(entry, jo.getJSONArray("PROB"));
        break;
    }
    return jop;
}

From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.CoreRestorer.java

protected void runRestore(DatabaseDriver databaseDriver, String fileName)
        throws IOException, InterruptedException, RunProcessException {
    int i = 1;/*from w w w  . j a  v a 2s . c o m*/
    while (true) {
        Process p = this.runCommandLine(databaseDriver.getRestoreCommandLine(), true);
        this.filer.retrieve(p.getOutputStream(), fileName);
        p.waitFor();
        if (p.exitValue() == 0) {
            break;
        }
        if (i >= this.dbCommandRetry) {
            throw new RunProcessException("\nError during process (exit code is " + p.exitValue() + "): ");
        }
        logger.warn("Retry {}/{}: fail to restore data for file {}.", i, dbCommandRetry, fileName);
        Thread.sleep(10000);
        i++;
    }
}

From source file:net.landora.video.playerbackends.GenericPlayerBackend.java

@Override
public void playFile(File file) {
    try {/*from   w  w w .j  a  v  a  2  s  .  c  o  m*/
        List<String> args = new ArrayList<String>();
        args.add(ProgramsAddon.getInstance().getConfiguredPath(program));
        args.addAll(Arrays.asList(extraArgs));
        args.add(file.getAbsolutePath());

        ProcessBuilder process = new ProcessBuilder(args);
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

    } catch (Exception e) {
        log.error("Error playing file with " + program.getName() + ": " + file, e);
    }
}

From source file:com.seniorproject.semanticweb.services.HadoopService.java

private void deleteFolderFromHadoop() throws IOException, InterruptedException {
    Process ps2 = Runtime.getRuntime().exec("hadoop fs -rm -r /user/admin/SeniorData/out4");
    ps2.waitFor();
    java.io.InputStream is2 = ps2.getInputStream();
    byte b2[] = new byte[is2.available()];
    is2.read(b2, 0, b2.length);/*from  w ww  . j  a  va 2  s  .c o m*/
    System.out.println(new String(b2));
}

From source file:com.serena.rlc.provider.filesystem.client.FilesystemClient.java

public void localExec(String execScript, String execDir, String execParams, boolean ignoreErrors)
        throws FilesystemClientException {
    Path script = Paths.get(execDir + File.separatorChar + execScript);

    try {// w  w  w  .j ava 2s. c  o  m
        if (!Files.exists(script)) {
            if (ignoreErrors) {
                logger.debug("Execution script " + script.toString() + " does not exist, ignoring...");
            } else {
                throw new FilesystemClientException(
                        "Execution script " + script.toString() + " does not exist");
            }
        } else {
            ProcessBuilder pb = new ProcessBuilder(script.toString());
            pb.directory(new File(script.getParent().toString()));
            System.out.println(pb.directory().toString());
            logger.debug("Executing script " + execScript + " in directory " + execDir + " with parameters: "
                    + execParams);
            Process p = pb.start(); // Start the process.
            p.waitFor(); // Wait for the process to finish.
            logger.debug("Executed script " + execScript + " successfully.");
        }
    } catch (Exception e) {
        logger.debug(e.getLocalizedMessage());
        throw new FilesystemClientException(e.getLocalizedMessage());
    }

}

From source file:org.elasticsearch.qa.die_with_dignity.DieWithDignityIT.java

public void testDieWithDignity() throws Exception {
    // deleting the PID file prevents stopping the cluster from failing since it occurs if and only if the PID file exists
    final Path pidFile = PathUtils.get(System.getProperty("pidfile"));
    final List<String> pidFileLines = Files.readAllLines(pidFile);
    assertThat(pidFileLines, hasSize(1));
    final int pid = Integer.parseInt(pidFileLines.get(0));
    Files.delete(pidFile);//from w  ww. jav  a 2s.  c  om
    IOException e = expectThrows(IOException.class,
            () -> client().performRequest(new Request("GET", "/_die_with_dignity")));
    Matcher<IOException> failureMatcher = instanceOf(ConnectionClosedException.class);
    if (Constants.WINDOWS) {
        /*
         * If the other side closes the connection while we're waiting to fill our buffer
         * we can get IOException with the message below. It seems to only come up on
         * Windows and it *feels* like it could be a ConnectionClosedException but
         * upstream does not consider this a bug:
         * https://issues.apache.org/jira/browse/HTTPASYNC-134
         *
         * So we catch it here and consider it "ok".
        */
        failureMatcher = either(failureMatcher).or(
                hasToString(containsString("An existing connection was forcibly closed by the remote host")));
    }
    assertThat(e, failureMatcher);

    // the Elasticsearch process should die and disappear from the output of jps
    assertBusy(() -> {
        final String jpsPath = PathUtils.get(System.getProperty("runtime.java.home"), "bin/jps").toString();
        final Process process = new ProcessBuilder().command(jpsPath).start();
        assertThat(process.waitFor(), equalTo(0));
        try (InputStream is = process.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line;
            while ((line = in.readLine()) != null) {
                final int currentPid = Integer.parseInt(line.split("\\s+")[0]);
                assertThat(line, pid, not(equalTo(currentPid)));
            }
        }
    });

    // parse the logs and ensure that Elasticsearch died with the expected cause
    final List<String> lines = Files.readAllLines(PathUtils.get(System.getProperty("log")));

    final Iterator<String> it = lines.iterator();

    boolean fatalErrorOnTheNetworkLayer = false;
    boolean fatalErrorInThreadExiting = false;

    while (it.hasNext() && (fatalErrorOnTheNetworkLayer == false || fatalErrorInThreadExiting == false)) {
        final String line = it.next();
        if (line.contains("fatal error on the network layer")) {
            fatalErrorOnTheNetworkLayer = true;
        } else if (line.matches(".*\\[ERROR\\]\\[o.e.b.ElasticsearchUncaughtExceptionHandler\\] \\[node-0\\]"
                + " fatal error in thread \\[Thread-\\d+\\], exiting$")) {
            fatalErrorInThreadExiting = true;
            assertTrue(it.hasNext());
            assertThat(it.next(), equalTo("java.lang.OutOfMemoryError: die with dignity"));
        }
    }

    assertTrue(fatalErrorOnTheNetworkLayer);
    assertTrue(fatalErrorInThreadExiting);
}