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.ms.commons.utilities.CoreUtilities.java

/**
 * ???//from  ww  w  .ja v  a2  s. c  o  m
 * 
 * @return
 */
public static String getHostName() {
    if (hostName != null) {
        return hostName;
    } else {
        try {
            String cmd = isWindowsOS() ? "hostname" : "/bin/hostname";
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            InputStream in = process.getInputStream();
            InputStreamReader inr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(inr);
            String wg = br.readLine();
            if (wg != null) {
                hostName = wg.trim();
            } else {
                hostName = "unknown hostname";
            }
        } catch (Exception e) {
            logger.error("Exception", e);
            hostName = "unknown hostname";
        }
    }
    return hostName;
}

From source file:kr.ac.kaist.wala.hybridroid.analysis.resource.AndroidDecompiler.java

private static void permission(String path) {
    String[] cmd = { "chmod", "755", path };
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);//from  w  w w . j a v a2  s  .  c  o m

    Process p = null;
    try {
        p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String r = null;

        while ((r = br.readLine()) != null) {
            System.out.println(r);
        }

        while ((r = bre.readLine()) != null) {
            System.err.println(r);
        }

        int res = p.waitFor();
        if (res != 0) {
            throw new InternalError("failed to decompile: " + path);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

@BeforeClass
public static void setUp() throws Exception {
    //testcase setup
    TestCaseContext.Builder b = new TestCaseContext.Builder();
    testCaseCollection = b.build(new File(PATH_BASE));
    File outdir = new File(PATH_ACTUAL);
    outdir.mkdirs();/*w  w  w  .  j a  v a2s.  co m*/

    //vagrant setup
    File installerTargetDir = new File(asterixProjectDir, "target");
    System.out.println(managixFolderName);
    managixFolderName = installerTargetDir.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory() && name.startsWith("asterix-installer")
                    && name.endsWith("binary-assembly");
        }

    })[0];
    invoke("cp", "-r", installerTargetDir.toString() + "/" + managixFolderName,
            asterixProjectDir + "/" + CLUSTER_BASE);

    logOutput(remoteInvoke("cp -r /vagrant/" + managixFolderName + " /tmp/asterix").getInputStream());

    logOutput(managixInvoke("configure").getInputStream());
    logOutput(managixInvoke("validate").getInputStream());

    Process p = managixInvoke("create -n vagrant-ssh -c /vagrant/cluster.xml");
    String pout = processOut(p);
    LOGGER.info(pout);
    Assert.assertTrue(checkOutput(pout, "ACTIVE"));
    //TODO: I should check for 'WARNING' here, but issue 764 stops this from being reliable 
    LOGGER.info("Test start active cluster instance PASSED");

    Process stop = managixInvoke("stop -n vagrant-ssh");
    Assert.assertTrue(checkOutput(stop.getInputStream(), "Stopped Asterix instance"));
    LOGGER.info("Test stop active cluster instance PASSED");
}

From source file:com.vmware.photon.controller.provisioner.xenon.helpers.TestEnvironment.java

public static List<Long> findUnixProcessIds(String filter, String name) {
    ArrayList processes = new ArrayList();

    try {//from w w w.j a v a  2s  .  c om
        String cmd = String.format("ps -o ppid,pid,ucomm %s", new Object[] { filter });
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
        input.readLine();

        while (true) {
            String[] columns;
            String ucomm;
            do {
                String line;

                if ((line = input.readLine()) == null) {
                    input.close();
                    return processes;
                }

                columns = line.trim().split("\\s+", 3);
                ucomm = columns[2].trim();
                if (name.startsWith(ucomm)) {
                    int i = 0;
                }
            } while (name != null && !ucomm.equalsIgnoreCase(name));

            try {
                Long pid = Long.valueOf(Long.parseLong(columns[1].trim()));
                processes.add(pid);
            } catch (Throwable ex11) {
                ;
            }
        }
    } catch (Throwable ex12) {
        return processes;
    }
}

From source file:brut.util.OS.java

public static void exec(String[] cmd) throws BrutException {
    Process ps = null;
    try {//from ww w  .j a v a  2 s  . co m
        ps = Runtime.getRuntime().exec(cmd);

        new StreamForwarder(ps.getInputStream(), System.err).start();
        new StreamForwarder(ps.getErrorStream(), System.err).start();
        if (ps.waitFor() != 0) {
            throw new BrutException("could not exec command: " + Arrays.toString(cmd));
        }
    } catch (IOException ex) {
        throw new BrutException("could not exec command: " + Arrays.toString(cmd), ex);
    } catch (InterruptedException ex) {
        throw new BrutException("could not exec command: " + Arrays.toString(cmd), ex);
    }
}

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();

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

    StringBuilder sb = new StringBuilder();

    String line = reader.readLine();

    while (line != null) {
        sb.append(line);/*www  .  j  a  va2s .  c o  m*/

        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:de.bamamoto.mactools.png2icns.Scaler.java

protected static String runProcess(String[] commandLine) throws IOException {
    StringBuilder cl = new StringBuilder();
    for (String i : commandLine) {
        cl.append(i);/* w  w w .  j  ava2 s.co  m*/
        cl.append(" ");
    }

    String result = "";

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    Map<String, String> env = builder.environment();
    env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
    builder.redirectErrorStream(true);
    Process process = builder.start();

    String line;

    InputStream stdout = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }

    boolean isProcessRunning = true;
    int maxRetries = 60;

    do {
        try {
            isProcessRunning = process.exitValue() < 0;
        } catch (IllegalThreadStateException ex) {
            System.out.println("Process not terminated. Waiting ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException iex) {
                //nothing todo
            }
            maxRetries--;
        }
    } while (isProcessRunning && maxRetries > 0);
    System.out.println("Process has terminated");
    if (process.exitValue() != 0) {
        throw new IllegalStateException("Exit value not equal to 0: " + result);
    }
    if (maxRetries == 0 && isProcessRunning) {
        System.out.println("Process does not terminate. Try to kill the process now.");
        process.destroy();
    }

    return result;
}

From source file:Main.java

public static String getKernelVersion() {
    Process process = null;
    try {/*  ww w  .  j a  va2s.c  om*/
        process = Runtime.getRuntime().exec("cat /proc/version");
    } catch (IOException e) {
        e.printStackTrace();
    }
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr, 8 * 1024);
    String result = "";
    String line;
    try {
        while ((line = br.readLine()) != null) {
            result += line;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (result != "") {
        String keyword = "version ";
        int index = result.indexOf(keyword);
        line = result.substring(index + keyword.length());
        index = line.indexOf(" ");
        return line.substring(0, index);
    }
    return "Unknown";
}

From source file:com.flipkart.flux.examples.WorkflowExecutionDemo.java

/**
 * Helper method to execute a shell command
 * @param command shell command to run//  ww w  . j a v a2s.  c  om
 * @return shell command's output
 */
private static String executeCommand(String command) throws IOException, InterruptedException {

    StringBuilder output = new StringBuilder();

    Process p;

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

    //prints the output of the process
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line).append("\n");
    }

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

    //prints the error stream of the process
    String errorLine = "";
    while ((errorLine = stdError.readLine()) != null) {
        System.out.println(errorLine);
    }

    return output.toString();

}

From source file:net.orfjackal.retrolambda.test.Java5BytecodeTest.java

private static String javap(Class<?> aClass) throws IOException {
    Process process = new ProcessBuilder().directory(TestEnv.testClassesDir)
            .command("javap", "-v", "-p", aClass.getName()).redirectErrorStream(true).start();
    return CharStreams.toString(new InputStreamReader(process.getInputStream()));
}