Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectErrorStream.

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;//from w  w  w  .j a v  a2s  . co  m
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:com.googlecode.flyway.commandline.largetest.CommandLineLargeTest.java

/**
 * Runs the Flyway Command Line tool./*  ww w  .j a  va 2  s.  c  o m*/
 *
 * @param expectedReturnCode The expected return code for this invocation.
 * @param configFileName     The config file name. {@code null} for default.
 * @param operation          The operation {@code null} for none.
 * @param extraArgs          The extra arguments to pass to the tool.
 * @return The standard output produced by the tool.
 * @throws Exception thrown when the invocation failed.
 */
private String runFlywayCommandLine(int expectedReturnCode, String configFileName, String operation,
        String... extraArgs) throws Exception {
    List<String> args = new ArrayList<String>();

    String installDir = System.getProperty("installDir");
    args.add(installDir + "/flyway." + flywayCmdLineExtensionForCurrentSystem());

    if (operation != null) {
        args.add(operation);
    }
    if (configFileName != null) {
        String configFile = new ClassPathResource("largeTest.properties").getFile().getPath();
        args.add("-configFile=" + configFile);
    }
    args.addAll(Arrays.asList(extraArgs));

    ProcessBuilder builder = new ProcessBuilder(args);
    builder.directory(new File(installDir));
    builder.redirectErrorStream(true);

    Process process = builder.start();
    String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8"));
    int returnCode = process.waitFor();

    System.out.print(stdOut);

    assertEquals("Unexpected return code", expectedReturnCode, returnCode);

    return stdOut;
}

From source file:ape.NetworkSlowCommand.java

/**
 * This method implements the event//from   www .  j a  v  a2 s.c om
 * @param time The amount of time to delay all network traffic in milliseconds
 * @param period How long the delay should last in seconds
 * @return True if successful execution, false if an error occurred
 * @throws IOException
 */
private boolean executecommand(double time, double period) throws IOException {
    String cmd = "tc qdisc add dev eth0 root netem delay " + time + "ms && sleep " + period
            + " && tc qdisc del dev eth0 root netem";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println(
                "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace");
        e.printStackTrace();
        return false;
    }

    try {
        int retVal = p.waitFor();
        System.out.println("The return value for '" + cmd + "' was " + retVal);
        if (retVal != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection Resumed");
                else {
                    System.out.println("Connection Resumed Failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;

        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            e.printStackTrace();
            return false;
        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.eclipse.smila.utils.scriptexecution.WindowsScriptExecutor.java

/**
 * Do execution of given command file.//www.  j av  a 2  s.  c o  m
 * 
 * @param file
 *          file
 * 
 * @return result code
 * 
 * @throws IOException
 *           IOException
 * @throws InterruptedException
 *           InterruptedException
 */
private int doExecute(final File file) throws IOException, InterruptedException {

    _log.debug("Do Execute " + file.getAbsolutePath());

    final ProcessBuilder processBuilder = new ProcessBuilder(file.getAbsolutePath());
    processBuilder.directory(file.getParentFile());
    processBuilder.redirectErrorStream(true);

    final Process process = processBuilder.start();

    final int resultCode = process.waitFor();

    LogHelper.debug(_log, process.getInputStream());

    return resultCode;
}

From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Elasticsearch server ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*from   w  w  w .j  a v a 2 s.com*/
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getElasticsearchStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0)
            logger.info("Elasticsearch server has been stopped");
        else {
            logger.error("Unable to stop Elasticsearch server. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Elasticsearch correctly", e);
    }
}

From source file:aiai.ai.core.ExecProcessService.java

public Result execCommand(List<String> cmd, File execDir, File consoleLogFile)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);/*from  w  w  w  .j  a  v  a 2 s  .c  om*/
    pb.directory(execDir);
    pb.redirectErrorStream(true);
    final Process process = pb.start();

    final StreamHolder streamHolder = new StreamHolder();
    int exitCode;
    try (final FileOutputStream fos = new FileOutputStream(consoleLogFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        final Thread reader = new Thread(() -> {
            try {
                streamHolder.is = process.getInputStream();
                int c;
                while ((c = streamHolder.is.read()) != -1) {
                    bos.write(c);
                }
            } catch (IOException e) {
                log.error("Error collect data from output stream", e);
            }
        });
        reader.start();

        exitCode = process.waitFor();
        reader.join();
    } finally {
        try {
            if (streamHolder.is != null) {
                streamHolder.is.close();
            }
        } catch (Throwable th) {
            log.warn("Error with closing InputStream", th);
        }
    }

    log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes"));
    log.debug("'\tcmd: {}", cmd);
    log.debug("'\texecDir: {}", execDir.getPath());
    String console = readLastLines(500, consoleLogFile);
    log.debug("'\tconsole output:\n{}", console);

    return new Result(exitCode == 0, exitCode, console);
}

From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java

public Document analyze(URL url) throws IOException, JDOMException, InterruptedException {
    InputStream in = null;/*from   w  w  w.  j a  va2  s.  c  om*/
    boolean threw = true;
    try {
        log.info("Starting analysis of [" + url.toExternalForm() + "]");

        List<String> command = constructCommand(url);

        logCommand(command);

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream();
        Process p = pb.start();
        // FIXME: we need to filter the InputStream as it seems we can get
        // content outside of the XML document (see sitespeed.io)
        in = p.getInputStream();
        byte[] result = IOUtils.toByteArray(in);

        log.info("Result of analysis:" + ArrayUtils.toString(result));

        Document doc = docBuilder.get().build(new ByteArrayInputStream(result));

        log.info(XmlPrettyPrinter.prettyPrint(doc));

        int status = p.waitFor();
        if (status != 0) {
            throw new RuntimeException("PhantomJS returned with status [" + status + "]");
        }
        threw = false;
        return doc;
    } finally {
        Closeables.close(in, threw);
    }
}

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Storage process ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*from  ww  w.  j  a  va 2s.c o m*/
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getStorageStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0) {
            logger.info("Storage process has been stopped");
            instanceState.setStorageProxyAlive(false);
        } else {
            logger.error("Unable to stop storage process. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Storage process correctly", e);
    }
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * /*from   w ww. ja  va2s.co m*/
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}

From source file:net.landora.video.mplayer.MPlayerParser.java

private MPlayerInfoParse mplayerIdentify(File f, Integer videoId, Integer audioId, Integer subtitleId)
        throws IOException, InterruptedException {
    //mplayer -frames 0 -msglevel identify=9 "$1" -vo null -ao null 2>/dev/null | grep "^ID"
    List<String> cmd = new ArrayList<String>();
    cmd.add(ProgramsAddon.getInstance().getConfiguredPath(CommonPrograms.MPLAYER));
    cmd.add("-frames");
    cmd.add("0");
    cmd.add("-msglevel");
    cmd.add("identify=9");
    cmd.add("-vo");
    cmd.add("null");
    cmd.add("-ao");
    cmd.add("null");

    if (videoId != null) {
        cmd.add("-vid");
        cmd.add(videoId.toString());/*from w  ww  .j a  v a 2  s . c o  m*/
    }

    if (audioId != null) {
        cmd.add("-aid");
        cmd.add(audioId.toString());
    }

    if (subtitleId != null) {
        cmd.add("-sid");
        cmd.add(subtitleId.toString());
    }

    cmd.add(f.getAbsolutePath());

    ProcessBuilder process = new ProcessBuilder(cmd);
    process.redirectErrorStream(true);
    Process p = process.start();

    StringWriter buffer = new StringWriter();
    IOUtils.copy(p.getInputStream(), buffer);
    p.waitFor();

    Matcher infoMatcher = dataPattern.matcher(buffer.toString());
    MPlayerInfoParse result = new MPlayerInfoParse();
    while (infoMatcher.find()) {
        result.add(infoMatcher.group(1), infoMatcher.group(2));
    }

    return result;
}