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:io.hops.hopsworks.common.security.PKIUtils.java

public static String createCRL(Settings settings, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Creating crl...");
    String generatedCrlFile;/*w w  w . j ava2  s  .co  m*/
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
        generatedCrlFile = settings.getIntermediateCaDir() + "/crl/intermediate.crl.pem";
    } else {
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
        generatedCrlFile = settings.getCaDir() + "/crl/ca.crl.pem";
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-gencrl");
    cmds.add("-out");
    cmds.add(generatedCrlFile);

    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to create crl. Exit value: " + exitValue);
    }
    logger.info("Created crl.");
    return FileUtils.readFileToString(new File(generatedCrlFile));
}

From source file:com.clavain.alerts.Methods.java

public static boolean sendSMSMessage(String message, String mobile_nr) {
    boolean retval = false;
    // http://smsflatrate.net/schnittstelle.php?key=ff&to=00491734631526&type=4&text=ALERT:%20Notification%20Test%20(HTTPS)%20-%20HTTP%20Critical-%20OK%20String%20not%20found
    try {/* www  .j  a v  a  2 s  . c o  m*/
        if (p.getProperty("sms.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.gw");
            if (mobile_nr.startsWith("0049")) {
                gw = p.getProperty("smsflatrate.gwde");
            }
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("bulksms")) {
            // http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username=ff&password=yt89hjfff98&message=Hey%20Fucker&msisdn=491734631526
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username="
                    + p.getProperty("bulksms.username") + "&password=" + p.getProperty("bulksms.password")
                    + "&message=" + msg + "&msisdn=" + mobile_nr);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().startsWith("0")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("twilio")) {
            // reformat number?
            if (mobile_nr.startsWith("00")) {
                mobile_nr = "+" + mobile_nr.substring(2, mobile_nr.length());
            } else if (mobile_nr.startsWith("0")) {
                mobile_nr = "+" + mobile_nr.substring(1, mobile_nr.length());
            }
            TwilioRestClient client = new TwilioRestClient(p.getProperty("twilio.accountsid"),
                    p.getProperty("twilio.authtoken"));
            //String msg = URLEncoder.encode(message);
            // Build the parameters 
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("To", mobile_nr));
            params.add(new BasicNameValuePair("From", p.getProperty("twilio.fromnr")));
            params.add(new BasicNameValuePair("Body", message));

            MessageFactory messageFactory = client.getAccount().getMessageFactory();
            Message tmessage = messageFactory.create(params);
            logger.info("twilio: msg send to " + mobile_nr + " sid: " + tmessage.getSid() + " status: "
                    + tmessage.getStatus() + " twilio emsg: " + tmessage.getErrorMessage());

        } else if (p.getProperty("sms.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("sms.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("sms.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();
        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendSMSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}

From source file:ee.ria.xroad.proxy.messagelog.TestUtil.java

static ShellCommandOutput runShellCommand(String command) {
    if (isBlank(command)) {
        return null;
    }//  www .ja  v a2s . co m

    log.info("Executing shell command: \t{}", command);

    try {
        Process process = new ProcessBuilder(command.split("\\s+")).start();

        StandardErrorCollector standardErrorReader = new StandardErrorCollector(process);

        StandardOutputReader standardOutputReader = new StandardOutputReader(process);

        standardOutputReader.start();
        standardErrorReader.start();

        standardOutputReader.join();
        standardErrorReader.join();
        process.waitFor();

        int exitCode = process.exitValue();

        return new ShellCommandOutput(exitCode, standardOutputReader.getStandardOutput(),
                standardErrorReader.getStandardError());
    } catch (Exception e) {
        log.error("Failed to execute archive transfer command '{}'", command);
        throw new RuntimeException(e);
    }
}

From source file:com.evolveum.midpoint.test.util.TestUtil.java

public static String execSystemCommand(String command, boolean ignoreExitCode)
        throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    LOGGER.debug("Executing system command: {}", command);
    Process process = runtime.exec(command);
    int exitCode = process.waitFor();
    LOGGER.debug("Command exit code: {}", exitCode);
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    StringBuilder output = new StringBuilder();
    String line = null;/*  w w  w .j  a va  2s . c om*/
    while ((line = reader.readLine()) != null) {
        output.append(line);
    }
    reader.close();
    String outstring = output.toString();
    LOGGER.debug("Command output:\n{}", outstring);
    if (!ignoreExitCode && exitCode != 0) {
        String msg = "Execution of command '" + command + "' failed with exit code " + exitCode;
        LOGGER.error("{}", msg);
        throw new IOException(msg);
    }
    return outstring;
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Run command cmd in separate process in directory
 *
 * @param directory    run in this directory
 * @param cmd          command to run/* w  w  w  .ja  v  a 2  s. c  o m*/
 * @param errorMessage error message if process didn't finish with exit value 0
 * @return stdout combined with stderr
 * @throws Exception
 */
public static String runCmd(File directory, List<String> cmd, String errorMessage) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(directory);
    pb.redirectErrorStream(true); // error sent to output stream
    Process p = pb.start();

    // get output stream to string
    String s;
    StringBuilder sb = new StringBuilder();
    BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((s = stdout.readLine()) != null) {
        logger.info(s);
        sb.append(s);
        sb.append('\n');
    }
    String sbs = sb.toString();
    int exitValue = p.waitFor();
    if (exitValue != 0)
        throw new Exception(errorMessage + " exit value " + exitValue + "  " + sbs);
    return sbs;
}

From source file:it.polimi.diceH2020.plugin.control.DICEWrap.java

/**
 * Creates JSIM model (.jsimg) from pnml in the given directory  
 * //from  w w w.ja  v a 2s.co m
 * @throws IOException
 */

public static void genJSIM(int cdid, String alt, String lastTransactionId) throws IOException {
    Configuration conf = Configuration.getCurrent();
    File sparkIdx = new File(Preferences.getSavingDir() + "spark.idx");
    String fileName;

    if (Configuration.getCurrent().getIsPrivate()) {
        fileName = Preferences.getSavingDir() + conf.getID() + "J" + cdid + "inHouse" + alt;
    } else {
        fileName = Preferences.getSavingDir() + conf.getID() + "J" + cdid + alt.replaceAll("-", "");
    }

    try {
        FileWriter fw = new FileWriter(sparkIdx.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(lastTransactionId);
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String pnmlPath = Preferences.getSavingDir() + conf.getID() + "J" + cdid + alt.replaceAll("-", "")
            + ".pnml";
    String outputPath = new File(fileName + ".jsimg").getAbsolutePath();
    String indexPath = sparkIdx.getAbsolutePath();

    String command = String.format("java -cp %sbin:%slib/* PNML_Pre_Processor gspn %s %s %s",
            Preferences.getJmTPath(), Preferences.getJmTPath(), pnmlPath, outputPath, indexPath);

    System.out.println("Calling PNML_Pre_Processor");
    System.out.println(command);

    Process proc;

    try {
        proc = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    try {
        proc.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

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

/**
 *
 * @param cmd//from  ww w. j  a  v  a  2  s  .co  m
 * @return
 */
public static List<String> invokeNativeCommandAndGetResult(String[] cmd) {
    List<String> outputList = new ArrayList<String>();

    try {
        Runtime r = Runtime.getRuntime();
        Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            pb.redirectErrorStream(true);
        //            Process ps = pb.start();

        BufferedReader rdr = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        String in = rdr.readLine();
        while (in != null) {
            outputList.add(in);
            in = rdr.readLine();
        }

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

        ps.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return outputList;
}

From source file:exm.stc.ui.Main.java

private static void runPreprocessor(Logger logger, String input, String output, List<String> preprocArgs) {
    List<String> cmd = new ArrayList<String>();
    /*//from ww w  .ja v a2 s  .  c  o  m
      -undef flag is provided to disable non-standard macros
     */
    if (useGCCProcessor()) {
        // We use gcc -E because cpp is broken on Mac GCC 4.2.1
        //    Cf. http://stackoverflow.com/questions/4137923
        cmd.addAll(Arrays.asList("gcc", "-E", "-undef", "-x", "c", input, "-o", output));
    } else {
        cmd.addAll(Arrays.asList("cpp", "-undef", input, output));
    }

    for (String dir : Settings.getModulePath()) {
        cmd.add("-I");
        cmd.add(dir);
    }

    for (String macro : preprocArgs) {
        cmd.add("-D");
        cmd.add(macro);
    }

    String cmdString = StringUtils.join(cmd, ' ');
    try {
        logger.debug("Running cpp: " + cmdString);
        Process cpp = Runtime.getRuntime().exec(cmd.toArray(new String[] {}));
        int cppExitCode = -1;
        boolean done = false;
        do {
            try {
                cppExitCode = cpp.waitFor();
                done = true;
            } catch (InterruptedException ex) {
                // Continue on after spurious interrupt
            }
        } while (!done);

        StringWriter sw = new StringWriter();
        IOUtils.copy(cpp.getErrorStream(), sw, "UTF-8");
        String cppStderr = sw.toString();

        logger.debug("Preprocessor exit code: " + cppExitCode);
        logger.debug("Preprocessor stderr: " + cppStderr);

        if (cppExitCode != 0) {
            // Print stderr message first, then clarify that failure was in preprocessor
            System.out.println(cppStderr);
            System.out.println("Aborting due to failure in cpp preprocessor invoked as: " + cmdString + ". "
                    + ("Exit code was " + cppExitCode + ". "));
            System.exit(1);
        } else if (cppStderr.length() != 0) {
            logger.warn("Preprocessor warnings:\n" + cppStderr);
        }
    } catch (IOException e) {
        System.out.println("I/O error while launching preprocessor with command line:" + cmdString + ": "
                + e.getMessage());
        System.exit(1);
    }
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private static List<String> system(ProcessBuilder.Redirect errorRedirector,
        ProcessBuilder.Redirect outputRedirector, String... command) {
    try {//from   w w w  .  j a v  a  2  s . c  om
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectError(errorRedirector);
        builder.redirectOutput(outputRedirector);
        final Process process = builder.start();
        Verify.verify(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:Main.java

private static void destroyPid(int pid) {

    Process suProcess = null;
    PrintStream outputStream = null;
    try {/*from  w  w w .j a  va  2 s .com*/
        suProcess = Runtime.getRuntime().exec("su");
        outputStream = new PrintStream(new BufferedOutputStream(suProcess.getOutputStream(), 8192));
        outputStream.println("kill " + pid);
        outputStream.println("exit");
        outputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
        if (suProcess != null) {
            try {
                suProcess.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}