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:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir,
        InputStream input) throws IOException {
    // Create the result object
    TestJobResult.TransformResult result = new TestJobResult.TransformResult();

    CountingOutputStream output = null;//from   w ww.  j  a  v  a  2  s .  co m
    CountingOutputStream error = null;
    try {
        // Create and open temporary file for standard output
        File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir);
        output = new CountingOutputStream(new FileOutputStream(outputFile));

        // Create and open temporary file for standard error
        File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir);
        error = new CountingOutputStream(new FileOutputStream(errorFile));

        // If executable is relative, try to resolve in working directory
        // (This emulates the behavior of Streaming)
        if (!executable.isAbsolute()) {
            File resolvedExecutable = new File(workingDir, executable.toString());
            if (resolvedExecutable.isFile()) {
                resolvedExecutable.setExecutable(true);
                executable = resolvedExecutable.getAbsoluteFile();
            }
        }

        // Run the transform

        CommandLine command;
        if (_switchUserCommand == null)
            command = new CommandLine(executable);
        else {
            command = CommandLine.parse(_switchUserCommand);
            HashMap<String, String> substitutionMap = new HashMap<String, String>();
            substitutionMap.put("cmd", executable.toString());
            command.setSubstitutionMap(substitutionMap);
        }

        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(output, error, input);
        executor.setWorkingDirectory(workingDir);
        executor.setWatchdog(dog);
        executor.setStreamHandler(pump);
        executor.setExitValues(null);

        int exitCode = executor.execute(command);

        result.setExitCode(exitCode);

        // Check whether it produced any output
        if (output.getByteCount() == 0) {
            output.close();
            outputFile.delete();
        } else
            result.setOutputFile(outputFile);

        // Check whether it produced any error output
        if (error.getByteCount() == 0) {
            error.close();
            errorFile.delete();
        } else
            result.setErrorFile(errorFile);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(error);
    }

    return result;
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }//  w w w.j a  va2 s .  co m
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

From source file:com.github.cshubhamrao.MediaConverter.MainUI.java

/** Runs ffmpeg -version */
@Override//from ww w  .  j av  a  2s. co  m
protected Void doInBackground() {
    ffmpeg = FFMpegLoader.getFFMpegExecutable();
    if (ffmpeg != null) {
        try {
            cmd = new CommandLine(ffmpeg);
            cmd.addArgument("-version");
            OutputStream outputStream = new ByteArrayOutputStream();
            DefaultExecutor exec = new DefaultExecutor();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            exec.setStreamHandler(streamHandler);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
            exec.setWatchdog(watchdog);
            exec.execute(cmd);
            publish(outputStream.toString());
        } catch (ExecuteException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:modules.GeneralNativeCommandModule.java

protected KeyValueResult extractNative(String command, String options, Path path)
        throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }//from www  . j av  a2 s  . c  o m
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {
        // System.out.println(commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        // System.out.println(commandLine);
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults");
    t.add("fullOutput", outputStream.toString().trim());
    return t;
}

From source file:modules.NativeProcessIterativeDaemonModule.java

protected String extractNative(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }//from w w w  . ja  v  a  2  s  .  c o  m
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {

        // System.out.println("Now execute " + commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    return outputStream.toString().trim();
}

From source file:it.drwolf.ridire.index.cwb.CWBFrequencyList.java

private String getFrequencyList(boolean deleteFLFile, List<String> semDescription, List<String> funDescription,
        int quantityP, String type, Integer threshold, boolean sorted) {
    CommandLine commandLine = CommandLine.parse(this.cwbscanExecutable);
    commandLine.addArgument("-q");
    if (threshold != null && threshold > 0) {
        commandLine.addArgument("-f");
        commandLine.addArgument(threshold + "");
    }// ww w  .  ja v  a  2 s . co m
    commandLine.addArgument("-r").addArgument(this.cqpRegistry);
    commandLine.addArgument("-C");
    commandLine.addArgument(this.cqpCorpusName);
    if (type.equals("forma")) {
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS")) {
        commandLine.addArgument("pos+0");
    } else if (type.equals("easypos")) {
        commandLine.addArgument("easypos+0");
    } else if (type.equals("lemma")) {
        commandLine.addArgument("lemma+0");
    } else if (type.equals("PoS-forma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS-lemma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("lemma+0");
    }
    String semFuncParam = "";
    if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
            && funDescription.get(0).trim().length() > 0
            || semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                    && semDescription.get(0).trim().length() > 0) {
        semFuncParam = "?";
        if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
                && funDescription.get(0).trim().length() > 0) {
            String fd = StringUtils.join(funDescription, "\\|");
            semFuncParam += "text_functional=/\\(" + fd + "\\)/ ";
        }
        if (semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                && semDescription.get(0).trim().length() > 0) {
            String sd = StringUtils.join(semDescription, "\\|");
            semFuncParam += "text_semantic=/\\(" + sd + "\\)/ ";

        }
        commandLine.addArgument(semFuncParam);
    }
    if (sorted) {
        commandLine.addArgument("|");
        commandLine.addArgument("sort");
        commandLine.addArgument("-nr");
        commandLine.addArgument("-k");
        commandLine.addArgument("1");
    }
    if (quantityP > 0) {
        commandLine.addArgument("|");
        commandLine.addArgument("head");
        commandLine.addArgument("-" + quantityP);
    }
    File flTempFile = null;
    try {
        flTempFile = File.createTempFile("ridireFL", null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    commandLine.addArgument(" > ");
    commandLine.addArgument(flTempFile.getAbsolutePath());
    String c = commandLine.toString();
    try {
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, c);
        tempSh.setExecutable(true);
        commandLine = CommandLine.parse(tempSh.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBFrequencyList.TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = 0;
        exitValue = executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        if (exitValue == 0) {
            StrTokenizer strTokenizer = new StrTokenizer();
            this.frequencyList = new ArrayList<FrequencyItem>();
            List<String> lines = FileUtils.readLines(flTempFile);
            for (String line : lines) {
                strTokenizer.reset(line);
                String[] tokens = strTokenizer.getTokenArray();
                if (tokens.length == 2) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                } else if (tokens.length == 3) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[2], tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                }
            }
            if (deleteFLFile) {
                FileUtils.deleteQuietly(flTempFile);
            }
        }
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return flTempFile.getAbsolutePath();
}

From source file:com.nts.alphamale.shell.AdbShellExecutor.java

/**
 * @param cmd adb /* w  w w .  j ava  2  s . c om*/
 * @param synch   ? ? true: synchronous, false: asynchronous
 * @param  (ms)
 * @return Executor Standard Output? Map
 */
public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) {
    Map<String, Object> executorMap = new HashMap<String, Object>();
    DefaultExecutor executor = new DefaultExecutor();
    PipedOutputStream pos = new PipedOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err);
    streamHandler.setStopTimeout(timeoutMilliseconds);
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new PipedInputStream(pos));
    } catch (IOException e) {
        //log.error(e.getCause() + " : " + e.getMessage());
    }
    executor.setStreamHandler(streamHandler);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds);
    executor.setWatchdog(watchDog);
    try {
        if (synch)
            executor.execute(cmd);
        else
            executor.execute(cmd, new DefaultExecuteResultHandler());

        log.debug(cmd.toString());
        LineIterator li = IOUtils.lineIterator(dis, "UTF-8");
        if (li != null) {
            executorMap.put("executor", executor);
            executorMap.put("stdOut", li);
        }
    } catch (Exception e) {
        log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]");
    }
    return executorMap;
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);
    exec.setStreamHandler(pump);//w  w  w. j a v  a  2s  .  co m
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

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 .  ja  v  a 2s  .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:io.vertx.config.vault.utils.VaultProcess.java

private void init() {
    String line = executable.getAbsolutePath() + " init -key-shares=1 -key-threshold=1 " + CA_CERT_ARG;
    System.out.println(">> " + line);
    CommandLine parse = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> {
        if (l.contains("Unseal Key 1:")) {
            unseal = l.replace("Unseal Key 1: ", "").trim();
        } else if (l.contains("Initial Root Token:")) {
            token = l.replace("Initial Root Token: ", "").trim();
        }/*from w w  w .ja  v a2 s .c  o m*/
    }), System.err);

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

    //    await().until(() -> token != null);
    //    await().until(() -> unseal != null);

    System.out.println("Vault Server initialized (but sealed)");
    System.out.println("Root token: " + token);
    System.out.println("Unseal key: " + unseal);
}