Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

In this page you can find the example usage for java.lang ProcessBuilder ProcessBuilder.

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:com.twitter.hraven.hadoopJobMonitor.notification.Mail.java

public static void send(String subject, String msg, String to) {
    List<String> commands = new LinkedList<String>();
    commands.add("/bin/bash");
    commands.add("-c");
    commands.add("echo \"" + msg + "\" | mail -s \"" + subject + "\" " + to + "," + CC);
    //This option is not supported by all mail clients: + " -c " + CC);
    //This option is not supported by all mail clients: + " -- -f " + ADMIN);
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process p;/*from   ww w  .  jav a 2 s.  c om*/
    int exitValue = -1;
    try {
        p = pb.start();
        exitValue = p.waitFor();
        LOG.info("Send email to " + to + " exitValue is " + exitValue);
    } catch (IOException e) {
        LOG.error("Error in executing mail command", e);
    } catch (InterruptedException e) {
        LOG.error("Error in executing mail command", e);
    } finally {
        if (exitValue != 0) {
            LOG.fatal(commands);
            //        ExitUtil.terminate(1, "Could not send mail: " + "exitValue was "
            //            + exitValue);
        }
    }
}

From source file:JMeterProcessing.JMeterPropertiesGenerator.java

private static void doCurl(String url, String[] idNames, Map<String, Long> idValuesMap)
        throws JSONException, IOException {
    String[] command = { "curl", "-H", "Accept:application/json", "-X", "GET", "-u",
            _USERNAME + ":" + _PASSWORD, url };

    ProcessBuilder process = new ProcessBuilder(command);

    Process p = process.start();//  w  w w.  j a v a 2s . c  o m

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line = reader.readLine();

    while (line != null) {
        sb.append(line);

        line = reader.readLine();
    }

    String result = sb.toString();

    if (result != null) {
        JSONObject curlResult = new JSONObject(result);

        JSONObject jsonObject;

        try {
            JSONArray data = curlResult.getJSONArray("data");

            jsonObject = data.getJSONObject(0);
        } catch (JSONException e) {
            jsonObject = curlResult.getJSONObject("data");
        }

        for (String idName : idNames) {
            Long idValue = jsonObject.getLong(idName);

            idValuesMap.put(idName, idValue);
        }
    }
}

From source file:com.alibaba.jstorm.utils.SystemOperation.java

public static String exec(String cmd) throws IOException {
    LOG.debug("Shell cmd: " + cmd);
    Process process = new ProcessBuilder(new String[] { "/bin/bash", "-c", cmd }).start();
    try {//from   w  w w  .j a va  2  s .co m
        process.waitFor();
        String output = IOUtils.toString(process.getInputStream());
        String errorOutput = IOUtils.toString(process.getErrorStream());
        LOG.debug("Shell Output: " + output);
        if (errorOutput.length() != 0) {
            LOG.error("Shell Error Output: " + errorOutput);
            throw new IOException(errorOutput);
        }
        return output;
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    }

}

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();//from www .  j av  a  2 s  .  c  o  m
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:com.github.born2snipe.project.setup.scm.GitRepoInitializer.java

private void executeCommandIn(File projectDir, String... commands) {
    try {//ww w . j a  v  a 2 s  .  co  m
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.directory(projectDir);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        System.out.println(IOUtils.toString(process.getInputStream()));
        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.offbynull.portmapper.common.ProcessUtils.java

/**
 * Run a process and dump the stdout stream to a string.
 * @param timeout maximum amount of time the process can take to run
 * @param command command/*  w w w. java2  s  .com*/
 * @param args arguments
 * @return stdout from the process dumped to a string
 * @throws IOException if the process encounters an error
 * @throws NullPointerException if any arguments are {@code null} or contains {@code null}
 * @throws IllegalArgumentException any numeric argument is negative
 */
public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException {
    Validate.notNull(command);
    Validate.noNullElements(args);
    Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout);

    String[] pbCmd = new String[args.length + 1];
    pbCmd[0] = command;
    System.arraycopy(args, 0, pbCmd, 1, args.length);

    ProcessBuilder builder = new ProcessBuilder(pbCmd);

    final AtomicBoolean failedFlag = new AtomicBoolean();

    Timer timer = new Timer("Process timeout timer", true);
    Process proc = null;
    try {
        proc = builder.start();

        final Process finalProc = proc;
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                failedFlag.set(true);
                finalProc.destroy();
            }
        }, timeout);

        String ret = IOUtils.toString(proc.getInputStream());
        if (failedFlag.get()) {
            throw new IOException("Process failed");
        }

        return ret;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
        timer.cancel();
        timer.purge();
    }
}

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;/*w w  w.  j a va 2 s .c  o  m*/
    ProcessOutput processOutput = null;
    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:hu.bme.mit.trainbenchmark.sql.process.MySqlProcess.java

public static void run(final String command[]) throws IOException, InterruptedException {
    final ProcessBuilder pb = new ProcessBuilder(command);
    final Process p = pb.start();
    p.waitFor();/* ww w. j  av a2  s . c o  m*/

    final String stdOut = getInputAsString(p.getInputStream());
    final String stdErr = getInputAsString(p.getErrorStream());
    // System.out.println(stdOut);
    // System.out.println(stdErr);
}

From source file:com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequenceBinaries.java

@Override
public void runSequence() throws BootSequenceException {
    String[] commands = { "/bin/chmod", "-R", "+x", binariesPath.getAbsolutePath() };
    logger.debug("Running command: " + String.join(" ", commands) + " ...");
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process p = null;//from   w  w  w  .jav a 2s  .  c o  m
    try {
        p = pb.start();
        p.waitFor();
    } catch (IOException | InterruptedException e) {
        throw new BootSequenceException("Error when booting: " + e.getMessage(), e);
    }
    logger.debug("Finished Command: " + String.join(" ", commands) + ".");
}

From source file:es.ua.dlsi.patch.translation.LocalApertiumTranslator.java

public Set<String> getTranslation(final String input) {

    Set<String> output = new HashSet<>();
    String finalline = "";
    // pull from the map if already there

    try {/*from w w w . j a  va2 s. c o m*/
        String[] command = { "apertium", "-u", langCmd };
        ProcessBuilder probuilder = new ProcessBuilder(command);

        Process process = probuilder.start();
        OutputStream stdin = process.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        writer.write(input);
        writer.newLine();
        writer.flush();
        writer.close();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            finalline += line;
        }
        br.close();

    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(-1);
    }
    output.add(finalline);
    return output;
}