Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

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

Prototype

public abstract InputStream getInputStream();

Source Link

Document

Returns the input stream connected to the normal output of the process.

Usage

From source file:com.arm.connector.bridge.core.Utils.java

/**
 * Execute the AWS CLI// w w w  .  j  av  a  2s .  c o m
 * @param logger - ErrorLogger instance
 * @param args - arguments for the AWS CLI 
 * @return response from CLI action
 */
public static String awsCLI(ErrorLogger logger, String args) {
    // construct the arguments
    String cmd = "./aws " + args;
    String response = null;
    String error = null;

    try {
        // invoke the AWS CLI
        Process proc = Runtime.getRuntime().exec(cmd);
        response = Utils.convertStreamToString(proc.getInputStream());
        error = Utils.convertStreamToString(proc.getErrorStream());

        // wait to completion
        proc.waitFor();
        int status = proc.exitValue();

        // DEBUG
        if (status != 0) {
            // non-zero exit status
            logger.warning("AWS CLI: Invoked: " + cmd);
            logger.warning("AWS CLI: Response: " + response);
            logger.warning("AWS CLI: Errors: " + error);
            logger.warning("AWS CLI: Exit Code: " + status);
        } else {
            // successful exit status
            logger.info("AWS CLI: Invoked: " + cmd);
            logger.info("AWS CLI: Response: " + response);
            logger.info("AWS CLI: Exit Code: " + status);
        }
    } catch (IOException | InterruptedException ex) {
        logger.warning("AWS CLI: Exception for command: " + cmd, ex);
        response = null;
    }

    // return the resposne
    return response;
}

From source file:net.sf.sahi.util.Utils.java

public static String executeCommand(String[] command) throws Exception {
    StringBuffer sb = new StringBuffer();
    Process p = Runtime.getRuntime().exec(command);
    InputStream stdInput = p.getInputStream();
    InputStream stdError = p.getErrorStream();
    StringBuffer inBuffer = new StringBuffer();
    StringBuffer errBuffer = new StringBuffer();
    Thread inThread = new Thread(new StreamReader(stdInput, inBuffer));
    inThread.start();//from   ww  w.  j  a  v  a 2  s.co  m
    Thread errThread = new Thread(new StreamReader(stdError, errBuffer));
    errThread.start();
    p.waitFor();
    inThread.join();
    errThread.join();
    sb.append(inBuffer);
    sb.append(errBuffer);
    return sb.toString();
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else/*from  w ww  .ja v a 2  s . c  om*/
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {
    Process proc = null;
    int exitCode = -1;

    if (runAsRoot) {
        proc = Runtime.getRuntime().exec("su");
    } else {/*from w  w  w.  j a v a2 s  .c  o  m*/
        proc = Runtime.getRuntime().exec("sh");
    }

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {
        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();
    }

    return exitCode;
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private static List<String> system(String... command) {
    try {/*from  w  ww . j a  v  a  2  s .  c  om*/
        final Process process = new ProcessBuilder(command).start();
        Preconditions.checkState(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:com.comcast.oscar.netsnmp.NetSNMP.java

/**
 * //w  ww  . j  a v  a2 s .c  om
 * @param sSnmpTranslateCMD
 * @return OID Translation - Null is snmptranslate is not installed*/
private static ArrayList<String> runSnmpTranslate(String sSnmpTranslateCMD) {

    boolean localDebug = Boolean.FALSE;

    if (debug | localDebug)
        System.out.println(sSnmpTranslateCMD);

    ArrayList<String> als = new ArrayList<String>();

    Process p = null;
    try {
        p = Runtime.getRuntime().exec(sSnmpTranslateCMD);
    } catch (IOException e1) {
        /* If not found or installed */
        return null;
    }

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

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    String sStd_IO = "";

    /*Read the output from the command If Any */

    int iCounter = 0;
    try {
        while ((sStd_IO = stdInput.readLine()) != null) {

            //Clean up White Space
            if (!sStd_IO.isEmpty())
                als.add(sStd_IO);

            if (debug | localDebug)
                System.out.println(++iCounter + " IN: " + sStd_IO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        while ((sStd_IO = stdError.readLine()) != null) {

            als.add(sStd_IO);

            if (debug | localDebug)
                System.out.println(++iCounter + " OUT: " + sStd_IO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return als;
}

From source file:automenta.climatenet.ImportKML.java

public static void exec(String cmd) {
    try {// w w  w .j av a2 s  . c  o  m
        String[] cmdParm = { "/bin/sh", "-c", cmd };

        Process proc = Runtime.getRuntime().exec(cmdParm);
        IOUtils.copy(proc.getInputStream(), System.out);
        IOUtils.copy(proc.getErrorStream(), System.err);
        proc.waitFor();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:net.paoding.analysis.knife.PaodingMaker.java

private static String getSystemEnv(String name) {
    try {/*www  .  j av  a2  s  .  com*/
        return System.getenv(name);
    } catch (Error error) {
        String osName = System.getProperty("os.name").toLowerCase();
        try {
            String cmd;
            if (osName.indexOf("win") != -1) {
                cmd = "cmd /c SET";
            } else {
                cmd = "/usr/bin/printenv";
            }
            Process process = Runtime.getRuntime().exec(cmd);
            InputStreamReader isr = new InputStreamReader(process.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null && line.startsWith(name)) {
                int index = line.indexOf(name + "=");
                if (index != -1) {
                    return line.substring(index + name.length() + 1);
                }
            }
        } catch (Exception e) {
            log.warn("unable to read env from os" + e.getMessage(), e);
        }
    }
    return null;
}

From source file:com.matze5800.paupdater.Functions.java

public static String getRomId(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Process proc;
    BufferedReader reader;//from  w  ww.  jav a  2s  .c  o m
    String Rom = null;
    try {
        proc = Runtime.getRuntime().exec(new String[] { "/system/bin/getprop", "ro.goo.rom" });
        reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        Rom = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (Rom.equals(null)) {
        Rom = "Error parsing ro.goo.rom!";
    }
    Log.i("Local Parser", "Rom: " + Rom);
    prefs.edit().putString("Rom", Rom).commit();
    return Rom;
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*from   ww  w .j a  v a2 s  .c o m*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}