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.github.genium_framework.appium.support.command.CommandManager.java

/**
 * Execute a command on the operating system using Java's built-in Process
 * class//from  www  .  j  av  a 2 s. co  m
 *
 * @param command A string array representation of the command to execute.
 * @param getOutput Whether or not to get the output/error streams of the
 * process you forked. This is helpful for debugging reasons.
 * @return A string representation of output/error streams of the process.
 */
public static String executeCommandUsingJavaRuntime(String[] command, boolean getOutput) {
    String output = "";

    try {
        Process p = Runtime.getRuntime().exec(command);

        // read the output from the command if requested by the user
        if (getOutput) {
            List<String> outErrStr = IOUtils.readLines(p.getInputStream());
            output = StringUtils.toString(outErrStr.toArray(new String[outErrStr.size()]), "\n");
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "An exception was thrown while executing the command (" + command + ")", ex);
    }

    return output;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.crfsuite.task.CRFSuiteTestTask.java

private static String captureProcessOutput(Process aProcess) {
    InputStream src = aProcess.getInputStream();
    Scanner sc = new Scanner(src);
    StringBuilder dest = new StringBuilder();
    while (sc.hasNextLine()) {
        String l = sc.nextLine();
        dest.append(l + "\n");
    }/*from  w w  w .j av  a 2 s. co m*/
    sc.close();
    return dest.toString();
}

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  .  java2 s. 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: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   www  .j  a va2  s  .  c om*/

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

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

    return procId;

}

From source file:localization.split.java

public static boolean checkLPU(String filepath, String passoloPath) {
    File logfile = new File(filepath.substring(0, filepath.lastIndexOf("\\") + 1) + "error.log");
    try {/*from   w  ww  .java2 s  . c o m*/
        String cmd = "cmd.exe /c " + passoloPath + " /openproject:" + filepath;
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd);
        InputStreamReader isr = new InputStreamReader(proc.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.contains("Opening in read-only mode")) {
                if (!logfile.exists()) {
                    logfile.createNewFile();
                }
                String content = filepath
                        + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2011."
                        + "\n";
                FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);
                bw.close();
                return false;
            }
        }
        int exitVal = proc.waitFor();
        if (exitVal == 10) {
            if (!logfile.exists()) {
                logfile.createNewFile();
            }
            String content = filepath
                    + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2015."
                    + "\n";
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            return false;
        }

    } catch (Exception e) {
        try {
            String content = e.getMessage();
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (Exception e1) {

        }

        return false;
    }
    return true;
}

From source file:abs.backend.erlang.ErlangBackend.java

public static void compile(Model m, File destDir, boolean verbose)
        throws IOException, InterruptedException, InternalBackendException {
    if (verbose)// ww w  . j  a v  a2s .c o  m
        System.out.println("Generating Erlang code...");

    // check erlang version number
    Process versionCheck = Runtime.getRuntime().exec(new String[] { "erl", "-eval",
            "io:fwrite(\"~s\n\", [erlang:system_info(otp_release)]), halt().", "-noshell" });
    versionCheck.waitFor();
    BufferedReader ir = new BufferedReader(new InputStreamReader(versionCheck.getInputStream()));
    int version = Integer.parseInt(ir.readLine());
    if (version < minVersion) {
        String message = "ABS requires at least erlang version " + Integer.toString(minVersion)
                + ", installed version is " + Integer.toString(version);
        throw new InternalBackendException(message);
    }
    ErlApp erlApp = new ErlApp(destDir);
    m.generateErlangCode(erlApp);
    erlApp.close();
    String[] rebarProgram = new String[] { "escript", "../bin/rebar", "compile" };
    Process p = Runtime.getRuntime().exec(rebarProgram, null, new File(destDir, "absmodel"));
    if (verbose)
        IOUtils.copy(p.getInputStream(), System.out);
    p.waitFor();
    if (p.exitValue() != 0) {
        String message = "Compilation of generated erlang code failed with exit value " + p.exitValue();
        if (!verbose)
            message = message + "\n  (use -v for detailed compiler output)";
        throw new InternalBackendException(message);
        // TODO: consider removing the generated code here.  For now,
        // let's leave it in place for diagnosis.
    } else {
        if (verbose) {
            System.out.println();
            System.out.println("Finished.  \"gen/erl/run\" to start the model.");
            System.out.println("          (\"gen/erl/run --help\" for more options)");
        }
    }
}

From source file:acoli.controller.Controller.java

private static BufferedReader getOutput(Process p) {
    return new BufferedReader(new InputStreamReader(p.getInputStream()));
}

From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java

private static void decompressUtil(Path archiveFilePath, Path workingDir, boolean stripParent)
        throws Exception {
    try {//from   w  w  w .ja va2  s.  c om
        MutableList<String> tarArgs = Lists.mutable.of(UNIX_TAR, "xvzf",
                archiveFilePath.toFile().getAbsolutePath());

        if (stripParent) {
            tarArgs = tarArgs.with("--strip").with("1");
        }
        Process process = new ProcessBuilder(tarArgs.toList()).directory(workingDir.toFile()).start();
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            logStdout(process.getInputStream());
            logStdErr(process.getErrorStream());
            throw new Exception("Failed to decompress");
        }
    } catch (Exception e) {
        throw new Exception("Failed to decompress", e);
    }
}

From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java

public static void compress(Path sourceDirectoryPath, Path archiveFilePath) throws Exception {
    try {//from   ww w. j a  va  2  s.  c  om
        ImmutableList<String> tarArgs = Lists.immutable.of(UNIX_TAR, "cvzf",
                archiveFilePath.toFile().getAbsolutePath(), ".");
        Process process = new ProcessBuilder(tarArgs.toList()).directory(sourceDirectoryPath.toFile()).start();
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            logStdout(process.getInputStream());
            logStdErr(process.getErrorStream());
            throw new Exception("Failed to compress");
        }
    } catch (Exception e) {
        throw new Exception("Failed to compress", e);
    }
}

From source file:ota.otaupdates.utils.Utils.java

/**
 * Credit goes to Matthew Booth (http://www.github.com/MatthewBooth) for this function
 * @param propName The prop to be checked
 * @return String The value of the prop/*w  w w.  ja  v  a 2  s.c  o  m*/
 */
public static String getProp(String propName) {
    Process p = null;
    String result = "";
    try {
        p = new ProcessBuilder("/system/bin/getprop", propName).redirectErrorStream(true).start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while ((line = br.readLine()) != null) {
            result = line;
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}