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:org.kiji.bento.box.tools.UpgradeInstallTool.java

/**
 * Take all stdout/stderr from a running subprocess and print it to our stdout.
 *
 * @param proc the process to consume input from.
 * @throws IOException if there's an error reading from the stream.
 *//*from   w w w  .ja  va 2s  . c o  m*/
private static void printProcessOutput(Process proc) throws IOException {
    final BufferedReader inputReader = new BufferedReader(
            new InputStreamReader(proc.getInputStream(), "UTF-8"));
    try {
        while (true) {
            // Read and echo all stdout/stderr from the subprocess here.
            String line = inputReader.readLine();
            if (null == line) {
                break;
            }

            System.out.println(line.trim());
        }
    } finally {
        IOUtils.closeQuietly(inputReader);
    }
}

From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java

private static File findNodeInCurrentFileSystem() {
    Runtime rt = Runtime.getRuntime();
    String instancePath;/*from  w w  w . ja v a 2s . c om*/
    Process p = null;
    try {
        p = rt.exec(returnCommandThatSearchesForDefaultNode());
        p.waitFor();
        instancePath = getProcessOutput(p.getInputStream());
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (p != null)
            p.destroy();
    }

    File result;
    if (StringUtils.isBlank(instancePath)
            || !(result = new File(instancePath + File.separator + NODE_MODULES_FOLDER + APPIUM_NODE_MASK))
                    .exists())
        throw new InvalidServerInstanceException(
                "There is no installed nodes! Please install "
                        + " node via NPM (https://www.npmjs.com/package/appium#using-node-js) or download and "
                        + "install Appium app (http://appium.io/downloads.html)",
                new IOException("The installed appium node package has not been found."));

    return result;
}

From source file:Main.java

public static String executeCommand(String[] args) {
    String result = new String();
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    Process process = null;
    InputStream errIs = null;//  www. j a  v  a  2 s  . c  o  m
    InputStream inIs = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int read = -1;
        process = processBuilder.start();
        errIs = process.getErrorStream();
        while ((read = errIs.read()) != -1) {
            baos.write(read);
        }
        baos.write('\n');
        inIs = process.getInputStream();
        while ((read = inIs.read()) != -1) {
            baos.write(read);
        }
        byte[] data = baos.toByteArray();
        result = new String(data);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        try {
            if (errIs != null) {
                errIs.close();
            }
            if (inIs != null) {
                inIs.close();
            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        if (process != null) {
            process.destroy();
        }
    }
    return result;
}

From source file:com.sshtools.common.util.X11Util.java

public static X11Cookie getCookie(XDisplay xdisplay) {
    if (System.getProperty("os.name").startsWith("Windows"))
        return getRNDCookie();
    log.debug("Getting X11 cookie using xauth");
    try {/*from w w w.  j av a2  s  .  c  o m*/
        String host = xdisplay.getHost();
        String display = host + ":" + xdisplay.getDisplay();
        String cmd = "xauth list " + display + " 2>/dev/null";
        if (host == null || host.equals("localhost") || host.equals("unix")) {
            cmd = "xauth list :" + xdisplay.getDisplay() + " 2>/dev/null";
        }

        Process process = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            log.debug("Executing " + cmd);
            process = Runtime.getRuntime().exec(cmd);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in = process.getInputStream()));
            out = process.getOutputStream();
            String line = null;
            String cookie = null;
            while ((line = reader.readLine()) != null) {
                log.debug(line);
                StringTokenizer t = new StringTokenizer(line);
                try {
                    String fhost = t.nextToken();
                    String type = t.nextToken();
                    String value = t.nextToken();
                    if (cookie == null) {
                        cookie = value;
                        log.debug("Using cookie " + cookie);
                    }
                    return expand(type, cookie);
                } catch (Exception e) {
                    log.error("Unexpected response from xauth.", e);
                    log.warn("Trying random data.");
                    return getRNDCookie();
                }
            }
        } finally {
            IOUtil.closeStream(in);
            IOUtil.closeStream(out);
        }
        return getRNDCookie();
    } catch (Exception e) {
        log.warn("Had problem finding xauth data (" + e + ") trying random data.");
        return getRNDCookie();
    }
}

From source file:org.spring.data.gemfire.AbstractGemFireIntegrationTest.java

protected static ServerLauncher startGemFireServer(final long waitTimeout, final String cacheXmlPathname,
        final Properties gemfireProperties) throws IOException {
    String gemfireMemberName = gemfireProperties.getProperty(DistributionConfig.NAME_NAME);
    String serverId = DATE_FORMAT.format(Calendar.getInstance().getTime());

    gemfireMemberName = String.format("%1$s-%2$s",
            (StringUtils.hasText(gemfireMemberName) ? gemfireMemberName : ""), serverId);

    File serverWorkingDirectory = FileSystemUtils.createFile(gemfireMemberName.toLowerCase());

    Assert.isTrue(FileSystemUtils.createDirectory(serverWorkingDirectory),
            String.format("Failed to create working directory (%1$s) in which the GemFire Server will run!",
                    serverWorkingDirectory));

    ServerLauncher serverLauncher = buildServerLauncher(cacheXmlPathname, gemfireProperties, serverId,
            DEFAULT_SERVER_PORT, serverWorkingDirectory);

    List<String> serverCommandLine = buildServerCommandLine(serverLauncher);

    System.out.printf("Starting GemFire Server in (%1$s)...%n", serverWorkingDirectory);

    Process serverProcess = ProcessUtils.startProcess(
            serverCommandLine.toArray(new String[serverCommandLine.size()]), serverWorkingDirectory);

    readProcessStream(serverId, "ERROR", serverProcess.getErrorStream());
    readProcessStream(serverId, "OUT", serverProcess.getInputStream());
    waitOnServer(waitTimeout, serverProcess, serverWorkingDirectory);

    return serverLauncher;
}

From source file:javadepchecker.Main.java

/**
 * Get jar names from the Gentoo package and store in a collection
 *
 * @param pkg Gentoo package name//w  w w  . jav a  2 s  .c  om
 * @return a collection of jar names
 */
private static Collection<String> getPackageJars(String pkg) {
    ArrayList<String> jars = new ArrayList<>();
    try {
        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 != null/* package somehow missing*/ && !output.trim().isEmpty()) {
            jars.addAll(Arrays.asList(output.split(":")));
        }
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jars;
}

From source file:com.qq.tars.tools.SystemUtils.java

public static Pair<Integer, Pair<String, String>> exec(String command) {
    log.info("start to exec shell, command={}", command);

    try {/*from w w  w. j a  va2  s. co m*/
        Process process = Runtime.getRuntime().exec("/bin/sh");

        OutputStream os = process.getOutputStream();
        os.write(command.getBytes());
        os.close();

        final StringBuilder stdout = new StringBuilder(1024);
        final StringBuilder stderr = new StringBuilder(1024);
        final BufferedReader stdoutReader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(process.getErrorStream(), "GBK"));

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stdoutReader.readLine())) {
                    stdout.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stdout error", e);
            }
        }).start();

        new Thread(() -> {
            String line;
            try {
                while (null != (line = stderrReader.readLine())) {
                    stderr.append(line).append("\n");
                }
            } catch (IOException e) {
                log.error("read stderr error", e);
            }
        }).start();

        int ret = process.waitFor();

        stdoutReader.close();
        stderrReader.close();

        Pair<String, String> output = Pair.of(stdout.toString(), stderr.toString());
        return Pair.of(ret, output);
    } catch (Exception e) {
        return Pair.of(-1, Pair.of("", ExceptionUtils.getStackTrace(e)));
    }
}

From source file:FileUtil.java

/**
 *  Runs a simple command in given directory.
 *  The environment is inherited from the parent process (e.g. the
 *  one in which this Java VM runs)./*from w w  w  .j a  v a 2 s.com*/
 *
 *  @return Standard output from the command.
 *  @param  command The command to run
 *  @param  directory The working directory to run the command in
 *  @throws IOException If the command failed
 *  @throws InterruptedException If the command was halted
 */
public static String runSimpleCommand(String command, String directory)
        throws IOException, InterruptedException {
    StringBuffer result = new StringBuffer();

    System.out.println("Running simple command " + command + " in " + directory);

    Process process = Runtime.getRuntime().exec(command, null, new File(directory));

    BufferedReader stdout = null;
    BufferedReader stderr = null;

    try {
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
        stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String line;

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

        StringBuffer error = new StringBuffer();
        while ((line = stderr.readLine()) != null) {
            error.append(line + "\n");
        }

        if (error.length() > 0) {
            System.out.println("Command failed, error stream is: " + error);
        }

        process.waitFor();

    } finally {
        // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
        process.getInputStream().close();
        if (stdout != null)
            stdout.close();
        if (stderr != null)
            stderr.close();
    }

    return result.toString();
}

From source file:ExifUtils.ExifReadWrite.java

private static ArrayList<String> exifTool_builder(String[] parameters, File directory) {
    //        final String command[] = "exiftool " + parameters;
    ArrayList<String> lines = new ArrayList<>();
    try {//from   w  ww. j av a  2  s .  c  om
        ProcessBuilder processBuilder = new ProcessBuilder(parameters).directory(directory);
        Process p = processBuilder.start();
        final BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stdinReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stderrReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;
}

From source file:com.l2jfree.sql.L2DataSource.java

protected static final void writeBackup(String databaseName, Process run) {
    try {// w ww. jav a  2  s.c  o  m
        boolean success = false;

        InputStream in = null;
        try {
            in = run.getInputStream();

            success = writeBackup(databaseName, in);
        } catch (IOException e) {
            _log.warn("DatabaseBackupManager: Could not make backup:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        if (!success) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(run.getErrorStream()));

                for (String line; (line = br.readLine()) != null;)
                    _log.warn("DatabaseBackupManager: " + line);
            } catch (Exception e) {
                _log.warn("DatabaseBackupManager: Could not make backup:", e);
            } finally {
                IOUtils.closeQuietly(br);
            }
        }

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup:", e);
    }
}