Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

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

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

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

Usage

From source file:ch.puzzle.itc.mobiliar.business.shakedown.control.ShakedownTestRunner.java

private List<String> copySTMtoRemoteServerAndGetMissingSTPs(String bundle, STS sts)
        throws ShakedownTestException {
    List<String> result = new ArrayList<String>();
    Runtime r = Runtime.getRuntime();
    File f = new File(bundle);
    if (!f.exists()) {
        throw new ShakedownTestException("The STM bundle file " + f.getAbsolutePath() + " does not exist!");
    }//from w  ww  .  j  av a2s. co  m
    // Create folder if it does not yet exist
    String createRemoteSTMFolderIfNotExists = "ssh " + sts.getUser() + "@" + sts.getRemoteHost() + " mkdir -p "
            + sts.getRemoteSTPPath() + File.separator + "stms";
    log.info("EXECUTE: " + createRemoteSTMFolderIfNotExists);
    try {
        Process createRemoteSTMFolder = r.exec(createRemoteSTMFolderIfNotExists);
        if (createRemoteSTMFolder.waitFor() != 0) {
            throw new ShakedownTestException("Was not able to create STM folder on remote site: "
                    + sts.getRemoteHost() + File.separator + "stms with user " + sts.getUser());
        }
        String copySTMcommand = "scp " + bundle + " " + sts.getUser() + "@" + sts.getRemoteHost() + ":"
                + sts.getRemoteSTPPath() + File.separator + "stms" + File.separator + f.getName();
        log.info("EXECUTE: " + copySTMcommand);
        Process p = r.exec(copySTMcommand);
        if (p.waitFor() == 0) {
            log.info("Copied STM bundle " + bundle + " to host " + sts.getRemoteHost());
            String launchDepMgmtCommand = "ssh " + sts.getUser() + "@" + sts.getRemoteHost() + " java -jar "
                    + sts.getRemoteSTPPath() + File.separator + "stms" + File.separator + f.getName() + " "
                    + sts.getRemoteSTPPath() + " dependencyManagement";
            log.info("EXECUTE: " + launchDepMgmtCommand);
            Process dependencyMgmt = r.exec(launchDepMgmtCommand);
            BufferedReader bufferedreader = null;
            try {
                bufferedreader = new BufferedReader(
                        new InputStreamReader(new BufferedInputStream(dependencyMgmt.getErrorStream())));
                String errorline;
                while ((errorline = bufferedreader.readLine()) != null) {
                    if (errorline.startsWith("@{") && errorline.trim().endsWith("}")) {
                        result.add(errorline.trim().substring(2, errorline.trim().length() - 1));
                    }
                }
            } finally {
                if (bufferedreader != null) {
                    bufferedreader.close();
                }
            }
        } else {
            throw new ShakedownTestException("Was not able to copy STP " + bundle + " to host "
                    + sts.getRemoteHost() + " with ssh user " + sts.getUser());
        }
    } catch (IOException e) {
        throw new ShakedownTestException("Was not able to copy STM to remote server ", e);
    } catch (InterruptedException e) {
        throw new ShakedownTestException("Was not able to copy STM to remote server ", e);
    }
    return result;
}

From source file:com.isecpartners.gizmo.FourthIdea.java

private String readError(Process proc) {
    return readStream(proc, proc.getErrorStream());
}

From source file:com.eucalyptus.storage.ISCSIManager.java

/**
 * Executes the specified command in a separate process. A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on the process using
 * {@link java.util.concurrent.ExecutorService ExecutorService} framework. If the process does not complete with in the timeout, it is cancelled.
 * //from   ww w.ja v  a2 s.com
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private CommandOutput execute(String[] command, Long timeout) throws EucalyptusCloudException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = service.submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new EucalyptusCloudException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("ISCSIManager executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (Exception ex) {
        if (ex instanceof EucalyptusCloudException) {
            throw (EucalyptusCloudException) ex;
        } else {
            throw new EucalyptusCloudException(ex);
        }
    }
}

From source file:eu.smartenit.unada.tpm.TopologyProximityMonitorImpl.java

/**
 * OS-independent traceroute executor to specified address.
 *
 * @param address destination host./*from   w  ww  .jav a  2s . com*/
 * @return Traceroute output.
 * @throws IOException If an I/O error occurs
 * @throws InterruptedException if the current thread is
 * {@linkplain Thread#interrupt() interrupted} by another thread while it is
 * waiting, then the wait is ended and an {@link InterruptedException} is
 * thrown.
 */
public List<String> executeTraceroute(Inet4Address address) throws IOException, InterruptedException {
    logger.debug("Executing traceroute");
    String command;
    if (IS_WINDOWS) {
        command = String.format(WINDOWS_TRACEROUTE_COMMAND, address.getHostAddress());
    } else if (IS_LINUX) {
        command = String.format(LINUX_TRACEROUTE_COMMAND, address.getHostAddress());
    } else {
        throw new UnsupportedOperationException("OS is neither Windows nor Linux (os.name = \"" + OS + "\")");
    }
    Process proc = Runtime.getRuntime().exec(command, new String[] { "LC_ALL=C" });
    BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String line;
    String error = "";
    while ((line = stderr.readLine()) != null) {
        error = error + line + "\n";
    }
    if (!error.isEmpty()) {
        throw new RuntimeException("Error while executing \"" + command + "\": " + error);
    }

    proc.waitFor();

    List<String> result = new ArrayList<>();
    while ((line = stdout.readLine()) != null) {
        result.add(line);
    }
    logger.debug("Traceroute finished");
    return result;
}

From source file:com.googlecode.jmxtrans.model.output.RRDToolWriter.java

/**
 * Calls out to the rrdtool binary with the 'create' command.
 *///from  ww w  .  ja v  a2  s . c  o m
protected void rrdToolCreateDatabase(RrdDef def) throws Exception {
    List<String> commands = new ArrayList<>();
    commands.add(this.binaryPath + "/rrdtool");
    commands.add("create");
    commands.add(this.outputFile.getCanonicalPath());
    commands.add("-s");
    commands.add(String.valueOf(def.getStep()));

    for (DsDef dsdef : def.getDsDefs()) {
        commands.add(getDsDefStr(dsdef));
    }

    for (ArcDef adef : def.getArcDefs()) {
        commands.add(getRraStr(adef));
    }

    ProcessBuilder pb = new ProcessBuilder(commands);
    Process process = pb.start();
    try {
        checkErrorStream(process);
    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:net.sf.mavenjython.JythonMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args) throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);/*from w  w w  . j a v a  2 s  .c o m*/
    final Process p;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:com.photon.phresco.util.Utility.java

public static BufferedReader executeCommand(String commandString, String workingDirectory) {
    InputStream inputStream = null;
    InputStream errorStream = null;
    SequenceInputStream sequenceInputStream = null;
    BufferedReader bufferedReader = null;
    try {//from   w  ww . jav a  2 s  .  co  m
        Commandline cl = new Commandline(commandString);
        cl.setWorkingDirectory(workingDirectory);
        Process process = cl.execute();
        inputStream = process.getInputStream();
        errorStream = process.getErrorStream();
        sequenceInputStream = new SequenceInputStream(inputStream, errorStream);
        bufferedReader = new BufferedReader(new InputStreamReader(sequenceInputStream));
    } catch (CommandLineException e) {
        //FIXME : log exception
        e.printStackTrace();
    }

    return bufferedReader;
}

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.");
    }// ww w  .j  a va  2  s.com

    return RepeatStatus.FINISHED;
}

From source file:io.crate.frameworks.mesos.CrateExecutor.java

protected void redirectProcess(Process process) {
    StreamRedirect stdoutRedirect = new StreamRedirect(process.getInputStream(), System.out);
    stdoutRedirect.start();//  w  w  w  . j  a  v  a 2s  .co m
    StreamRedirect stderrRedirect = new StreamRedirect(process.getErrorStream(), System.err);
    stderrRedirect.start();
}

From source file:net.sourceforge.vulcan.maven.MavenBuildTool.java

@Override
protected void preparePipes(final Process process) throws IOException {
    process.getOutputStream().close();/* w  w w  . j av a 2s .c  o  m*/

    stdErrThread = new PipeThread("Maven stderr l [" + projectName + "]", process.getErrorStream(),
            stdErrStream);
    stdErrThread.start();

    if (logFile == null) {
        process.getInputStream().close();
        return;
    }

    final OutputStream logOutputStream = new FileOutputStream(logFile);

    logThread = new PipeThread("Maven Build Logger [" + projectName + "]", process.getInputStream(),
            logOutputStream);
    logThread.start();
}