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:de.huberlin.wbi.hiway.am.HiWay.java

/**
 * If the debug flag is set, dump out contents of current working directory and the environment to stdout for debugging.
 *//*  w ww  .  j a  va  2 s .  c o m*/
private static void dumpOutDebugInfo() {
    System.out.println("Dump debug output");
    Map<String, String> envs = System.getenv();
    for (Map.Entry<String, String> env : envs.entrySet()) {
        System.out.println("System env: key=" + env.getKey() + ", val=" + env.getValue());
    }

    String cmd = "ls -al";
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = run.exec(cmd);
        pr.waitFor();

        try (BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
            String line = "";
            while ((line = buf.readLine()) != null) {
                System.out.println("System CWD content: " + line);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

/**
 * Get PDF information with pdfinfo:/*from  w  ww  . j a  v  a2 s  .co  m*/
 * - "Pages: X": number of pages;
 * - "Page X size: www.ww hhh.hh": size of each page, in pts.
 * @returns a map:
 * - [Pages][n]
 * - [Page 1][111.11 222.22]
 * - [Page i][www.ww hhh.hh]
 * - [Page n][999.99 1000.00]
 */
private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException {
    logger.debug("Getting PDF info");

    try {
        setPDFCommandsPath();
    } catch (IllegalStateException e) {
        logger.error("Failed to set PDF commands path: ", e);
        throw e;
    }

    HashMap<String, String> pdfProperties = new HashMap<String, String>();

    String sourcePath = null;

    if (input.getImageFile() != null) {
        logger.debug("PDFInfo image file: " + input.getImageFile());
        sourcePath = input.getImageFile();
    } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) {
        FileInputStream fis = null;
        fis = (FileInputStream) input.getObject();
        File in;

        // Copy to tmp file
        try {
            String cacheDir = OpenURLJP2KService.getCacheDir();
            if (cacheDir != null) {
                in = File.createTempFile("tmp", ".pdf", new File(cacheDir));
            } else {
                in = File.createTempFile("tmp", ".pdf");
            }
            in.deleteOnExit();

            FileOutputStream fos = new FileOutputStream(in);
            IOUtils.copyStream(fis, fos);
        } catch (IOException e) {
            logger.error(e, e);
            throw new DjatokaException(e);
        }
        sourcePath = in.getAbsolutePath();
    } else {
        throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName()
                + " is not supported");
    }

    String pdfinfoCmd[] = PDFINFO_COMMAND.clone();
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath;
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1";
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number.
    pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath;
    Process pdfProc = null;
    try {
        ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>();
        MatchResult pages = null;

        pdfProc = Runtime.getRuntime().exec(pdfinfoCmd);
        BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream()));
        String line;
        for (line = lr.readLine(); line != null; line = lr.readLine()) {
            Matcher mm1 = PAGES_PATT.matcher(line);
            if (mm1.matches())
                pages = mm1.toMatchResult();
            Matcher mm2 = MEDIABOX_PATT.matcher(line);
            if (mm2.matches())
                pageSizes.add(mm2.toMatchResult());
        }

        int istatus = pdfProc.waitFor();
        if (istatus != 0)
            logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath);

        if (pages == null) {
            logger.error("Did not find 'Pages' line in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            pdfProperties.put("Pages", "0");
        } else {
            //int n = Integer.parseInteger(pages.group(1));
            pdfProperties.put("Pages", pages.group(1));
        }

        if (pageSizes.isEmpty()) {
            logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: "
                    + Arrays.deepToString(pdfinfoCmd));
            throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo.");
        } else {
            for (MatchResult mr : pageSizes) {
                String page = mr.group(1);

                float x0 = Float.parseFloat(mr.group(2));
                float y0 = Float.parseFloat(mr.group(3));
                float x1 = Float.parseFloat(mr.group(4));
                float y1 = Float.parseFloat(mr.group(5));
                float w = Math.abs(x1 - x0);
                float h = Math.abs(y1 - y0);
                // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level).
                float ws = w * MAX_DPI / DEFAULT_DENSITY;
                float hs = h * MAX_DPI / DEFAULT_DENSITY;
                String width = "" + ws; //mr.group(2);
                String height = "" + hs; //mr.group(3);
                pdfProperties.put("Page " + page, width + " " + height);
            }
        }

    } catch (Exception e) {
        logger.error("Failed getting PDF information: ", e);
        throw new DjatokaException("Failed getting PDF information: ", e);
    } finally {
        // Our exec() should just consume one of the streams, but we want to stay safe.
        // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream());
        org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream());
    }

    return pdfProperties;
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Retrieves the global hadoop classpath.
 *
 * @param params/*w  w  w  .  j  a  va 2  s  . c om*/
 * @return hadoop global classpath
 */
public static String getHadoopClasspathGlob(String... params) {
    ProcessBuilder pb = new ProcessBuilder(params);
    try {
        Process process = pb.start();
        int errCode = process.waitFor();
        if (errCode != 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        //Now we must remove the yarn shuffle library as it creates issues for 
        //Zeppelin Spark Interpreter
        StringBuilder classpath = new StringBuilder();

        for (String path : sb.toString().split(File.pathSeparator)) {
            if (!path.contains("yarn") && !path.contains("jersey") && !path.contains("servlet")) {
                classpath.append(path).append(File.pathSeparator);
            }
        }
        if (classpath.length() > 0) {
            return classpath.toString().substring(0, classpath.length() - 1);
        }

    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(HopsUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:configuration.Cluster.java

public static String[] call_Python_Process(String script, String commands)
        throws IOException, InterruptedException {
    //System.out.println("Commands>"+commands);
    String STDoutput = "";
    String STDError = "";

    Process p = Runtime.getRuntime().exec("python " + script + " " + commands);
    BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    String line = "";

    // Check Output
    while ((line = bri.readLine()) != null) {
        STDoutput += line;/*from   w  ww.j av  a2 s .c  o  m*/
    }
    bri.close();
    while ((line = bre.readLine()) != null) {
        STDError += line;
    }
    bre.close();
    p.waitFor();

    String[] tab = { STDoutput, STDError };
    return tab;
}

From source file:Main.java

public void run() {
    try {/*from w  w w.ja  v a  2 s.  c  om*/
        Process child = Runtime.getRuntime().exec(executable);
        BufferedReader br = new BufferedReader(new InputStreamReader(child.getInputStream()));
        for (String s = br.readLine(); s != null; s = br.readLine()) {
            System.out.println("[" + prIndex + "] " + s);
            try {
                Thread.sleep(20);
            } catch (Exception intex) {
            }
        }
        br.close();
    } catch (Exception ioex) {
        System.err.println("IOException for process #" + prIndex + ": " + ioex.getMessage());
    }
}

From source file:com.github.born2snipe.project.setup.scm.GitRepoInitializer.java

private void executeCommandIn(File projectDir, String... commands) {
    try {/* w  w w . j a v a 2 s.  c  o m*/
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.directory(projectDir);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        System.out.println(IOUtils.toString(process.getInputStream()));
        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.samsung.sjs.Compiler.java

public static int manage_c_compiler(Process clang, CompilerOptions opts)
        throws IOException, InterruptedException {
    clang.waitFor();//from  www .  ja  v a  2  s  .  co  m
    if (clang.exitValue() != 0 && !opts.debug()) {
        // If clang failed and we didn't already dump its stderr
        StringWriter w_stdout = new StringWriter(), w_stderr = new StringWriter();
        IOUtils.copy(clang.getInputStream(), w_stdout, Charset.defaultCharset());
        IOUtils.copy(clang.getErrorStream(), w_stderr, Charset.defaultCharset());
        String compstdout = w_stdout.toString();
        String compstderr = w_stderr.toString();
        System.err.println("C compiler [" + opts.clangPath() + "] failed.");
        System.out.println("C compiler stdout:");
        System.out.println(compstdout);
        System.err.println("C compiler stderr:");
        System.err.println(compstderr);
    }
    return clang.exitValue();
}

From source file:de.christian_klisch.software.servercheck.GeneralTest.java

@Test
public void testCommandline() {
    System.out.println(CommandView.class.toString());
    try {/*from ww  w  . j a  v  a 2 s . co  m*/
        Process p = Runtime.getRuntime().exec("echo 0");
        System.out.println(IOUtils.toString(p.getInputStream(), "UTF-8"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertTrue(true);
}

From source file:iotest.WriteToFileTest.java

@Test
@Ignore// www .ja  v a2 s  .  c o  m
public void printWorkingDIR() throws IOException {

    String[] cmd = { "/bin/bash", "-c", "cd /media/sf_FBDC_PROD; ls -l" };
    Process p = Runtime.getRuntime().exec(cmd);

    String output = IOUtils.toString(p.getInputStream());

    System.out.println(">>>>>>>>>>>" + output);
}

From source file:io.galeb.router.handlers.InfoHandler.java

private String getUptimeSO() {
    ProcessBuilder processBuilder = new ProcessBuilder("uptime");
    processBuilder.redirectErrorStream(true);
    try {/*from   w  w  w.ja  v a 2 s .c om*/
        Process process = processBuilder.start();
        return IOUtils.toString(process.getInputStream(), "UTF-8").replace("\n", "");
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        return "";
    }
}