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

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

Introduction

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

Prototype

public ExecuteWatchdog(final long timeout) 

Source Link

Document

Creates a new watchdog with a given timeout.

Usage

From source file:net.ladenthin.snowman.imager.run.streamer.Streamer.java

@Override
public void run() {
    final CImager conf = ConfigurationSingleton.ConfigurationSingleton.getImager();

    for (;;) {//  w  w w .j ava 2s .c  o m
        if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) {
            LOGGER.trace("killFlag == true");
            return;
        }

        final CommandLine cmdLine = new CommandLine(streamer);
        // final CommandLine cmdLine = new CommandLine("sleep");
        // cmdLine.addArgument("200");

        cmdLine.addArgument("-c");
        cmdLine.addArgument(conf.getStreamer().getDevice());
        cmdLine.addArgument("-t");
        cmdLine.addArgument(
                String.valueOf(conf.getStreamer().getFramesPerSecond() * conf.getStreamer().getRecordTime()));
        cmdLine.addArgument("-r");
        cmdLine.addArgument(String.valueOf(conf.getStreamer().getFramesPerSecond()));
        cmdLine.addArgument("-s");
        cmdLine.addArgument(conf.getStreamer().getResolutionX() + "x" + conf.getStreamer().getResolutionY());
        cmdLine.addArgument("-o");
        cmdLine.addArgument(conf.getStreamer().getPath() + File.separator
                + conf.getSnowmanServer().getCameraname() + "_" + (long) (System.currentTimeMillis() / 1000)
                + "_" + conf.getStreamer().getFramesPerSecond() + "_00000000.jpeg");

        LOGGER.trace("cmdLine: {}", cmdLine);

        // 10 seconds should be more than enough
        final long safetyTimeWindow = 10000;

        final DefaultExecutor executor = new DefaultExecutor();
        final long timeout = 1000 * (conf.getStreamer().getRecordTime() + safetyTimeWindow);
        // final long timeout = 5000;
        LOGGER.trace("timeout: {}", timeout);
        final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
        try {
            LOGGER.debug("start process");
            final int exitValue = executor.execute(cmdLine);
            LOGGER.debug("process executed");
            LOGGER.trace("exitValue: {}", exitValue);
        } catch (IOException e) {
            if (watchdog.killedProcess()) {
                LOGGER.warn("Process was killed on purpose by the watchdog ");
            } else {
                LOGGER.error("Process exited with an error.");
                Imager.waitALittleBit(5000);
            }
        }
        LOGGER.trace("loop end");

    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;/*from   www . ja v a 2 s .c o m*/
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

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

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

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

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

        logger.debug("Pandoc 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 \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

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   w w  w  .ja v a  2  s.  co  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();
}

From source file:io.manasobi.utils.CmdUtils.java

/**
 *   (commandLine) ?   ?? ?  ? ?//w  w  w  .  jav  a 2  s  .  c o m
 * 
 * @param commandLine    
 * @param argument     ?
 * @param timeout     
 * 
 * @return int ? 
 */
public static int execute(CommandLine commandLine, String argument, long timeout) {

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

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    // ? 
    if (StringUtils.isNotEmpty(argument)) {
        commandLine.addArguments(argument);
    }

    //  
    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    // ??  ? 
    executor.setExitValue(SUCCESS_RETURN_CODE);

    try {

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();

        return resultHandler.getExitValue();

    } catch (Exception e) {

        throw new CmdUtilsException(e.getMessage());
    }
}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

/**
 * Executes the ffmpeg process with the previous given arguments.
 * /*from  w  w w .j  a v a 2  s . c  o m*/
 * @return The standard output of the child process.
 * 
 * @throws IOException
 *             If the process call fails.
 */
public String execute() throws IOException {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
        final String arg = args.get(i);
        final Boolean isFile = argIsFile.get(i);
        if (isFile) {
            String key = "file" + fileNumber;
            map.put(key, new File(arg));
            cmdLine.addArgument("'${" + key + "}'", false);
            fileNumber++;
        } else {
            cmdLine.addArgument(arg);
        }
    }
    cmdLine.setSubstitutionMap(map);
    LOG.fine("Execute: " + cmdLine);
    DefaultExecutor executor = new DefaultExecutor();
    //5minutes wait
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 5);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out));
    int[] exitValues = { 0, 1 };
    executor.setExitValues(exitValues);
    executor.execute(cmdLine);
    return out.toString();
}

From source file:de.jsurf.http.HttpServerHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    HttpRequest request = (HttpRequest) e.getMessage();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "video/mpts");
    /*response.setChunked(true);
    response.setHeader(Names.TRANSFER_ENCODING, Values.CHUNKED);*/

    Channel c = e.getChannel();/*w ww .  j a  va  2s  .  com*/

    // create a media reader
    String inputStream = HttpServerConfiguration.getConfiguration().getChannelInput(request.getUri());

    if (inputStream == null) {
        response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
        ChannelFuture future = c.write(response);
        future.addListener(ChannelFutureListener.CLOSE);
        return;
    }

    String path = new java.io.File(".").getCanonicalPath();
    log.debug("Current execution path: " + path);

    String[] parameters = new String[] { "-loglevel", "error", "-i", inputStream, "-vcodec", "copy", "-acodec",
            "copy", "-vbsf", "h264_mp4toannexb", "-f", "mpegts", "pipe:1" };

    CommandLine cmdLine = CommandLine.parse("ffmpeg.exe");
    cmdLine.addArguments(parameters);
    DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchDog = new ExecuteWatchdog(86400000); // One day timeout          
    executor.setWatchdog(watchDog);

    PipedInputStream pin = new PipedInputStream();
    PipedOutputStream pout = new PipedOutputStream(pin);

    PumpStreamHandler streamHandler = new PumpStreamHandler(pout, System.err);
    executor.setStreamHandler(streamHandler);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, resultHandler);

    c.write(response);
    InputStream in = new BufferedInputStream(pin);
    ChannelFuture future = c.write(new ChunkedStream(in));

    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                log.debug("operationComplete: closeChannel");
                future.getChannel().close();
            } catch (Exception e) {

            }
            log.debug("operationComplete: Destroy ffmpeg process");
            watchDog.destroyProcess();
        }
    });
}

From source file:com.adaptris.core.services.system.SystemCommandExecutorService.java

/**
 * Invokes the command line executable/*  w w w. j ava 2s.  com*/
 * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage)
 */
@Override
public void doService(AdaptrisMessage msg) throws ServiceException {

    try (OutputStream out = getOutputCapture().startCapture(msg)) {
        Executor cmd = getCommandBuilder().configure(new DefaultExecutor());
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMs());
        cmd.setWatchdog(watchdog);
        CommandLine cl = getCommandBuilder().createCommandLine(msg);
        Map<String, String> env = getCommandBuilder().createEnvironment(msg);

        PumpStreamHandler pump = new PumpStreamHandler(out);
        cmd.setStreamHandler(pump);
        log.trace("Executing {}", cl);
        int exit = cmd.execute(cl, env);
        msg.addMetadata(COMMAND_RETURN_VALUE_METADATA_KEY, "" + exit);
    } catch (Exception e) {
        throw ExceptionHelper.wrapServiceException(e);
    }
}

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 ava 2s  .  c  om

    return executor;
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

private void startServer() {
    String line = executable.getAbsolutePath() + " server -config=src/test/resources/config.json";
    System.out.println(">> " + line);
    CommandLine parse = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    AtomicBoolean ready = new AtomicBoolean();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> {
        if (l.contains("Vault server started!")) {
            ready.set(true);//from w  ww .  j a v  a2  s .  co m
        }
    }), System.err);

    watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse, resultHandler);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    await().untilAtomic(ready, is(true));
    System.out.println("Vault Server ready - but not yet initialized");
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.svmlib.SVMLibExperimentRunner.java

public static void runCommand(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/*from   ww  w .  jav  a2 s.  c  om*/

    // set one hour limit for training
    ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * 60 * 60);
    executor.setWatchdog(watchdog);

    System.out.println("Running\n" + command);

    int exitValue = executor.execute(cmdLine);
}