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:mitm.common.tools.OpenSSLWrapperTest.java

@Test(timeout = 5000)
public void testVerify() throws Exception {
    System.out.println("Starting testVerify");

    OpenSSLWrapper wrapper = new OpenSSLWrapper();

    File signedFile = new File(testDir, "clear-signed-validcertificate.eml");

    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("root");

    wrapper.setCertificateAuthorities(certificate);

    Process p = wrapper.verify(signedFile);

    InputStream result = p.getInputStream();

    String error = IOUtils.toString(p.getErrorStream(), "US-ASCII");

    System.out.println(error);//www  .ja  v a2  s  .c om

    assertTrue(error.startsWith("Verification successful"));

    File outputFile = new File(tempDir, "openssltestverify.eml");

    FileOutputStream outputStream = new FileOutputStream(outputFile);

    IOUtils.copy(result, outputStream);

    outputStream.close();
}

From source file:uk.ac.ebi.eva.pipeline.jobs.steps.VepAnnotationGeneratorStep.java

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    ObjectMap pipelineOptions = jobOptions.getPipelineOptions();

    ProcessBuilder processBuilder = new ProcessBuilder("perl", pipelineOptions.getString("app.vep.path"),
            "--cache", "--cache_version", pipelineOptions.getString("app.vep.cache.version"), "-dir",
            pipelineOptions.getString("app.vep.cache.path"), "--species",
            pipelineOptions.getString("app.vep.cache.species"), "--fasta",
            pipelineOptions.getString("input.fasta"), "--fork", pipelineOptions.getString("app.vep.num-forks"),
            "-i", pipelineOptions.getString("vep.input"), "-o", "STDOUT", "--force_overwrite", "--offline",
            "--everything");

    logger.debug("VEP annotation parameters = " + Arrays.toString(processBuilder.command().toArray()));

    logger.info("Starting read from VEP output");
    Process process = processBuilder.start();

    long written = connectStreams(new BufferedInputStream(process.getInputStream()),
            new GZIPOutputStream(new FileOutputStream(pipelineOptions.getString("vep.output"))));

    int exitValue = process.waitFor();
    logger.info("Finishing read from VEP output, bytes written: " + written);

    if (exitValue > 0) {
        String errorLog = pipelineOptions.getString("vep.output") + ".errors.txt";
        connectStreams(new BufferedInputStream(process.getErrorStream()), new FileOutputStream(errorLog));
        throw new Exception("Error while running VEP (exit status " + exitValue + "). See " + errorLog
                + " for the errors description from VEP.");
    }/*  w ww  . ja va2s. co m*/

    return RepeatStatus.FINISHED;
}

From source file:fm.last.irccat.Scripter.java

public void run() {
    try {/* ww  w.j  a  v  a 2  s  .  c  om*/
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime
                .exec(new String[] { bot.getCmdScript(), nick + " " + channel + " " + returnName + " " + cmd });
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line;
        int i = 0;
        while ((line = br.readLine()) != null) {
            bot.sendMsg(returnName, line);
            if (++i == bot.getCmdMaxResponseLines()) {
                bot.sendMsg(returnName, "<truncated, too many lines>");
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.anosym.webcmd.web.SSHTerminalController.java

@SuppressWarnings({ "UseSpecificCatch", "BroadCatchBlock", "TooBroadCatch" })
public void handleCommand() {
    try {//from   ww  w . jav a2 s .c  o  m
        String command = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
                .get("ssh-terminal-command");
        String cmd[] = command.trim().split(" ");
        System.out.println("Command: " + Arrays.toString(cmd));
        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        InputStream inn = p.getInputStream();
        int count = inn.available();
        byte[] buffer = new byte[count];
        //wait for the input to be available.
        inn.read(buffer);
        //            String result = new String(buffer);
        //            SSHTerminalResponse response = new SSHTerminalResponse(result, SSHTerminalResponse.TerminalResponseType.COMPLETE);
        //            RequestContext rc = RequestContext.getCurrentInstance();
        //            rc.addCallbackParam("response", response);
        //            System.out.println("Response: " + result);
    } catch (Exception ex) {
        //            Logger.getLogger(SSHTerminalController.class.getName()).log(Level.SEVERE, null, ex);
        //            String result = ExceptionUtils.getFullStackTrace(ex);
        //            SSHTerminalResponse response = new SSHTerminalResponse(result, SSHTerminalResponse.TerminalResponseType.COMPLETE);
        //            RequestContext rc = RequestContext.getCurrentInstance();
        //            rc.addCallbackParam("response", response);
    }

}

From source file:com.tyndalehouse.step.tools.modules.ConvertXmlToOSISModule.java

private void outputErrors(final Process p, final String moduleName) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringBuilder content = new StringBuilder(256);
    String line;/*from ww  w  . j a v  a2s.co  m*/
    while ((line = in.readLine()) != null) {
        content.append(line);
        content.append("\r\n");
    }
    FileUtils.writeStringToFile(new File(BASE_ERRORS, moduleName + ".log"), content.toString());
    in.close();
}

From source file:es.tid.fiware.rss.service.CdrsManager.java

/**
 * Run process to save Cdr into database.
 * /*from   w ww  .  ja v  a2s.  c o m*/
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
public String runCdrToDB() throws IOException, InterruptedException {
    String cdrToDBScript = (String) rssProps.get("cdrToDBScript");
    logger.trace("cdrToDBScript: " + cdrToDBScript);
    File cdrToDBSH = new File(cdrToDBScript);
    logger.debug("Running script: " + cdrToDBSH.getCanonicalPath());
    Process p = runtime.exec("sh " + cdrToDBSH.getCanonicalPath());
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String aLine;
    String error = null;
    while ((aLine = br.readLine()) != null) {
        if (aLine.indexOf("ERROR") != -1 && error == null) {
            error = aLine;
            logger.error(aLine);
        } else {
            logger.debug(aLine);
        }
    }
    int exitVal = p.waitFor();
    br.close();
    logger.debug("Process exitValue: " + exitVal);
    return error;
}

From source file:com.betfair.cougar.test.socket.app.JarRunner.java

protected void start(File dir, String[] extraArgs, boolean waitUntilExit) throws Exception {
    dir.mkdirs();//from  w w w. ja  v a2  s. c  om
    runDir = dir;
    // java -jar <jarfile>
    String[] baseCmd = new String[] { System.getProperty("java.home") + "/bin/java", "-jar",
            jarFile.getAbsolutePath() };
    String[] cmd = new String[baseCmd.length + extraArgs.length];
    System.arraycopy(baseCmd, 0, cmd, 0, baseCmd.length);
    System.arraycopy(extraArgs, 0, cmd, baseCmd.length, extraArgs.length);

    System.out.print("Running: java -jar " + cmd[2].substring(cmd[2].lastIndexOf("/") + 1));
    for (int i = 3; i < cmd.length; i++) {
        System.out.print(" " + cmd[i]);
    }
    System.out.println();

    Process p = Runtime.getRuntime().exec(cmd, new String[0], dir);
    startOutputStreaming(dir, p.getInputStream(), "stdout");
    startOutputStreaming(dir, p.getErrorStream(), "stderr");
    if (waitUntilExit) {
        p.waitFor();
        outputs = getOutputs();
    } else {
        backgroundProcess = p;
    }
}

From source file:com.github.greengerong.NgProtractor.java

private void executeCommand(final String cmd, final String logAction) {
    final Log log = getLog();

    try {//  w  w  w  .j av a 2s  . com
        log.info(String.format("execute %s running: %s", logAction, cmd));
        final ProcessBuilder processBuilder = new ProcessBuilder(getCommandAccordingToOS(cmd));
        final Process process = processBuilder.start();
        final String runningInfo = IOUtil.toString(process.getInputStream());
        log.info(runningInfo);
    } catch (IOException e) {
        log.warn(String.format("execute %s running script error", logAction), e);
    }
}

From source file:com.tascape.qa.th.Utils.java

public static void waitForOutputLine(final Process process, String lineExpected, final long timeout)
        throws IOException {
    Thread t = new Thread() {
        @Override/*w ww . j  a  va  2 s  .  c  o  m*/
        public void run() {
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ex) {
                LOG.warn(ex.getMessage());
            } finally {
                if (process != null) {
                    process.destroy();
                }
            }
        }
    };
    t.setName(Thread.currentThread().getName() + "-" + t.hashCode());
    t.setDaemon(true);
    t.start();

    try (BufferedReader stdIn = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        for (String line = stdIn.readLine(); line != null;) {
            if (line.contains(lineExpected)) {
                break;
            }
            line = stdIn.readLine();
        }
    }
    t.interrupt();
}