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:de.akquinet.innovation.play.maven.Play2CleanMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("clean");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }/*  w  w  w .  j  a v  a2 s .  c o  m*/

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during cleanup", e);
    }

    // Also delete the dist directory
    File dist = new File(project.getBasedir(), "dist");
    if (dist.exists()) {
        getLog().debug("Deleting " + dist.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(dist);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the dist folder", e);
        }
    } else {
        getLog().debug("'dist' directory not found");
    }

    // Delete the log folder
    File logs = new File(project.getBasedir(), "logs");
    if (logs.exists()) {
        getLog().debug("Deleting " + logs.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(logs);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the logs folder", e);
        }
    } else {
        getLog().debug("'logs' directory not found");
    }

    // Also delete the lib directory if set
    if (cleanLibFolder) {
        File lib = new File(project.getBasedir(), "lib");
        if (lib.exists()) {
            getLog().debug("Deleting " + lib.getAbsolutePath());
            try {
                FileUtils.deleteDirectory(lib);
            } catch (IOException e) {
                throw new MojoExecutionException("Can't delete the " + lib + " folder", e);
            }
        } else {
            getLog().debug("'" + lib + "' directory not found");
        }
    }
}

From source file:com.vmware.bdd.usermgmt.job.ChangeLocalAccountStateExecutor.java

private void changeLocalAccountState(String argument) {
    //String chefCmd = "sudo /opt/serengeti/sbin/set-password L";
    String sudoCmd = CommonUtil.getCustomizedSudoCmd();
    CommandLine cmdLine = new CommandLine(sudoCmd).addArgument(SET_PASSWORD_COMMAND).addArgument(argument);

    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger
            new ExecOutputLogger(LOGGER, true)) //error logger
    );/*w  ww.  j  a  v  a2 s . com*/

    executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT));

    try {
        int exitVal = executor.execute(cmdLine);
        if (exitVal != 0) {
            throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", null);
        }
    } catch (IOException e) {
        throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", e);
    }
}

From source file:com.stratio.explorer.shell.ShellInterpreter.java

@Override
public InterpreterResult interpret(String cmd) {
    logger.info("Run shell command '" + cmd + "'");
    long start = System.currentTimeMillis();
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(cmd, false);//from  w w  w.  ja  v  a  2 s .  c om
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    executor.setWatchdog(new ExecuteWatchdog(CMD_TIMEOUT));
    try {
        int exitValue = executor.execute(cmdLine);
        return new InterpreterResult(InterpreterResult.Code.SUCCESS, outputStream.toString());
    } catch (ExecuteException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    } catch (IOException e) {
        logger.error("Can not run " + cmd, e);
        return new InterpreterResult(Code.ERROR, e.getMessage());
    }
}

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();/*from   ww w.j  a v a2  s  .c  om*/

    // 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:it.drwolf.ridire.utility.RIDIREReTagger.java

public String retagFile(File f) throws ExecuteException, IOException {
    // Map<String, File> map = new HashMap<String, File>();
    String fileIN = f.getAbsolutePath();
    String fileOut = f.getAbsolutePath() + ".iso";
    String posOld = f.getAbsolutePath() + ".iso.pos";
    String posNew = f.getAbsolutePath() + ".pos";
    // first convert from utf8 to iso8859-1
    CommandLine commandLine = CommandLine.parse("iconv");
    commandLine.addArgument("-c").addArgument("-s").addArgument("-f").addArgument("utf8").addArgument("-t")
            .addArgument("iso8859-1//TRANSLIT").addArgument("-o").addArgument(fileOut, false)
            .addArgument(fileIN, false);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(commandLine);
    if (exitValue == 0) {
        // tag using latin1 and Baroni's tagset
        commandLine = CommandLine.parse(this.treeTaggerBin);
        commandLine.addArgument(fileOut, false);
        executor = new DefaultExecutor();
        executor.setExitValue(0);//w  w w.  ja  v  a2s  . c  o  m
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        TreeTaggerLog treeTaggerLog = new TreeTaggerLog();
        PumpStreamHandler executeStreamHandler = new PumpStreamHandler(treeTaggerLog, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue2 = executor.execute(commandLine);
        if (exitValue2 == 0) {
            // FileUtils.deleteQuietly(new File(fileOut));
            File posTagFile = new File(posOld);
            FileUtils.writeLines(posTagFile, treeTaggerLog.getLines());
        }
        // reconvert to utf8
        commandLine = CommandLine.parse("iconv");
        commandLine.addArgument("-s").addArgument("-f").addArgument("iso8859-1").addArgument("-t")
                .addArgument("utf8//TRANSLIT").addArgument("-o").addArgument(posNew, false)
                .addArgument(posOld, false);
        executor = new DefaultExecutor();
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        int exitValue3 = executor.execute(commandLine);
        if (exitValue3 == 0) {
            // FileUtils.deleteQuietly(new File(f.getPath() + ".iso.pos"));
            return new File(posNew).getCanonicalPath();
        }
    }
    return null;
}

From source file:com.k42b3.sacmis.ExecutorAbstract.java

public void run() {
    try {//w ww .  j  a v  a2s .  com
        // clear text
        this.textArea.setText("");

        CommandLine commandLine = CommandLine.parse(this.getExecutable() + " " + this.cmd);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setStreamHandler(new PumpStreamHandler(new TextAreaOutputStream(textArea)));
        executor.setWatchdog(watchdog);
        executor.execute(commandLine);
    } catch (FoundNoExecutableException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Information", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.oneops.inductor.ProcessRunner.java

/**
 * Creates a process and logs the output
 *
 * @param cmd/*from w w  w  .j  a v a 2s.c o m*/
 * @param logKey
 * @param result
 */
private void executeProcess(String[] cmd, String logKey, ProcessResult result) {

    Map<String, String> env = getEnvVars(logKey, cmd);
    logger.info(logKey + " Cmd: " + String.join(" ", cmd) + ", Env: " + env);

    // run the cmd
    try {

        CommandLine cmdLine = new CommandLine(cmd[0]);
        // add rest of cmd string[] as arguments
        for (int i = 1; i < cmd.length; i++) {
            // needs the quote handling=false or else doesn't work
            // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec?
            cmdLine.addArgument(cmd[i], false);
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
        executor.setStreamHandler(new OutputHandler(logger, logKey, result));
        result.setResultCode(executor.execute(cmdLine, env));

        // set fault to last error if fault map is empty
        if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) {
            result.getFaultMap().put("ERROR", result.getLastError());
        }

    } catch (ExecuteException ee) {
        logger.error(logKey + ee);
        result.setResultCode(ee.getExitValue());
    } catch (IOException e) {
        logger.error(e);
        result.setResultCode(1);
    }

}

From source file:io.rhiot.utils.process.ExecProcessManager.java

@Override
public List<String> executeAndJoinOutput(String... command) {

    CommandLine cmdLine = CommandLine.parse(String.join(" ", command));
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/* w w  w .ja v  a2 s.  c om*/
    ExecResultHandler resultHandler = null;

    if (getTimeout() > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(getTimeout());
        executor.setWatchdog(watchdog);
        resultHandler = new ExecResultHandler(watchdog);
    }
    try {
        CollectingLogOutputStream outAndErr = new CollectingLogOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(outAndErr));
        if (resultHandler != null) {
            executor.execute(cmdLine, resultHandler);
        } else {
            executor.execute(cmdLine);
        }
        resultHandler.waitFor();
        return outAndErr.getLines();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vmware.bdd.service.impl.NodeLdapUserMgmtConfService.java

private void transferFile(String srcFilePath, String ip, String targetFilePath) {
    CommandLine cmdLine = new CommandLine("scp").addArgument(srcFilePath)
            .addArgument(ip + ":" + targetFilePath);

    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger
            new ExecOutputLogger(LOGGER, true)) //error logger
    );//w  w  w  . jav  a 2  s  .c  o  m

    executor.setWatchdog(new ExecuteWatchdog(1000l * 120l));

    try {
        int exitVal = executor.execute(cmdLine);
        if (exitVal != 0) {
            throw new RuntimeException("CFG_LDAP_FAIL", null);
        }
    } catch (IOException e) {
        throw new RuntimeException("CFG_LDAP_FAIL", e);
    }
}

From source file:com.vmware.bdd.usermgmt.job.CfgUserMgmtOnMgmtVMExecutor.java

private void execCommand(CommandLine cmdLine) {
    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger
            new ExecOutputLogger(LOGGER, true)) //error logger
    );//from w  w w .  j  a  v  a 2  s . c  o  m

    executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT));

    try {
        int exitVal = executor.execute(cmdLine);
        if (exitVal != 0) {
            throw new UserMgmtExecException("CFG_LDAP_FAIL", null);
        }
    } catch (IOException e) {
        throw new UserMgmtExecException("CFG_LDAP_FAIL", e);
    }
}