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

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

Introduction

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

Prototype

public void setWatchdog(final ExecuteWatchdog watchDog) 

Source Link

Usage

From source file:it.drwolf.ridire.session.async.Mapper.java

@SuppressWarnings("unchecked")
private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager)
        throws IOException, InterruptedException {
    String workingDirName = System.getProperty("java.io.tmpdir");
    String userDir = System.getProperty("user.dir");
    byte[] buf = new byte[Mapper.BUFLENGTH];
    int count = 0;
    GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((count = gzis.read(buf)) != -1) {
        baos.write(buf, 0, count);/*from  www . j  a  v  a 2 s  .c  om*/
    }
    gzis.close();
    baos.close();
    byte[] byteArray = baos.toByteArray();
    String uuid = UUID.randomUUID().toString();
    String pdfFileName = uuid + ".pdf";
    String htmlFileName = uuid + ".html";
    File tmpDir = new File(workingDirName);
    String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName;
    File fileToConvert = new File(tmpDir, pdfFileName);
    FileUtils.writeByteArrayToFile(fileToConvert, byteArray);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY);
    CommandLine commandLine = CommandLine.parse(cp.getCommandValue());
    commandLine.addArgument("-c");
    commandLine.addArgument("-i");
    commandLine.addArgument(fileToConvert.getAbsolutePath());
    commandLine.addArgument(htmlFileNameCompletePath);
    executor.setExitValue(0);
    executor.execute(commandLine);
    try {
        FileUtils.moveFileToDirectory(
                new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false);
    } catch (IOException e) {
    }
    cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY);
    commandLine = CommandLine
            .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue());
    commandLine.addArgument(htmlFileNameCompletePath);
    commandLine.addArgument("39");
    commandLine.addArgument("6");
    commandLine.addArgument("5");
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
    ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null);
    executor.setStreamHandler(executeStreamHandler);
    int exitValue = executor.execute(commandLine);
    String htmlString = null;
    if (exitValue == 0) {
        htmlString = baosStdOut.toString();
    }
    FileUtils.deleteQuietly(new File(htmlFileNameCompletePath));
    PrefixFileFilter pff = new PrefixFileFilter(uuid);
    for (File f : FileUtils.listFiles(tmpDir, pff, null)) {
        FileUtils.deleteQuietly(f);
    }
    if (htmlString != null) {
        htmlString = htmlString.replaceAll(" ", " ");
        htmlString = htmlString.replaceAll("<br.*?>", " ");
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(htmlString.getBytes());
        String encoding = charsetDetector.detect().getName();
        return new StringWithEncoding(htmlString, encoding);
    }
    return null;
}

From source file:net.spinetrak.rpitft.command.Command.java

Result execute(final Stream stream_) {
    final CommandLine commandline = CommandLine.parse(_script);
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(500);
    exec.setWatchdog(watchdog);
    final PumpStreamHandler streamHandler = new PumpStreamHandler(stream_.getStream());
    exec.setStreamHandler(streamHandler);
    int result = -1;
    try {//w  ww .ja  v  a  2s.c o  m
        result = exec.execute(commandline);
    } catch (final IOException ex_) {
        //LOGGER.error(ex_.getMessage());
    }
    return new Result(stream_, result);
}

From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java

protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//from   ww  w.  j a  va2 s  . c om

    if (execCommand.getWorkingDir() != null) {
        executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile());
    }
    if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) {
        executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout()));
    }
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    return executor;
}

From source file:org.apache.falcon.regression.core.util.ExecUtil.java

public static ExecResult executeCommand(CommandLine commandLine) {
    LOGGER.info("Command to be executed: " + commandLine);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5 * 1000)); //timeout of 5 seconds
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));
    int exitVal = 1;
    String exception = "";
    try {/*w  ww .  ja va 2  s . co m*/
        exitVal = executor.execute(commandLine);
    } catch (IOException e) {
        LOGGER.warn("Caught exception: " + e);
        exception = e.toString();
    }
    final String output = outStream.toString();
    String errors = errStream.toString();
    errors = errors.isEmpty() ? exception : errors;

    LOGGER.info("exitVal: " + exitVal);
    LOGGER.info("output: " + output);
    LOGGER.info("errors: " + errors);
    return new ExecResult(commandLine, exitVal, output.trim(), errors.trim());
}

From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//from ww w . j av  a  2 s  .  co m

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();
    res.exitcode = executor.execute(cmd, execEnv(env));
    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);

    return res;
}

From source file:org.apache.hive.hcatalog.templeton.StreamOutputWriter.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);/*from   ww w  .  j a va2s .  c o  m*/

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();

    res.exitcode = executor.execute(cmd, execEnv(env));

    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);
    try {
        watchdog.checkException();
    } catch (Exception ex) {
        LOG.error("Command: " + cmd + " failed. res=" + res, ex);
    }
    if (watchdog.killedProcess()) {
        String msg = " was terminated due to timeout(" + timeout + "ms).  See " + AppConfig.EXEC_TIMEOUT_NAME
                + " property";
        LOG.warn("Command: " + cmd + msg + " res=" + res);
        res.stderr += " Command " + msg;
    }
    if (res.exitcode != 0) {
        LOG.info("Command: " + cmd + " failed. res=" + res);
    }
    return res;
}

From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

/**
 * Execute shell command/* ww w. ja  v  a  2 s .c  o  m*/
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText, File workingDir) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        if (workingDir != null) {
            exec.setWorkingDirectory(workingDir);
        }
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        log.info("Executing command: " + commandText
                + (workingDir == null ? "" : " at " + workingDir.getCanonicalPath()));
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * Execute shell command/*from  w w  w.ja  va2s .  c  o  m*/
 *
 * @param commandText Command string to be executed
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText, int timeout) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentIntegrationTest.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java

/**
 * Execute shell command//from  w ww.j  a  v  a2 s .c om
 *
 * @param commandText
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentTestManager.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * Execute shell command/*  w  w w. jav a  2  s  . co  m*/
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}