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.sap.prd.mobile.ios.mios.Forker.java

static int forkProcess(final PrintStream out, final File executionDirectory, final String... args)
        throws IOException {

    if (out == null)
        throw new IllegalArgumentException("Print stream for log handling was not provided.");

    if (args == null || args.length == 0)
        throw new IllegalArgumentException("No arguments has been provided.");

    for (final String arg : args)
        if (arg == null || arg.isEmpty())
            throw new IllegalArgumentException(
                    "Invalid argument '" + arg + "' provided with arguments '" + Arrays.asList(args) + "'.");

    final ProcessBuilder builder = new ProcessBuilder(args);

    if (executionDirectory != null)
        builder.directory(executionDirectory);

    builder.redirectErrorStream(true);//from   ww w . ja va  2  s .  co m

    InputStream is = null;

    //
    // TODO: check if there is any support for forking processes in
    // maven/plexus
    //

    try {

        final Process process = builder.start();

        is = process.getInputStream();

        handleLog(is, out);

        return process.waitFor();

    } catch (InterruptedException e) {
        throw new RuntimeException(e.getClass().getName()
                + " caught during while waiting for a forked process. This exception is not expected to be caught at that time.",
                e);
    } finally {
        //
        // Exception raised during close operation below are not reported.
        // That is actually bad.
        // We do not have any logging facility here and we cannot throw the
        // exception since this would swallow any
        // other exception raised in the try block.
        // May be we should revisit that ...
        //
        IOUtils.closeQuietly(is);
    }
}

From source file:Main.java

public static String getMotherboardSN() {
    String result = "";
    try {//from  w  w  w .  j av a2s  .  co  m
        File file = File.createTempFile("realhowto", ".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n" + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";

        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        input.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result.trim();
}

From source file:Main.java

public static File writeLog(String root, String filename) {
    StringBuilder log = new StringBuilder();
    try {//  ww w. jav a  2s  .  c o  m
        Process process = Runtime.getRuntime().exec("logcat -d");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            log.append(line).append("\n");
        }
    } catch (IOException e) {
        log.append(e.toString());
    }

    File file = new File(root, filename);

    try {
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fOut);

        // Write the string to the file
        osw.write(log.toString());
        osw.flush();
        osw.close();

    } catch (Exception e) {
        Log.e(TAG, String.format("Failed to write log to [%s]", file), e);
    }
    return file;
}

From source file:Main.java

/**
 * Check that console output contains the specified text
 *
 * @param command    Console command//w w w .j a  v  a2 s  . c o  m
 * @param outputLine Text to check for
 * @return True if the output line was found in the logs from the given
 * command, false otherwise.
 */
public static boolean checkConsole(String command, String outputLine) throws Exception {

    boolean stringFound = false;
    Process process = Runtime.getRuntime().exec(command);
    String line;
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    while ((line = bufferedReader.readLine()) != null) {
        if (line.contains(outputLine)) {
            stringFound = true;
            break;
        }

    }
    return stringFound;
}

From source file:ml.shifu.shifu.executor.ProcessManager.java

public static int runShellProcess(String currentDir, String[] args) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    processBuilder.directory(new File(currentDir));
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    LogThread logThread = new LogThread(process, process.getInputStream(), currentDir);
    logThread.start();/*from  ww w  .j  av  a 2  s  .  co  m*/

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        process.destroy();
    } finally {
        logThread.setToQuit(true);
    }

    LOG.info("Under {} directory, finish run `{}`", currentDir, args);
    return process.exitValue();
}

From source file:Main.java

public static String getProp(String name) {
    String line = null;//  w  w  w  . j a  v a 2  s  .  co m
    BufferedReader input = null;
    try {
        Process p = Runtime.getRuntime().exec("getprop " + name);
        input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
        line = input.readLine();
        input.close();
    } catch (IOException ex) {
        Log.e(TAG, "Unable to read prop " + name, ex);
        return null;
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return line;
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.CmdStream.java

/**
 * Performs system command call.//from w ww. j a v a2s.  c om
 * 
 * @param cmdData
 *            command data: name and parameters
 * @return command response string
 * @throws Exception
 *             if exception occurs while performing system command call
 */
protected static String executeCommand(String cmdData) throws Exception {
    if (StringUtils.isEmpty(cmdData)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "CmdStream.cant.execute.cmd"), cmdData);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "CmdStream.invoking.command"),
            cmdData);

    Process p = Runtime.getRuntime().exec(cmdData);

    return Utils.readInput(p.getInputStream(), false);
}

From source file:edu.berkeley.sparrow.daemon.util.Resources.java

public static int getSystemMemoryMb(Configuration conf) {
    int systemMemory = -1;
    try {/*  ww w  . j  a  va 2  s.  c  om*/
        Process p = Runtime.getRuntime().exec("cat /proc/meminfo");
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = in.readLine();
        while (line != null) {
            if (line.contains("MemTotal")) {
                String[] parts = line.split("\\s+");
                if (parts.length > 1) {
                    int memory = Integer.parseInt(parts[1]) / 1000;
                    systemMemory = memory;
                }
            }
            line = in.readLine();
        }
    } catch (IOException e) {
    }
    if (conf.containsKey(SparrowConf.SYSTEM_MEMORY)) {
        return conf.getInt(SparrowConf.SYSTEM_MEMORY);
    } else {
        if (systemMemory != -1) {
            return systemMemory;
        } else {
            return SparrowConf.DEFAULT_SYSTEM_MEMORY;
        }
    }
}

From source file:Main.java

private static String attemptCommand(String[] command) {
    StringBuffer buffer = null;//from   www  . j ava 2 s. com

    try {

        Process p = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line;

        while ((line = reader.readLine()) != null) {
            if (buffer == null) {
                buffer = new StringBuffer();
            }

            buffer.append(line);
        }

        if (buffer != null) {
            return buffer.toString();
        }
        return null;
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.surfs.storage.common.util.CmdUtils.java

public static Map<String, Object> command(String cmd) {
    Map<String, Object> resp = new HashMap<String, Object>();
    BufferedReader bufRead = null;
    try {/*from  w  ww  .  ja  va  2  s. c  o  m*/
        //bufRead = executeCmdForReader(cmd);
        Process pro = Runtime.getRuntime().exec(cmd);
        bufRead = new BufferedReader(new InputStreamReader(pro.getInputStream(), "UTF-8"));
        // 0-success,others-failure
        int status = pro.waitFor();
        LogFactory.info("cmd:" + cmd);
        LogFactory.info("status:" + status);
        String response = null;
        while ((response = bufRead.readLine()) != null) {
            if (response.indexOf("avg") >= 0) {
                String[] ms = response.split("=")[1].split("\\/");
                resp.put("status", status);
                resp.put("latency", Float.parseFloat(ms[1]));
                LogFactory.info("latency:" + ms[1]);
                return resp;
            }
        }
    } catch (Exception e) {
        resp.put("status", 1);
        resp.put("response", "time out");
        return resp;
    } finally {
        if (bufRead != null)
            try {
                bufRead.close();
            } catch (Exception e) {
            }
    }
    resp.put("status", 1);
    resp.put("response", "time out");
    return resp;
}