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:com.taobao.adfs.util.Utilities.java

public static String runCommand(String command, Integer expectedExitCode, String extraPath, String libPath,
        boolean destory) throws IOException {
    BufferedReader stdOutputReader = null;
    StringBuilder output = new StringBuilder();
    Process process = runCommand(command, extraPath, libPath);
    ;//from  w  ww .  j  a  v  a  2 s . c  om
    try {
        stdOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = stdOutputReader.readLine()) != null) {
            output.append(line).append('\n');
        }
        if (output.length() > 0)
            output.deleteCharAt(output.length() - 1);
        if (expectedExitCode != null && process.waitFor() != expectedExitCode)
            throw new IOException(
                    "exit code=" + process.exitValue() + ", expected exit code=" + expectedExitCode);
    } catch (Throwable t) {
        destory = true;
        throw new IOException("fail to exceute " + command + ", output=" + output
                + (extraPath == null ? "" : ", extraPath=" + extraPath)
                + (libPath == null ? "" : ", libPath=" + libPath), t);
    } finally {
        if (stdOutputReader != null)
            stdOutputReader.close();
        process.getOutputStream().close();
        process.getInputStream().close();
        process.getErrorStream().close();
        if (destory)
            process.destroy();
    }
    return output.toString();
}

From source file:dk.clarin.tools.create.java

public boolean PDFhasNoFonts(File pdfFile) {
    String lastline = "";
    String lasterrline = "";
    try {//from w w  w.  j  a  va2s.  co  m
        String line;
        OutputStream stdin = null;
        InputStream stderr = null;
        InputStream stdout = null;

        String command = "/usr/bin/pdffonts " + pdfFile.getAbsolutePath();

        final Process process = Runtime.getRuntime().exec(command);
        stdin = process.getOutputStream();
        stderr = process.getErrorStream();
        stdout = process.getInputStream();
        stdin.close();

        // clean up if any output in stdout
        BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
        while ((line = brCleanUp.readLine()) != null) {
            lastline = line;
        }
        brCleanUp.close();

        // clean up if any output in stderr
        brCleanUp = new BufferedReader(new InputStreamReader(stderr));
        while ((line = brCleanUp.readLine()) != null) {
            lasterrline = line;
        }
        brCleanUp.close();
    } catch (Exception e) {
        logger.error("cannot analyse: " + pdfFile.getName() + ", error is: " + e.getMessage());
    }
    logger.debug("lasterrline [" + lasterrline + "] lastline [" + lastline + "]");
    return lasterrline.equals("") && (lastline.endsWith("---------"));
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Logs the output "dumpsys alarm" to the provided filename.
 *
 * Output contains list of scheduled alarms & historical alarm statistics since
 * device bootup.//from www .  j a v  a2 s  .  c  o m
 *
 * Note: On Froyo & older Android OS versions dumpsys output consists of absolute
 * times (in ms), but on later versions is relative in the format 1h1m20s32ms.
 *
 * Requires root permission.
 *
 * @param file Alarm log output filename
 */
private void getAlarmInfo(String file) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        String Command = "dumpsys alarm > " + mApp.getTcpDumpTraceFolderName() + file + "\n";
        os.writeBytes(Command);
        os.flush();
    } catch (IOException e) {
        Log.e(TAG, "exception in getAlarmInfo ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in getAlarmInfo closing output stream ", e);
        }
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Starts collecting kernel log/*w w w  .ja v a2  s. c  o m*/
 *
 * Requires root permission.
 *
 * @param file kernel log output filename
 */
private void startDmesg(String file) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        // Appending
        String Command = "cat /proc/kmsg >> " + mApp.getTcpDumpTraceFolderName() + file + "\n";
        os.writeBytes(Command);
        os.flush();
    } catch (IOException e) {
        Log.e(TAG, "exception in startDmesg ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in startDmesg closing output stream ", e);
        }
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

private void getBatteryInfo() {
    Process sh = null;
    DataOutputStream os = null;//from   w w w . ja va  2 s.  co  m
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        dumpsysTimestamp = System.currentTimeMillis();
        String Command = "dumpsys batteryinfo > " + mApp.getTcpDumpTraceFolderName() + outBatteryInfoFileName
                + "\n";
        os.writeBytes(Command);
        os.flush();
        Log.d(TAG, "getBatteryInfo timestamp " + dumpsysTimestamp);
        Runtime.getRuntime().exec("cat " + dumpsysTimestamp + " >> " + mApp.getTcpDumpTraceFolderName()
                + outBatteryInfoFileName + "\n");
    } catch (IOException e) {
        Log.e(TAG, "exception in getBatteryInfo ", e);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            Log.e(TAG, "exception in getBatteryInfo closing output stream ", e);
        }
    }
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args, File outputFile)
        throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);//from  w w w .java 2 s  .  c o  m
    pb.environment().put("BASEDIR", project.getBasedir().getAbsolutePath());
    final Process p;
    ByteArrayOutputStream stdoutBaos = null;
    ByteArrayOutputStream stderrBaos = null;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    if (outputFile == null) {
        stdoutBaos = new ByteArrayOutputStream();
        copyIO(p.getInputStream(), stdoutBaos);
    } else {
        try {
            copyIO(p.getInputStream(), new FileOutputStream(outputFile));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Failed to copy output to : " + outputFile.getAbsolutePath(), e);
        }
    }
    stderrBaos = new ByteArrayOutputStream();
    copyIO(p.getErrorStream(), stderrBaos);
    copyIO(System.in, p.getOutputStream());
    try {
        boolean error = false;
        if (p.waitFor() != 0) {
            error = true;
        }
        if (getLog().isDebugEnabled() && stdoutBaos != null) {
            getLog().debug(stdoutBaos.toString());
        }
        if (getLog().isErrorEnabled() && stderrBaos != null) {
            getLog().error(stderrBaos.toString());
        }
        if (error) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:eu.interedition.collatex.tools.CollationServer.java

public void service(Request request, Response response) throws Exception {
    final Deque<String> path = path(request);
    if (path.isEmpty() || !"collate".equals(path.pop())) {
        response.sendError(404);/*from  w w  w.  java2s  .  c o m*/
        return;
    }

    final SimpleCollation collation = JsonProcessor.read(request.getInputStream());
    if (maxCollationSize > 0) {
        for (SimpleWitness witness : collation.getWitnesses()) {
            final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken)
                    .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum();
            if (witnessLength > maxCollationSize) {
                response.sendError(413, "Request Entity Too Large");
                return;
            }
        }
    }

    response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>());
    collationThreads.submit(() -> {
        try {
            final VariantGraph graph = new VariantGraph();
            collation.collate(graph);

            // CORS support
            response.setHeader("Access-Control-Allow-Origin",
                    Optional.ofNullable(request.getHeader("Origin")).orElse("*"));
            response.setHeader("Access-Control-Allow-Methods",
                    Optional.ofNullable(request.getHeader("Access-Control-Request-Method"))
                            .orElse("GET, POST, HEAD, OPTIONS"));
            response.setHeader("Access-Control-Allow-Headers",
                    Optional.ofNullable(request.getHeader("Access-Control-Request-Headers"))
                            .orElse("Content-Type, Accept, X-Requested-With"));
            response.setHeader("Access-Control-Max-Age", "86400");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse("");

            if (clientAccepts.contains("text/plain")) {
                response.setContentType("text/plain");
                response.setCharacterEncoding("utf-8");
                try (final Writer out = response.getWriter()) {
                    new SimpleVariantGraphSerializer(graph).toDot(out);
                }
                response.resume();

            } else if (clientAccepts.contains("application/tei+xml")) {
                XMLStreamWriter xml = null;
                try {
                    response.setContentType("application/tei+xml");
                    try (OutputStream responseStream = response.getOutputStream()) {
                        xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream);
                        xml.writeStartDocument();
                        new SimpleVariantGraphSerializer(graph).toTEI(xml);
                        xml.writeEndDocument();
                    } finally {
                        if (xml != null) {
                            xml.close();
                        }
                    }
                    response.resume();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            } else if (clientAccepts.contains("application/graphml+xml")) {
                XMLStreamWriter xml = null;
                try {
                    response.setContentType("application/graphml+xml");
                    try (OutputStream responseStream = response.getOutputStream()) {
                        xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream);
                        xml.writeStartDocument();
                        new SimpleVariantGraphSerializer(graph).toGraphML(xml);
                        xml.writeEndDocument();
                    } finally {
                        if (xml != null) {
                            xml.close();
                        }
                    }
                    response.resume();
                } catch (XMLStreamException e) {
                    e.printStackTrace();
                }
            } else if (clientAccepts.contains("image/svg+xml")) {
                if (dotPath == null) {
                    response.sendError(204);
                    response.resume();
                } else {
                    final StringWriter dot = new StringWriter();
                    new SimpleVariantGraphSerializer(graph).toDot(dot);

                    final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph",
                            "-Tsvg").start();
                    final StringWriter errors = new StringWriter();
                    CompletableFuture.allOf(CompletableFuture.runAsync(() -> {
                        final char[] buf = new char[8192];
                        try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) {
                            int len;
                            while ((len = errorStream.read(buf)) >= 0) {
                                errors.write(buf, 0, len);
                            }
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(),
                                "UTF-8")) {
                            dotProcStream.write(dot.toString());
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        response.setContentType("image/svg+xml");
                        final byte[] buf = new byte[8192];
                        try (final InputStream in = dotProc.getInputStream();
                                final OutputStream out = response.getOutputStream()) {
                            int len;
                            while ((len = in.read(buf)) >= 0) {
                                out.write(buf, 0, len);
                            }
                        } catch (IOException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads), CompletableFuture.runAsync(() -> {
                        try {
                            if (!dotProc.waitFor(60, TimeUnit.SECONDS)) {
                                throw new CompletionException(new RuntimeException(
                                        "dot processing took longer than 60 seconds, process was timed out."));
                            }
                            if (dotProc.exitValue() != 0) {
                                throw new CompletionException(new IllegalStateException(errors.toString()));
                            }
                        } catch (InterruptedException e) {
                            throw new CompletionException(e);
                        }
                    }, processThreads)).exceptionally(t -> {
                        t.printStackTrace();
                        return null;
                    }).thenRunAsync(response::resume, processThreads);
                }
            } else {
                response.setContentType("application/json");
                try (final OutputStream responseStream = response.getOutputStream()) {
                    JsonProcessor.write(graph, responseStream);
                }
                response.resume();
            }
        } catch (IOException e) {
            // FIXME: ignored
        }
    });
}

From source file:com.netease.qa.emmagee.service.EmmageeService.java

public void getlog() {

    new Thread(new Runnable() {
        @Override//ww  w .  j a  v a 2  s .c om
        public void run() {
            try {
                Process process = null;
                DataOutputStream os = null;
                String logcatCommand;
                if (packageName.contains("elong")) {
                    logcatCommand = "logcat -v time |grep --line-buffered -E \"GreenDaoHelper_insert_e|Displayed\" | grep -v -E \"show|logs|back|info\"";
                } else {
                    logcatCommand = "logcat -v time |grep --line-buffered -E \"Displayed\"";
                }

                Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
                os = new DataOutputStream(process.getOutputStream());
                os.write(logcatCommand.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
                bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                bufferedWriter = new BufferedWriter(new FileWriter(new File("/sdcard/logcat.log")));
                String line = null;
                while (!isServiceStop) {
                    while ((line = bufferedReader.readLine()) != null) {
                        bufferedWriter.write(line + Constants.LINE_END);
                    }
                    try {
                        Thread.currentThread().sleep(Settings.SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                os.close();
                bufferedWriter.flush();
                bufferedReader.close();
                process.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
    }).start();

}

From source file:org.openlaszlo.sc.SWF9External.java

/**
 * Run the compiler using the command/arguments in cmd.
 * Collect and report any errors, and check for the existence
 * of the output file./*from ww  w . j a  v a2  s.  com*/
 * @throw CompilerError if there are errors messages from the external
 *        compiler, or if any part of the compilation process has problems
 */
public void execCompileCommand(List cmd, String dir, List tunits, String outfileName) throws IOException // TODO: [2007-11-20 dda] clean up, why catch only some exceptions?
{
    String compilerClass = (String) cmd.remove(0);
    String[] cmdstr = (String[]) cmd.toArray(new String[0]);
    String prettycmd = prettyCommand(cmd);
    System.err.println("Executing compiler: (cd " + dir + "; " + prettycmd + ")");
    BigErrorString bigErrorString = new BigErrorString();

    // Generate a small script (unix style) to document how
    // to build this batch of files.
    String buildsh = isWindows() ? "rem build script\n" : "#!/bin/sh\n";
    buildsh += "cd \"" + dir + "\"\n";
    buildsh += prettycmd + "\n";
    String buildfn = isWindows() ? "build.bat" : "build.sh";
    Compiler.emitFile(workDirectoryName(buildfn), buildsh);

    if (options.getBoolean(Compiler.EMIT_AS3_ONLY)) {
        return;
    }

    List newenv = new ArrayList();
    newenv.add("FLEX_HOME=" + FLEX_HOME());
    copyEnvVar(newenv, "HOME");
    copyEnvVar(newenv, "PATH");
    copyEnvVar(newenv, "JAVA_HOME");
    Process proc = Runtime.getRuntime().exec(cmdstr, (String[]) newenv.toArray(new String[0]), null);
    try {
        OutputStream os = proc.getOutputStream();
        OutputCollector outcollect = new OutputCollector(proc.getInputStream());
        ExternalCompilerErrorCollector errcollect = new ExternalCompilerErrorCollector(proc.getErrorStream(),
                tunits);
        os.close();
        outcollect.start();
        errcollect.start();
        int exitval = proc.waitFor();
        outcollect.join();
        errcollect.join();

        if (outcollect.getException() != null) {
            System.err.println("Error collecting compiler output: " + outcollect.getException());
            // TODO: [2007-11-20 dda] log this
        }
        String compilerOutput = outcollect.getOutput();
        if (compilerOutput.length() > 0) {
            System.err.println("compiler output:\n" + compilerOutput);
        }

        if (errcollect.getException() != null) {
            System.err.println("Error collecting compiler output: " + errcollect.getException());
            // TODO: [2007-11-20 dda] log this
        }
        List severe = errcollect.getSevereErrors();
        if (severe.size() > 0) {
            for (Iterator iter = severe.iterator(); iter.hasNext();) {
                String errstr = "SEVERE ERROR: " + (String) iter.next();
                bigErrorString.add(errstr);
                System.err.println(errstr);
            }
        }
        List errs = errcollect.getErrors();
        if (errs.size() > 0) {
            System.err.println("ERRORS: ");
            for (Iterator iter = errs.iterator(); iter.hasNext();) {
                ExternalCompilerError err = (ExternalCompilerError) iter.next();
                TranslationUnit tunit = err.getTranslationUnit();
                String srcLineStr;
                TranslationUnit.SourceFileLine srcFileLine;

                // actualSrcLine is the name/linenumber of the actual files
                // used in compilation, not the original sources.
                String actualSrcFile = null;
                if (tunit == null) {
                    actualSrcFile = "(unknown)";
                } else {
                    actualSrcFile = tunit.getSourceFileName();
                    if (actualSrcFile == null)
                        actualSrcFile = "(" + tunit.getName() + ")";
                }

                String actualSrcLine = "[" + actualSrcFile + ": " + err.getLineNumber() + "] ";

                if (tunit == null) {
                    srcLineStr = "tunit/line unknown: ";
                } else if ((srcFileLine = tunit.originalLineNumber(err.getLineNumber())) == null) {
                    srcLineStr = "line unknown: ";
                } else {
                    srcLineStr = srcFileLine.sourcefile.name + ": " + srcFileLine.line + ": ";
                }
                System.err.println(actualSrcLine + srcLineStr + err.getErrorString());

                bigErrorString.add(srcLineStr + err.cleanedErrorString());
            }
        }

        if (exitval != 0) {
            System.err.println("FAIL: compiler returned " + exitval);
        }
    } catch (InterruptedException ie) {
        throw new CompilerError("Interrupted compiler");
    }
    System.err.println("Done executing compiler");
    if (!new File(outfileName).exists()) {
        System.err.println("Intermediate file " + outfileName + ": does not exist");
        if (bigErrorString.str.length() > 0) {
            throw new CompilerError(bigErrorString.str);
        } else {
            throw new CompilerError("Errors from compiler, output file not created");
        }
    }
}

From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java

public String createImage(String name, String path, String baseImage) {

    String format = null;/*from   w w  w .ja  v a 2 s. c om*/
    try {
        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> name(" + name + "), path(" + path + ") ");

        if (!existsImage(name)) {
            //If the image does not exist, create it

            if (path.trim().endsWith(".iso")) {
                format = "iso";

            } else if (name.contains(baseImage)) {
                // TODO: create the image, base image does not require volume
                String[] fileSplit = path.split("[.]");
                format = fileSplit[fileSplit.length - 1];
            } else {
                format = this.IMG_DEFAULT_DISK_FORMAT;
            }

            System.out.println(
                    "DRP4ONE-OneExtraFuncs.createImage()> crating image=" + name + " with format=" + format);

            // TODO: create the image at the OpenStack repository
            ArrayList<String> myCmd = new ArrayList<String>();
            myCmd.add("glance");
            myCmd.add("add");
            myCmd.add(String.format("id=%s", name));
            myCmd.add(String.format("name=%s", name));
            myCmd.add(String.format("disk_format=%s", format));
            myCmd.add(String.format("container_format=%s", this.IMG_DEFAULT_CONTAINER_FORMAT));
            myCmd.add(String.format("is_public=%s", this.IMG_DEFAULT_IS_PUBLIC));

            ProcessBuilder pb = new ProcessBuilder(myCmd);
            pb.redirectErrorStream(true);

            // Set up the environment to communicate with OpenStack
            Map<String, String> envir = pb.environment();
            envir.put("OS_AUTH_URL", this.OS_AUTH_URL);
            envir.put("OS_TENANT_ID", this.OS_TENANT_ID);
            envir.put("OS_TENANT_NAME", this.OS_TENANT_NAME);
            envir.put("OS_USERNAME", this.OS_USERNAME);
            envir.put("OS_PASSWORD", this.OS_PASSWORD);

            // Execute the command specified with its environment
            Process p = pb.start();

            OutputStream pos = p.getOutputStream();

            InputStream fis = new FileInputStream(new File(path));
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = fis.read(buffer)) != -1) {
                pos.write(buffer, 0, read);
            }
            // Close the file stream
            fis.close();
            // Close the process stream. If not, OpenStack keeps the image at "Saving" status
            pos.close();

            //TODO: verify error creating image

            //                if (or.isError()) {
            //                    //TODO: if error creating image...
            //                    System.out.println("DRP4ONE-OneExtraFuncs.createImage()> Error creating image: " + name);
            //
            //                } else {
            //                    //TODO: if ok creating image 
            //                    System.out.println("DRP4ONE-OneExtraFuncs.createImage()> OK creating image: " + name);
            //                    int imgID = Integer.parseInt(or.getMessage());
            //                    //TODO: not leave while image not ready to being used
            //                    while (i.stateString() != "READY") {
            //                        String tmpState = i.stateString();
            //                        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> STATE(imgID=" + imgID + "): " + tmpState);
            //                        Thread.sleep(3000);
            //                    }
            //                }
        } else {
            //If the image already exists, don't create it
            //TODO: return the identifier
            return name;
        }
    } catch (Exception e) {
        System.out.println("DRP4ONE-OneExtraFuncs.createImage()> name(" + name + "), path(" + path + ") ");
        e.printStackTrace();
    }

    return name;
}