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.liferay.blade.samples.integration.test.utils.BladeCLIUtil.java

public static String execute(File workingDir, String... bladeArgs) throws Exception {

    String bladeCLIJarPath = getLatestBladeCLIJar();

    List<String> command = new ArrayList<>();

    command.add("java");
    command.add("-jar");
    command.add(bladeCLIJarPath);/* ww w . j av  a 2s .  com*/

    for (String arg : bladeArgs) {
        command.add(arg);
    }

    Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start();

    process.waitFor();

    InputStream stream = process.getInputStream();

    String output = new String(IO.read(stream));

    InputStream errorStream = process.getErrorStream();

    List<String> errorList = new ArrayList<>();

    String stringStream = null;

    if (errorStream != null) {
        stringStream = new String(IO.read(errorStream));

        errorList.add(stringStream);
    }

    List<String> filteredErrorList = new ArrayList<>();

    for (String string : errorList) {
        String exclusion = "(.*setlocale.*)";

        Pattern p = Pattern.compile(exclusion, Pattern.DOTALL);

        Matcher m = p.matcher(string);

        while (m.find()) {
            filteredErrorList.add(string);
        }

        if (string.contains("Picked up JAVA_TOOL_OPTIONS:")) {
            filteredErrorList.add(string);
        }
    }

    errorList.removeAll(filteredErrorList);

    Assert.assertTrue(errorList.toString(), errorList.size() <= 1);

    if (errorList.size() == 1) {
        Assert.assertTrue(errorList.get(0), errorList.get(0).isEmpty());
    }

    return output;
}

From source file:com.moss.posixfifosockets.PosixFifoSocket.java

public static void createFifo(File path) throws IOException {
    if (path.exists()) {
        throw new IOException("File already exists: " + path.getAbsolutePath());
    }// ww w .  j av  a  2 s.  co  m
    if (!path.getParentFile().exists()) {
        throw new FileNotFoundException(path.getParent());
    }
    try {
        if (path.exists()) {
            throw new RuntimeException("Path really does exist: " + path.getAbsolutePath());
        }

        final Process p = Runtime.getRuntime().exec("mkfifo " + path.getAbsolutePath());
        int result = p.waitFor();
        if (result != 0) {

            String stdOut = read(p.getInputStream());
            String stdErr = read(p.getErrorStream());
            throw new IOException("Error creating fifo at " + path.getAbsolutePath() + ": Received error code "
                    + result + ", STDOUT: " + stdOut + ", STDERR: " + stdErr);
        } else if (!path.exists()) {
            throw new RuntimeException("mkfifo didn't do its job: " + path.getAbsolutePath());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.dart.tools.designer.model.HtmlRenderHelper.java

/**
 * @return the image of given HTML content, may be <code>null</code>.
 *///from  w  w  w .  j av a2  s .  co m
public static Image renderImage(final String content) {
    try {
        File tempFile = File.createTempFile("htmlRender", ".html");
        try {
            IOUtils2.writeBytes(tempFile, content.getBytes());
            // start DumpRenderTree
            if (processOutputStream == null) {
                String path;
                {
                    Bundle bundle = DartDesignerPlugin.getDefault().getBundle();
                    URL url = bundle.getEntry("lib/DumpRenderTree.app/Contents/MacOS/DumpRenderTree");
                    path = FileLocator.toFileURL(url).getPath();
                }
                //        ProcessBuilder builder = new ProcessBuilder(path, "-p", tempFile.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(path, "-p", "-");
                builder.redirectErrorStream(true);
                Process process = builder.start();
                processOutputStream = process.getOutputStream();
                processInputStream = process.getInputStream();
                processReader = new BufferedReader(new InputStreamReader(processInputStream));
            }
            long start = System.nanoTime();
            // XXX
            //        processOutputStream.write((tempFile.getAbsolutePath() + "\n").getBytes());
            processOutputStream
                    .write(("http://127.0.0.1:3030/Users/scheglov/dart/dwc_first/web/out/dwc_first.html\n")
                            .getBytes());
            processOutputStream.flush();
            // read tree
            while (true) {
                String line = processReader.readLine();
                System.out.println(line);
                if (line.isEmpty()) {
                    break;
                }
            }
            // read image
            {
                processReader.readLine(); // ActualHash:
                processReader.readLine(); // Content-Type: image/png
                String lengthLine = processReader.readLine(); // Content-Length: 5546
                int pngLength = Integer.parseInt(StringUtils.removeStart(lengthLine, "Content-Length: "));
                //          System.out.println("pngLength: " + pngLength);
                char[] pngChars = new char[pngLength];
                readFully(processReader, pngChars);
                byte[] pngBytes = new String(pngChars).getBytes();
                Image image = new Image(null, new ByteArrayInputStream(pngBytes));
                System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
                return image;
            }
            //
            //        {
            //          SessionInputBuffer buffer = new AbstractSessionInputBuffer() {
            //            {
            //              init(processInputStream, 1024, new BasicHttpParams());
            //            }
            //
            //            @Override
            //            public boolean isDataAvailable(int timeout) throws IOException {
            //              return false;
            //            }
            //          };
            //          LineParser lineParser = new BasicLineParser(new ProtocolVersion("HTTP", 1, 1));
            //          HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(
            //              buffer,
            //              lineParser,
            //              new DefaultHttpResponseFactory(),
            //              new BasicHttpParams());
            //          HttpResponse response = parser.parse();
            //          System.out.println(response);
            //          HttpParams params = new BasicHttpParams();
            //          SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
            //          HttpMessageParser<BasicHttpResponse> parser = new DefaultResponseParser(
            //              inbuffer,
            //              BasicLineParser.DEFAULT,
            //              new DefaultHttpResponseFactory(),
            //              params);
            //
            //          HttpResponse response = parser.parse();
            //        }
            //        while (true) {
            //          String line = processReader.readLine();
            //          System.out.println(line);
            //        }
            //
            //        byte[] bytes = IOUtils2.readBytes(processInputStream);
            //        int exitValue = process.exitValue();
            //        System.out.println("bytes: " + bytes.length);
            //        System.out.println("bytesTime: " + (System.nanoTime() - start) / 1000000.0);
            //        String output = new String(bytes);
            //        System.out.println(StringUtils.substring(output, -10, 0));
            ////        System.out.println(output);
            //        //
            //        int pngOffset = output.indexOf("Content-Type: image/png");
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        Image image = new Image(null, new ByteArrayInputStream(bytes, pngOffset, bytes.length
            //            - pngOffset));
            //        System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
            //        return image;
        } finally {
            tempFile.delete();
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static boolean symlink(File inFile, File outFile) {
    int exitCode = -1;
    try {//from w w w  .j ava2 s  .c  o  m
        Process sh = Runtime.getRuntime().exec("sh");
        OutputStream out = sh.getOutputStream();
        String command = "/system/bin/ln -s " + inFile + " " + outFile + "\nexit\n";
        out.write(command.getBytes("ASCII"));

        final char buf[] = new char[40];
        InputStreamReader reader = new InputStreamReader(sh.getInputStream());
        while (reader.read(buf) != -1)
            throw new IOException("stdout: " + new String(buf));
        reader = new InputStreamReader(sh.getErrorStream());
        while (reader.read(buf) != -1)
            throw new IOException("stderr: " + new String(buf));

        exitCode = sh.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    }
    return exitCode == 0;
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait//from w  w  w  . j  a va  2 s .  c  om
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuffer output = new StringBuffer();
        int lineCount = 0;
        while ((line = reader.readLine()) != null) {
            if (lineCount < 10) { // only get 10 lines to prevent the overflow
                output.append(line);
            }
            lineCount += 1;
            logger.debug(line);
        }
        if (lineCount >= 10) {
            logger.debug("... there are alot of more output here which is not shown ! ...");
        }
        p.waitFor();
        System.out.println("Execute Commang output: " + output.toString().trim());

        if (p.exitValue() == 0) {
            logger.debug("Command exit 0, result: " + output.toString().trim());
            return output.toString().trim();
        } else {
            logger.debug("Command return non zero code: " + p.exitValue());
            return null;
        }
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return null;
}

From source file:edu.mit.genecircuits.GcUtils.java

static public void exec(String command) {

    try {//from  ww w.  j  av a  2  s.  co  m

        // Execute command
        System.out.println(command);
        Process p;
        p = Runtime.getRuntime().exec(command);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

        // read the output from the command
        String s;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }

    } catch (IOException e) {
        GcMain.error(e);
    }

}

From source file:javadepchecker.Main.java

private static Collection<String> getPackageJars(String pkg) {
    ArrayList<String> jars = new ArrayList<String>();
    try {//  w w w  . j  ava 2s  . c o  m
        Process p = Runtime.getRuntime().exec("java-config -p " + pkg);
        p.waitFor();
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String output = in.readLine();
        if (!output.trim().equals("")) {
            for (String jar : output.split(":")) {
                jars.add(jar);
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jars;
}

From source file:Main.java

public static int findProcessIdWithPidOf(String command) throws Exception {
    int procId = -1;
    Runtime r = Runtime.getRuntime();
    Process procPs = null;

    String baseName = new File(command).getName();
    // fix contributed my mikos on 2010.12.10
    procPs = r.exec(new String[] { SHELL_CMD_PIDOF, baseName });
    // procPs = r.exec(SHELL_CMD_PIDOF);

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;//from   w  w w.ja  v  a2 s .  c o m

    while ((line = reader.readLine()) != null) {

        try {
            // this line should just be the process id
            procId = Integer.parseInt(line.trim());
            break;
        } catch (NumberFormatException e) {
            Log.e("TorServiceUtils", "unable to parse process pid: " + line, e);
        }
    }

    return procId;

}

From source file:edu.ku.brc.af.ui.ProcessListUtil.java

/**
 * @return/*from   ww  w  .j a v a 2  s .  c om*/
 */
public static List<List<String>> getRunningProcessesWin() {

    List<List<String>> processList = new ArrayList<List<String>>();
    try {
        boolean doDebug = true;
        Process process = Runtime.getRuntime().exec("tasklist.exe /v /nh /FO CSV");
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            if (!line.trim().isEmpty()) {
                if (doDebug && StringUtils.contains(line, "mysql")) {
                    String lineStr = StringUtils.replaceChars(line, '\\', '/');
                    System.out.println("\n[" + lineStr + "]");
                    for (String tok : parse(lineStr)) {
                        System.out.print("[" + tok + "]");
                    }
                    System.out.println();

                }
                processList.add(parse(StringUtils.replaceChars(line, '\\', '/')));
            }
        }
        input.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return processList;
}

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;
    DataOutputStream out = null;/*  w  ww . j  a v a2 s  .c o  m*/
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
        shell = Runtime.getRuntime().exec(startCommand);
        out = new DataOutputStream(shell.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
        for (String command : commands) {
            out.writeBytes(command + "\n");
            out.flush();
        }
        out.writeBytes("exit\n");
        out.flush();
        shell.waitFor();
    } catch (Exception e) {
        Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {

        }
    }
    return reader;
}