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:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Creates executor with system watchdog for given output stream.
 * /*from   w w w  .jav a  2 s  . co m*/
 * @param outputStream
 * @return
 */
private static Executor createExecutor(OutputStream outputStream) {

    // create process watchdog with timeout 60000 milliseconds
    ExecuteWatchdog watchdog = new ExecuteWatchdog(WATCHDOG_TIMEOUT);

    // set watchdog and stream handler
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(outputStream, outputStream));
    return executor;
}

From source file:com.bptselenium.jenkins.BPTSeleniumJenkins.RunCommand.java

public static void runCommand(String command, TaskListener listener, Run<?, ?> build) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValue(10);/* w w  w. j  a v  a  2  s .c  o  m*/
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        //getting a non-standard execution value, set build result to unstable
        Result result = Result.UNSTABLE;
        if (build.getResult() == null) {
            build.setResult(result);
        } else if (build.getResult().isBetterThan(result)) {
            build.setResult(result.combine(build.getResult()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        listener.getLogger().println(outputStream.toString());
    }
}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//w  ww  .  j av  a 2 s.  c o m
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

From source file:com.muk.ext.process.ProcessExecutor.java

public int runCommandLine(CommandLine cmdLine, long maxWaitTimeInMillis) throws IOException {
    ExecuteWatchdog processWatchDog = new ExecuteWatchdog(maxWaitTimeInMillis);
    Executor executor = new DefaultExecutor();

    executor.setExitValue(0);//from ww w .j  a  v a  2 s .  c  o m
    executor.setWatchdog(processWatchDog);

    int result = 1;
    result = executor.execute(cmdLine);

    return result;
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);/*from ww  w . j  av a2  s .  c  o  m*/
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java

private Executor buildExecutor(ExecuteStreamHandler streamHandler) {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMinutes * 60 * 1000));
    // Setting this to null causes the executor to skip verifying exit codes; we'll handle checking the exit status
    // instead of having the executor throw an exception for non-zero exit codes.
    executor.setExitValues(null);/*w  w  w.  j a  v  a 2  s. c o  m*/

    return executor;
}

From source file:com.taobao.ad.es.common.job.executor.ShellHttpJobExecutor.java

@Override
public JobResult execute(JobData jobData) throws IOException {
    JobResult jobResult = JobResult.succcessResult();
    CommandLine cmdLine = CommandLine.parse(jobData.getData().get(JobData.JOBDATA_DATA_JOBCOMMAND));
    Executor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1200000);
    executor.setExitValue(0);/*from w w w.ja va  2  s.  c o m*/
    executor.setWatchdog(watchdog);
    int exitValue = -1;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    }
    if (exitValue != 0) {
        jobResult = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR,
                "Shell?");
        jobResult.setResultCode(exitValue);
        return jobResult;
    }
    jobResult.setResultCode(exitValue);
    return jobResult;
}

From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java

/**
 * Executing a predefined Rule/*from   w ww  . j a v a2  s.c  o m*/
 * @param ruleType RuleType
 * @param arg args for Rule
 * @return Success
 */
public boolean executePredefinedRule(byte ruleType, String arg) {
    logger.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            logger.warn(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}

From source file:de.esukom.decoit.ifmapclient.iptables.RulesExecutor.java

public boolean executePredefinedRule(byte ruleType, String[] arg) {
    IfMapClient.LOGGER.info("[IPTABLES] -> executing predefined command...");

    // use apache's commons-exec for executing command!
    CommandLine cmdLine = new CommandLine(command);

    // get the predefined rule-parameters
    String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg);

    if (ruleParams != null) {

        // add rule-parameters to CommanLine-Object
        for (int i = 0; i < ruleParams.length; i++) {
            cmdLine.addArgument(ruleParams[i]);
        }//ww w  .  jav  a2  s . c  om

        // execute command
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout);
        Executor executor = new DefaultExecutor();
        executor.setExitValue(1);
        executor.setWatchdog(watchdog);
        try {
            executor.execute(cmdLine, resultHandler);
        } catch (ExecuteException e) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: execute-exception occured!");
            return false;
        } catch (IOException e) {
            IfMapClient.LOGGER
                    .warning("[IPTABLES] -> error while executing predefined command: io-exception occured!");
            return false;
        }

        try {
            // some time later the result handler callback was invoked so we
            // can safely request the exit value
            resultHandler.waitFor();
            int exitCode = resultHandler.getExitValue();
            IfMapClient.LOGGER.warning("[IPTABLES] -> command executed, exit-code is: " + exitCode);

            switch (exitCode) {
            case EXIT_CODE_SUCCESS:
                return true;
            case EXIT_CODE_ERROR:
                return false;
            default:
                return false;
            }

        } catch (InterruptedException e) {
            IfMapClient.LOGGER.warning(
                    "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!");
            return false;
        }

    } else {
        IfMapClient.LOGGER.warning(
                "[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!");
        return false;
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);/*from  ww  w  . j a v  a  2 s.c  o  m*/
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured calibre ebook-convert executable
        logger.info("Calibre ebook-convert will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Calibre ebook-convert will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);

    logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString());
    cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString());

    // Output will be in format "KF8" only, old format does not allow external CSS files
    cmdLine.addArgument("--mobi-file-type=new");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(calibreStreamHandler);

    logger.debug("Launching calibres ebook-convert:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("calibres ebook-convert failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("calibre ebook-converts execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) {
                logger.error("calibres ebook-convert could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("calibre ebook-converts execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading calibre ebook-converts output from buffer:");
        logger.error(e.getMessage(), e);

    }

    logger.debug("Calibre ebook-convert output: \n" + output);

    return tempMobiFilepath.toFile();
}