Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

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

Usage

From source file:Main.java

public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;
    DataOutputStream out = null;/*  w  ww.  j  a v  a 2s  . com*/
    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;
}

From source file:edu.stanford.epad.common.dicom.DCM4CHEEUtil.java

public static void dcmsnd(String inputPathFile, boolean throwException) throws Exception {
    InputStream is = null;/*from  w  w w.  j a v a  2s .  c  o  m*/
    InputStreamReader isr = null;
    BufferedReader br = null;

    try {
        String dcmServerTitlePort = aeTitle + "@localhost:" + dicomServerPort;
        dcmServerTitlePort = dcmServerTitlePort.trim();
        log.info("Sending file - command: ./dcmsnd " + dcmServerTitlePort + " " + inputPathFile);
        String[] command = { "./dcmsnd", dcmServerTitlePort, inputPathFile };
        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomBinDirectoryPath = EPADConfig.getEPADWebServerDICOMBinDir();
        log.info("DICOM binary directory: " + dicomBinDirectoryPath);
        pb.directory(new File(dicomBinDirectoryPath));
        Process process = pb.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmsend output: " + line);
        }

        try {
            int exitValue = process.waitFor();
            log.info("dcmsnd exit value is: " + exitValue);
            if (sb.toString().contains("Sent 0 objects")) {
                log.warning("Zero objects sent to dcm4che, some error has occurred");
                throw new Exception("Error sending files to dcm4che");
            }

        } catch (InterruptedException e) {
            log.warning("Error sending DICOM files in: " + inputPathFile, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + cmdLineOutput);
        }
    } catch (Exception e) {
        if (e instanceof IllegalStateException && throwException) {
            throw e;
        }
        log.warning("dcmsnd failed: " + e.getMessage());
        if (throwException) {
            throw new IllegalStateException("dcmsnd failed", e);
        }
    } catch (OutOfMemoryError oome) {
        log.warning("dcmsnd ran out of memory", oome);
        if (throwException) {
            throw new IllegalStateException("dcmsnd ran out of memory", oome);
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
    }
}

From source file:org.janusgraph.pkgtest.AbstractJanusGraphAssemblyIT.java

protected static void command(File dir, String... command) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.directory(dir);/*  w w  w . j av  a2  s . co m*/
    //        pb.redirectInput(Redirect.PIPE);
    /*
     * Using Redirect.INHERIT with expect breaks maven-failsafe-plugin when
     * failsafe is configured to fork. The parent and child normally
     * communicate over stdout/stderr in fork mode. But after executing
     * expect, this failsafe communication starts appearing on the terminal.
     * The parent never sees it and assumes no tests ran. expect is probably
     * doing something nasty to its file descriptors and neglecting to clean
     * up after itself. Invoking unzip does not break failsafe+forks in this
     * way. So expect must be doing something unusual with its file
     * descriptors.
     *
     * Redirect.INHERIT works fine if failsafe is configured to never fork.
     */
    //        pb.redirectOutput(Redirect.INHERIT);
    //        pb.redirectError(Redirect.INHERIT);
    //        pb.redirectOutput(Redirect.PIPE);
    //        pb.redirectError(Redirect.PIPE);
    final Process p = pb.start();
    // Sense of "input" and "output" are reversed between ProcessBuilder and Process
    p.getOutputStream().close(); // Child process sees EOF on stdin (if it reads stdin at all)
    Thread outPrinter = new Thread(new SubprocessPipePrinter(p.getInputStream(), System.out));
    Thread errPrinter = new Thread(new SubprocessPipePrinter(p.getErrorStream(), System.out));
    outPrinter.start();
    errPrinter.start();
    int stat = p.waitFor();
    outPrinter.join();
    errPrinter.join();
    assertEquals(0, stat);
}

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  www.  j  a 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:com.github.horrorho.inflatabledonkey.util.LZFSEExtInputStream.java

public static LZFSEExtInputStream create(Path cmd, InputStream is) throws IOException {
    Process process = Runtime.getRuntime().exec(cmd + " -decode");
    LZFSEExtInputStream instance = new LZFSEExtInputStream(process, null);
    Thread thread = new Thread(() -> pipe(is, process.getOutputStream(), instance::error));
    thread.start();/*from ww w  .j  a  v a  2 s. co m*/
    return instance;
}

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

/**
 * @return the image of given HTML content, may be <code>null</code>.
 *//*from  ww w .j  a  v a 2s  . c  om*/
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:org.sonar.api.utils.command.CommandExecutor.java

private static void closeStreams(@Nullable Process process) {
    if (process != null) {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }/*from w  ww.j av  a  2 s  .co  m*/
}

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 {/*  w w w. ja  va2s  .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  ww w  .ja  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++) {
        // TorService.logMessage("executing shell cmd: " + cmds[i] +
        // "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

        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 String RunExecCmd(StringBuilder sb, Boolean su) {

    String shell;//  www .  ja v a 2 s  .  c  o m
    if (su) {
        shell = "su";
    } else {
        shell = "sh";
    }

    Process process = null;

    DataOutputStream processOutput = null;
    InputStream processInput = null;
    String outmsg = new String();

    try {

        process = Runtime.getRuntime().exec(shell);
        processOutput = new DataOutputStream(process.getOutputStream());
        processOutput.writeBytes(sb.toString() + "\n");
        processOutput.writeBytes("exit\n");
        processOutput.flush();
        processInput = process.getInputStream();
        outmsg = inputStream2String(processInput, "UTF-8");
        process.waitFor();

    } catch (Exception e) {
        //Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
        //return;
    }

    finally {
        try {
            if (processOutput != null) {
                processOutput.close();
            }
            process.destroy();
        } catch (Exception e) {
        }

    }
    return outmsg;
}