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.github.hdl.tensorflow.yarn.app.TFClient.java

private void execCmd(List<String> cmd) {
    try {/*from  w  ww.  j a va2s  .  c  o m*/
        Process process = new ProcessBuilder().command(cmd).inheritIO().start();
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:ape.ForkBombCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    // The explicit bash command that is executed
    String cmd = ":(){ :|: & };:&";

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);//from w ww  .  j av  a 2  s  .  co  m
    Process sh = pb.start();
    InputStream shIn = sh.getInputStream();
    try {
        if (sh.waitFor() != 0) {
            System.err.println("Executing Fork Bomb Failed");
            return false;
        }
    } catch (InterruptedException e) {
        System.out.println("The fork command received an Interrupt.");
        e.printStackTrace();
        return false;
    }
    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 forkbomb process.");
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypterDecrypterIT.java

@Test
public void testOpenSSLEncJavaDec() throws Exception {
    //Encrypt with openssl
    final File encryptFileScript = setupTempFile("encryptFile.sh");
    encryptFileScript.setExecutable(true);

    final File publicKey = setupTempFile("my.wisc.edu-public.pem");
    final File testFile = setupTempFile("testFile.txt");

    final ProcessBuilder pb = new ProcessBuilder(encryptFileScript.getAbsolutePath(),
            publicKey.getAbsolutePath(), testFile.getAbsolutePath());

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }/*from ww  w .ja  v a 2s . c  o  m*/
    assertEquals(0, ret);

    //Decrypt with java
    final File encryptedFile = new File(testFile.getParentFile(), "testFile.txt.tar");

    final InputStream encTestFileInStream = new FileInputStream(encryptedFile);
    final ByteArrayOutputStream testFileOutStream = new ByteArrayOutputStream();
    fileDecrypter.decrypt(encTestFileInStream, testFileOutStream);
    final String actual = new String(testFileOutStream.toByteArray(), Charset.defaultCharset()).trim();

    //Verify
    final String expected = FileUtils.readFileToString(testFile);
    assertEquals(expected, actual);
}

From source file:fr.inria.oak.paxquery.algebra.operators.BaseLogicalOperator.java

public void draw(String folder, String givenFileName) {
    //System.out.println("BaseLogicalOperator:");
    //System.out.println("\tfolder: "+folder);
    //System.out.println("\tgivenFileName: "+givenFileName);

    StringBuffer sb = new StringBuffer();
    sb.append("digraph  g{\n edge [dir=\"back\"]\n");
    recursiveDotString(sb, 0, 100);/*from   www  .j a va 2s  .  c om*/
    try {
        if (givenFileName == null) {
            givenFileName = "" + System.currentTimeMillis();
        }
        String pathName = "";
        int lastSlash = givenFileName.lastIndexOf(File.separator);
        if (lastSlash > 0) {
            pathName = givenFileName.substring(0, lastSlash);
            File dir = new File(pathName);
            dir.mkdirs();
        }

        String fileNameDot = new String(folder + File.separator + givenFileName + "-logplan.dot");
        String fileNamePNG = new String(folder + File.separator + givenFileName + "-logplan.png");

        //System.out.println("fileNameDot: "+fileNameDot);
        FileWriter file = new FileWriter(fileNameDot);
        file.write(new String(sb));
        file.write("}\n");
        file.close();
        Runtime r = Runtime.getRuntime();
        String com = new String("dot -Tpng " + fileNameDot + " -o " + fileNamePNG);
        Process p = r.exec(com);
        p.waitFor();
        //System.out.println("Logical plan drawn.");
        logger.debug("Logical plan drawn.");
    } catch (Exception e) {
        logger.error("Exception: ", e);
    }
}

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

@Override
public JSONObject classify(String audioFile) {
    String line = "";
    String fullLine = "";
    int idx = run_command.lastIndexOf("/");
    String full_path = paths.SMILExtractDir + run_command.substring(0, idx);
    String str = "bash " + paths.SMILExtractDir + run_command + " " + audioFile;
    try {/*from w w  w  . j a v  a2 s.  c o  m*/
        logger_instance.write(1, "full_path=" + full_path);
        logger_instance.write(1, "bash command: " + str);
        for (int trial = 0; trial < 3; trial++) {
            fullLine = "";
            Process p = Runtime.getRuntime().exec(str, null, new File(full_path));
            p.waitFor();
            logger_instance.write(1, "bash 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;
            if (fullLine.length() > 0)
                break;
        }
        logger_instance.write(1, "bash output:" + fullLine);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    JSONObject jo = null;
    try {
        jo = new JSONObject(fullLine.substring(fullLine.indexOf("{")));
    } catch (JSONException e) {
        System.out.println(fullLine);
        e.printStackTrace();
    } catch (StringIndexOutOfBoundsException e) {
        System.out.println(fullLine);
        e.printStackTrace();
    }

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

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypterDecrypterIT.java

@Test
public void testJavaEncOpenSSLDec() throws Exception {
    //Encrypt with Java
    final File testFile = setupTempFile("testFile.txt");

    InputStream testFileInStream = new FileInputStream(testFile);

    final File encFile = this.testFolder.newFile("testFile.txt.tar");
    this.fileEncrypter.encrypt("testFile.txt", (int) testFile.length(), testFileInStream,
            new FileOutputStream(encFile));

    //Decrypt with OpenSSL
    final File decryptFileScript = setupTempFile("decryptFile.sh");
    decryptFileScript.setExecutable(true);

    final File privateKey = setupTempFile("my.wisc.edu-private.pem");

    final ProcessBuilder pb = new ProcessBuilder(decryptFileScript.getAbsolutePath(),
            privateKey.getAbsolutePath(), encFile.getAbsolutePath());

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }//from   w  ww.  j  a  v  a2s  .c  o m
    assertEquals(0, ret);

    final File decryptedFile = new File(encFile.getParentFile(), "testFile.txt");

    //Verify
    final String expected = FileUtils.readFileToString(testFile);
    final String actual = FileUtils.readFileToString(decryptedFile);
    assertEquals(expected, actual);
}

From source file:com.teasoft.teavote.util.Utilities.java

public boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) throws Exception {
    String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword
            + " --events --routines --triggers -B " + dbName + " -r " + path;
    Process runtimeProcess;
    runtimeProcess = Runtime.getRuntime().exec(executeCmd);
    int processComplete = runtimeProcess.waitFor();
    return processComplete == 0;
}

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

/**
 * Archive the result of the previous task
 *//*  ww w .  jav a 2  s .  c o m*/
public TaskResult work(Task task) {
    logger.info("Executing with arguments");
    TaskResult result = new TaskResult();

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

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

    try {
        // create the temp files, and execute the command
        File inputFile = File.createTempFile("execute", "dat");
        File outputFile = File.createTempFile("execute", "dat");

        String[] exe = { command, inputFile.getAbsolutePath(), outputFile.getAbsolutePath() };

        FileOutputStream fos = new FileOutputStream(inputFile);
        fos.write(inputData);
        fos.close();

        Process p = Runtime.getRuntime().exec(exe);
        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("outputData", 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);

        inputFile.delete();
        outputFile.delete();

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

    return result;
}

From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java

/**
 * There is a bug that prevents exiftool to read unicode file names. We can get the windows filename if necessary
 * with getMSDOSName/* w ww  . j  av a  2  s.c om*/
 * 
 * @link(http://perlmaven.com/unicode-filename-support-suggested-solution)
 * @link(http://stackoverflow.com/questions/18893284/how-to-get-short-filenames-in-windows-using-java)
 */
public static String getMSDOSName(File file) {
    try {
        String path = getAbsolutePath(file);
        String path2 = file.getAbsolutePath();
        System.out.println(path2);
        // String toExecute = "cmd.exe /c for %I in (\"" + path2 + "\") do @echo %~fsI";
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","for","%I","in","(" + path2 + ")","do","@echo","%~sI");
        path2 = new File(
                "d:\\aaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbb\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();
        path2 = new File(
                "d:\\personal\\photos-tofix\\2013-proposed1-bad\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();

        System.out.println(path2);
        ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "for", "%I", "in", "(\"" + path2 + "\")", "do",
                "@echo", "%~fsI");
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","chcp 65001 & dir",path2);
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","ls",path2);
        Process process = pb.start();
        // Process process = Runtime.getRuntime().exec(execLine);
        // Process process = Runtime.getRuntime().exec(new String[]{"cmd","/c","for","%I","in","(\"" + path2 +
        // "\")","do","@echo","%~fsI"});
        process.waitFor();
        byte[] data = new byte[65536];
        // InputStreamReader isr = new InputStreamReader(process.getInputStream(), "UTF-8");
        // String charset = Charset.defaultCharset().name();
        String charset = "UTF-8";
        String lines = IOUtils.toString(process.getInputStream(), charset);
        // int size = process.getInputStream().read(data);
        // String path3 = path;
        // if (size > 0)
        // path3 = new String(data, 0, size).replaceAll("\\r\\n", "");
        String path3 = lines;
        System.out.println(pb.command());
        System.out.println(path3);
        byte[] data2 = new byte[65536];
        int size2 = process.getErrorStream().read(data2);
        if (size2 > 0) {
            String error = new String(data2, 0, size2);
            System.out.println(error);
            throw new RuntimeException("Error was thrown " + error);
        }
        return path3;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java

@Override
public String handle(Task aTask) throws Exception {
    File scriptFile = File.createTempFile("_script", ".sh");
    File logFile = File.createTempFile("log", null);
    FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script"));
    try (PrintStream stream = new PrintStream(logFile);) {
        Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath()));
        int chmodRetCode = chmod.waitFor();
        if (chmodRetCode != 0) {
            throw new ExecuteException("Failed to chmod", chmodRetCode);
        }/*www  .  jav  a 2 s .  c o m*/
        CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath());
        logger.debug("{}", cmd);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return FileUtils.readFileToString(logFile);
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(logFile)));
    } finally {
        FileUtils.deleteQuietly(logFile);
        FileUtils.deleteQuietly(scriptFile);
    }
}