Example usage for org.apache.commons.exec DefaultExecutor setStreamHandler

List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecutor setStreamHandler.

Prototype

public void setStreamHandler(final ExecuteStreamHandler streamHandler) 

Source Link

Usage

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffmpeg.java

@Override
public Object handle(Task aTask) throws Exception {
    List<String> options = aTask.getList("options", String.class);
    CommandLine cmd = new CommandLine("ffmpeg");
    options.forEach(o -> cmd.addArgument(o));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        int exitValue = exec.execute(cmd);
        return exitValue != 0 ? FileUtils.readFileToString(tempFile) : cmd.toString();
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {// ww  w  . j  ava  2s.c  om
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:it.unisi.bdm.crawler.PhantomjsBrowser.java

@Override
/**//from  w w w .j a v  a 2 s  .  c  o m
 * Invokes PhantomJS in order to download the page associated to `url`.
 * Please note that since the browser sometimes hangs, it's execution is
 * monitored by a wathdog that kills it after this.timeout ms.
 * 
 * @param url
 * @return Page
 * @throws BrowserTimeoutException If PhantomJS hangs.
 */
public Page getPage(String url) throws BrowserTimeoutException {
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);

    String line = "library/phantomjs library/crawler.js " + url;
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeout);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(psh);

    try {
        executor.execute(cmdLine);
    } catch (Exception e) {
        throw new BrowserTimeoutException();
    }

    String json = stdout.toString();
    return new Gson().fromJson(json, Page.class);
}

From source file:com.k42b3.sacmis.ExecutorAbstract.java

public void run() {
    try {/*w w w  .  j  a v a2 s  .c om*/
        // clear text
        this.textArea.setText("");

        CommandLine commandLine = CommandLine.parse(this.getExecutable() + " " + this.cmd);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setStreamHandler(new PumpStreamHandler(new TextAreaOutputStream(textArea)));
        executor.setWatchdog(watchdog);
        executor.execute(commandLine);
    } catch (FoundNoExecutableException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Information", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.stratio.explorer.shell.ShellInterpreter.java

@Override
public InterpreterResult interpret(String cmd) {
    logger.info("Run shell command '" + cmd + "'");
    long start = System.currentTimeMillis();
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(cmd, false);/*from w  w  w . j  av a  2 s .  c  o m*/
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    executor.setWatchdog(new ExecuteWatchdog(CMD_TIMEOUT));
    try {
        int exitValue = executor.execute(cmdLine);
        return new InterpreterResult(InterpreterResult.Code.SUCCESS, outputStream.toString());
    } catch (ExecuteException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    } catch (IOException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    }
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Mediainfo.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("mediainfo");
    cmd.addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);/*  w  w w  .ja v  a 2s.  c  o m*/
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:com.github.rwhogg.git_vcr.review.ProcessBasedReviewTool.java

/**
 * Runs the command string specified by commandLine, then returns the output.
 * Note that any command-line arguments from the configuration are automatically added.
 * @param commands The rest of the command line, excluding any arguments
 * @return The output of the command/*from   w  ww.j av a2s.c  om*/
 */
protected List<String> runProcess(String commands) throws ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValues(null);
    String arguments = configuration.getString("args", "");
    executor.execute(CommandLine.parse(getExecutableName() + " " + arguments + " " + commands));
    return Arrays.asList(outputStream.toString("UTF-8").split("\n"));
}

From source file:com.creactiviti.piper.plugin.ffmpeg.Ffprobe.java

@Override
public Map<String, Object> handle(Task aTask) throws Exception {
    CommandLine cmd = new CommandLine("ffprobe");
    cmd.addArgument("-v").addArgument("quiet").addArgument("-print_format").addArgument("json")
            .addArgument("-show_error").addArgument("-show_format").addArgument("-show_streams")
            .addArgument(aTask.getRequiredString("input"));
    log.debug("{}", cmd);
    DefaultExecutor exec = new DefaultExecutor();
    File tempFile = File.createTempFile("log", null);
    try (PrintStream stream = new PrintStream(tempFile);) {
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);//  ww  w .  jav a  2 s .c om
        return parse(FileUtils.readFileToString(tempFile));
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(tempFile)));
    } finally {
        FileUtils.deleteQuietly(tempFile);
    }
}

From source file:com.blackducksoftware.tools.scmconnector.core.CommandLineExecutor.java

@Override
public int executeCommand(Logger log, CommandLine command, File targetDir, String promptResponse)
        throws Exception {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);// ww  w .  j ava 2 s.c o  m

    PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHangler(log, Level.INFO));
    executor.setStreamHandler(psh);

    providePromptResponse(psh, promptResponse);

    executor.setWorkingDirectory(targetDir);

    // This log msg would reveal password
    // log.info("Command: " + command.toString() + " executed in: "
    // + targetDir.toString());

    int exitStatus = 1;
    try {
        exitStatus = executor.execute(command, EnvironmentUtils.getProcEnvironment());
    } catch (Exception e) {
        log.error("Failure executing Command: " + e.getMessage());
    }
    return exitStatus;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*from  ww  w . j a v  a  2  s . co  m*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:com.comcast.tvx.haproxy.HAProxyServiceController.java

@Override
public int reload() {
    if (!new File("/etc/init.d/haproxy").exists()) {
        logger.info("HaProxy is not installed");
        throw new IllegalArgumentException("HaProxy is not installed");
    }/*w w w .j  ava  2 s .c o m*/

    CommandLine cmdLine = new CommandLine("sudo");
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    cmdLine.addArgument("service");
    cmdLine.addArgument("haproxy");
    cmdLine.addArgument("reload");

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(psh);

    int exitValue;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    logger.info("output from running process: " + stdout.toString());
    logger.info("Exit value was: " + exitValue);
    return exitValue;

}