Example usage for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler

Introduction

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

Prototype

public PumpStreamHandler(final OutputStream outAndErr) 

Source Link

Document

Construct a new PumpStreamHandler.

Usage

From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java

static public String pushAppOntoDevice(String appPath, String deviceSerial) {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    CommandLine cmdLine = new CommandLine(sdkPath + getSlash() + "platform-tools" + getSlash() + "adb");
    Map<String, String> map = new HashMap<String, String>();
    map.put("deviceSerial", deviceSerial);
    cmdLine.addArgument("-s", false);
    cmdLine.addArgument("${deviceSerial}", false);
    cmdLine.addArgument("install", false);
    cmdLine.addArgument(appPath, false);
    cmdLine.setSubstitutionMap(map);/*from   w  ww .  java 2  s  .  co  m*/
    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
        return stdout.toString();
    } catch (ExecuteException e) {
        return Constants.UNEXPECTED_ERROR;
    } catch (IOException e) {
        return Constants.UNEXPECTED_ERROR;
    }
}

From source file:org.rbr8.script_runner.util.BatchScriptRunner.java

public void processFile(File file) throws IOException {

    CommandLine cmdLine = new CommandLine(executable);
    cmdLine.addArguments(arguments);//w w w  . jav a2 s  . c  om

    Map<String, Object> map = new HashMap<>();
    map.put(SubstitutionHelper.FILE, file);
    cmdLine.setSubstitutionMap(map);

    DefaultExecutor executor = new DefaultExecutor();
    //        executor.setExitValue(1);

    //        NotifierLogOutputStream outputLog = new NotifierLogOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(logOutputStream);
    executor.setStreamHandler(psh);

    //        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    //        executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
}

From source file:org.sikuli.natives.LinuxUtil.java

@Override
public void checkLibAvailability() {
    List<CommandLine> commands = Arrays.asList(CommandLine.parse("wmctrl -m"),
            CommandLine.parse("xdotool version"), CommandLine.parse("killall --version"));
    String msg = "";
    for (CommandLine cmd : commands) {
        try {//from   ww w  .  ja v a 2s . c  om
            DefaultExecutor executor = new DefaultExecutor();
            executor.setExitValue(0);
            //suppress system output
            executor.setStreamHandler(new PumpStreamHandler(null));
            executor.execute(cmd);
        } catch (IOException e) {
            String executable = cmd.toStrings()[0];
            if (executable.equals("wmctrl")) {
                wmctrlAvail = false;
            }
            if (executable.equals("xdotool")) {
                xdoToolAvail = false;
            }
            msg += "command '" + executable + "' is not executable\n";
        }
    }
    if (!msg.isEmpty()) {
        msg += "Please check the availability - some features might not work without!";
        Debug.error(msg);
    }
}

From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java

@Override
protected void startApplication() {
    File bundleDirectory = getBundleDirectory();
    List<String> javaOptions = getConfiguration().getJavaOptions();
    List<String> javaAgentOptions = getJavaAgentOptions();

    CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java"));
    if (javaAgentOptions.size() > 0) {
        cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()]));
    }/*  w ww . j  a  va  2s .c  om*/
    if (javaOptions.size() > 0) {
        cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()]));
    }
    cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments())
            .addArgument("config.yaml");

    log.debug("Launching: {}", cmdLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(bundleDirectory);
    executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis()));

    try {
        executor.setStreamHandler(streamHandler = new PumpStreamHandler(
                new FileOutputStream(new File(bundleDirectory, "output.log"))));
        executor.execute(cmdLine, new DefaultExecuteResultHandler());
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.waarp.commandexec.server.LocalExecServerHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    answered = false;/* w w w  . ja  v  a  2s.  c  om*/
    String request = msg;

    // Generate and write a response.
    String response;
    response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result;
    ExecuteWatchdog watchdog = null;
    try {
        if (request.length() == 0) {
            // No command
            response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result;
        } else {
            String[] args = request.split(" ");
            int cpt = 0;
            long tempDelay;
            try {
                tempDelay = Long.parseLong(args[0]);
                cpt++;
            } catch (NumberFormatException e) {
                tempDelay = delay;
            }
            if (tempDelay < 0) {
                // Shutdown Order
                isShutdown = true;
                logger.warn("Shutdown order received");
                response = LocalExecDefaultResult.ShutdownOnGoing.status + " "
                        + LocalExecDefaultResult.ShutdownOnGoing.result;
                Thread thread = new GGLEThreadShutdown(factory);
                thread.start();
                return;
            }
            String binary = args[cpt++];
            File exec = new File(binary);
            if (exec.isAbsolute()) {
                // If true file, is it executable
                if (!exec.canExecute()) {
                    logger.error("Exec command is not executable: " + request);
                    response = LocalExecDefaultResult.NotExecutable.status + " "
                            + LocalExecDefaultResult.NotExecutable.result;
                    return;
                }
            }
            // Create command with parameters
            CommandLine commandLine = new CommandLine(binary);
            for (; cpt < args.length; cpt++) {
                commandLine.addArgument(args[cpt]);
            }
            DefaultExecutor defaultExecutor = new DefaultExecutor();
            ByteArrayOutputStream outputStream;
            outputStream = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
            defaultExecutor.setStreamHandler(pumpStreamHandler);
            int[] correctValues = { 0, 1 };
            defaultExecutor.setExitValues(correctValues);
            if (tempDelay > 0) {
                // If delay (max time), then setup Watchdog
                watchdog = new ExecuteWatchdog(tempDelay);
                defaultExecutor.setWatchdog(watchdog);
            }
            int status = -1;
            try {
                // Execute the command
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e) {
                if (e.getExitValue() == -559038737) {
                    // Cannot run immediately so retry once
                    try {
                        Thread.sleep(LocalExecDefaultResult.RETRYINMS);
                    } catch (InterruptedException e1) {
                    }
                    try {
                        status = defaultExecutor.execute(commandLine);
                    } catch (ExecuteException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    } catch (IOException e1) {
                        try {
                            pumpStreamHandler.stop();
                        } catch (IOException e3) {
                        }
                        logger.error("Exception: " + e.getMessage() + " Exec in error with "
                                + commandLine.toString());
                        response = LocalExecDefaultResult.BadExecution.status + " "
                                + LocalExecDefaultResult.BadExecution.result;
                        try {
                            outputStream.close();
                        } catch (IOException e2) {
                        }
                        return;
                    }
                } else {
                    try {
                        pumpStreamHandler.stop();
                    } catch (IOException e3) {
                    }
                    logger.error(
                            "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                    response = LocalExecDefaultResult.BadExecution.status + " "
                            + LocalExecDefaultResult.BadExecution.result;
                    try {
                        outputStream.close();
                    } catch (IOException e2) {
                    }
                    return;
                }
            } catch (IOException e) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e3) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                response = LocalExecDefaultResult.BadExecution.status + " "
                        + LocalExecDefaultResult.BadExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return;
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e3) {
            }
            if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
                // kill by the watchdoc (time out)
                logger.error("Exec is in Time Out");
                response = LocalExecDefaultResult.TimeOutExecution.status + " "
                        + LocalExecDefaultResult.TimeOutExecution.result;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            } else {
                try {
                    response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name());
                } catch (UnsupportedEncodingException e) {
                    response = status + " " + outputStream.toString();
                }
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
            }
        }
    } finally {
        // We do not need to write a ByteBuf here.
        // We know the encoder inserted at LocalExecInitializer will do the
        // conversion.
        ctx.channel().writeAndFlush(response + "\n");
        answered = true;
        if (watchdog != null) {
            watchdog.stop();
        }
        logger.info("End of Command: " + request + " : " + response);
        ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n");
    }
}

From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java

/**
 * Execute shell command/* w ww .  ja  va2s.  c  o  m*/
 *
 * @param commandText
 */
protected int executeCommand(final String commandText, Map<String, String> environment) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    int result;
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".."
                + PATH_SEP + CONFIGURATOR_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        result = exec.execute(commandline, environment);

    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.xdi.util.process.ProcessHelper.java

public static boolean executeProgram(CommandLine commandLine, String workingDirectory,
        boolean executeInBackground, int successExitValue, OutputStream outputStream) {
    long printJobTimeout = PRINT_JOB_TIMEOUT;

    ExecuteStreamHandler streamHandler = null;
    if (outputStream != null) {
        streamHandler = new PumpStreamHandler(outputStream);
    }//from w w  w.  java  2s .  com

    PrintResultHandler printResult = null;
    try {
        log.debug(String.format("Preparing to start process %s", commandLine.toString()));
        printResult = executeProgram(commandLine, workingDirectory, printJobTimeout, executeInBackground,
                successExitValue, streamHandler);
        log.debug(String.format("Successfully start process %s", commandLine.toString()));
    } catch (Exception ex) {
        log.trace(String.format("Problem during starting process %s", commandLine.toString()), ex);
        ex.printStackTrace();
        return false;
    }

    // come back to check the print result
    log.debug(String.format("Waiting for the proces %s finish", commandLine.toString()));
    try {
        if (printResult == null) {
            return false;
        }
        printResult.waitFor();
    } catch (InterruptedException ex) {
        log.error(String.format("Problem during process execution %s", commandLine.toString()), ex);
    }

    log.debug(String.format("Process %s has finished", commandLine.toString()));

    return true;
}

From source file:org.zanata.rest.service.VirusScanner.java

/**
 * Builds an Executor which will output to the specified OutputStream.
 * <p>//from www  .  jav  a  2 s  .c o  m
 * The Executor will be configured to return exit values as int, rather than
 * throwing ExecuteException.
 *
 * @param output
 * @return a configured Executor
 */
private Executor buildExecutor(OutputStream output) {
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    ExecuteStreamHandler psh = new PumpStreamHandler(output);
    executor.setStreamHandler(psh);
    // We want to handle all exit values directly (not as ExecuteException).
    executor.setExitValues(null);
    return executor;
}

From source file:org.zanata.sync.jobs.utils.ProcessUtils.java

public static List<String> runNativeCommand(Path workingDir, long timeoutInMilli, String... commands) {
    Preconditions.checkArgument(commands != null && commands.length > 0, "You must provide commands to run");

    CommandLine commandLine = CommandLine.parse(commands[0]);
    ImmutableList<String> args = ImmutableList.copyOf(commands).subList(1, commands.length);
    for (String arg : args) {
        commandLine.addArgument(arg);/*  w  w w.j  a  v a 2 s  .  c o  m*/
    }

    Executor executor = new DefaultExecutor();

    ImmutableList.Builder<String> output = ImmutableList.builder();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            log.info(line);
            output.add(line);
        }
    }));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutInMilli);
    executor.setWatchdog(watchDog);
    executor.setWorkingDirectory(workingDir.toFile());
    executor.setProcessDestroyer(PROCESS_DESTROYER);

    try {
        int exitCode = executor.execute(commandLine);
        if (Execute.isFailure(exitCode) && watchDog.killedProcess()) {
            // it was killed on purpose by the watchdog
            log.error("process {} taking too long to run and killed by watchdog", commandLine);
        }
    } catch (IOException e) {
        log.error("error running:{}", commandLine);
        throw Throwables.propagate(e);
    }

    return output.build();
}

From source file:ro.cosu.vampires.client.executors.fork.ForkExecutor.java

@Override
public Result execute(Computation computation) {

    acquireResources();//  w w w. j a v  a2  s .  c  om

    CommandLine commandLine = getCommandLine(computation.command());

    CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream();
    PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream);
    executor.setStreamHandler(handler);
    executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS));
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    LocalDateTime start = LocalDateTime.now();
    int exitCode;
    try {
        executor.execute(commandLine, resultHandler);
    } catch (IOException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    try {
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1;

    //TODO take different action for failed commands so we can collect the output (stderr or java exception)

    LocalDateTime stop = LocalDateTime.now();

    long duration = Duration.between(start, stop).toMillis();

    releaseResources();
    return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop))
            .output(collectingLogOutputStream.getLines()).build();

}