Example usage for org.apache.commons.exec Executor setWatchdog

List of usage examples for org.apache.commons.exec Executor setWatchdog

Introduction

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

Prototype

void setWatchdog(ExecuteWatchdog watchDog);

Source Link

Document

Set the watchdog used to kill of processes running, typically, too long time.

Usage

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ??  ??  ? ? ./*from   ww  w .  j  a  v a2 s . com*/
 *
 * @param start     ??
 * @param end       ??
 * @param filename ?? ?
 * @return ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static String read(long start, long end, String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter
            .arrayFormat("sed '{},{}!d' {}", new Object[] { start, end, filename }).getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return new String(out.toByteArray());
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ?? ??  ? .//from ww w  .j a v  a2s. c  o  m
 *
 * @param filename ??  ? ?
 * @return  ?? ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static int lines(String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter.arrayFormat("sed -n '$=' {}", new Object[] { filename })
            .getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return Integer.parseInt(new String(out.toByteArray()).trim());
}

From source file:org.openhab.binding.exec.internal.ExecBinding.java

/**
 * <p>Executes <code>commandLine</code>. Sometimes (especially observed on 
 * MacOS) the commandLine isn't executed properly. In that cases another 
 * exec-method is to be used. To accomplish this please use the special 
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this 
 * delimiter it is split into a String[] array and the special exec-method
 * is used.</p>/*from   www  .j av a  2  s. c  o m*/
 * <p>A possible {@link IOException} gets logged but no further processing is
 * done.</p> 
 * 
 * @param commandLine the command line to execute
 * @return response data from executed command line 
 */
private String executeCommandAndWaitResponse(String commandLine) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.openhab.io.net.exec.ExecUtil.java

/**
 * <p>/*w ww . j a  va  2 s  . com*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        if (resultHandler.getException() != null) {
            logger.warn(resultHandler.getException().getMessage());
        } else {
            logger.debug("exit code '{}', result '{}'", exitCode, retval);
        }

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

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

/**
 * /*from  ww  w.  j  a  v a2s.  c  o  m*/
 * @param printJobTimeout
 *            the printJobTimeout (ms) before the watchdog terminates the
 *            print process
 * @param printInBackground
 *            printing done in the background or blocking
 * @param streamHandler
 * @return a print result handler (implementing a future)
 * @throws IOException
 *             the test failed
 */
public static PrintResultHandler executeProgram(CommandLine commandLine, String workingDirectory,
        long printJobTimeout, boolean printInBackground, int successExitValue,
        ExecuteStreamHandler streamHandler) throws IOException {
    ExecuteWatchdog watchdog = null;
    PrintResultHandler resultHandler;

    // Create the executor and consider the successExitValue as success
    Executor executor = new DefaultExecutor();
    executor.setExitValue(successExitValue);

    if (StringHelper.isNotEmpty(workingDirectory)) {
        executor.setWorkingDirectory(new File(workingDirectory));
    }

    // Redirect streams if needed
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    // Create a watchdog if requested
    if (printJobTimeout > 0) {
        watchdog = new ExecuteWatchdog(printJobTimeout);
        executor.setWatchdog(watchdog);
    }

    // Pass a "ExecuteResultHandler" when doing background printing
    if (printInBackground) {
        log.debug(String.format("Executing non-blocking process %s", commandLine.toString()));
        resultHandler = new PrintResultHandler(watchdog);
        executor.execute(commandLine, resultHandler);
    } else {
        log.debug(String.format("Executing blocking process %s", commandLine.toString()));
        successExitValue = executor.execute(commandLine);
        resultHandler = new PrintResultHandler(successExitValue);
    }

    return resultHandler;
}

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);/*from  w  w  w.j av a2 s . com*/
    }

    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();
}