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:org.eclipse.sisu.equinox.launching.internal.DefaultEquinoxLauncher.java

@Override
public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds)
        throws EquinoxLaunchingException {

    String executable = configuration.getJvmExecutable();
    if (executable == null || "".equals(executable)) {
        // use the same JVM as the one used to run Maven (the "java.home" one)
        executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        if (File.separatorChar == '\\') {
            executable = executable + ".exe";
        }/*from  w  w w.j  a  v  a  2 s.co m*/
    }
    CommandLine cli = new CommandLine(executable);

    final boolean handleQuotes = false;
    cli.addArguments(configuration.getVMArguments(), handleQuotes);

    cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes);

    cli.addArguments(configuration.getProgramArguments(), handleQuotes);

    log.info("Command line:\n\t" + cli.toString());

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = null;
    if (forkedProcessTimeoutInSeconds > 0) {
        watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L);
        executor.setWatchdog(watchdog);
    }
    // best effort to avoid orphaned child process
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(configuration.getWorkingDirectory());
    try {
        return executor.execute(cli, getMergedEnvironment(configuration));
    } catch (ExecuteException e) {
        if (watchdog != null && watchdog.killedProcess()) {
            log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed.");
        }
        return e.getExitValue();
    } catch (IOException e) {
        throw new EquinoxLaunchingException(e);
    }
}

From source file:org.evosuite.utils.ProcessLauncher.java

public int launchNewProcess(File baseDir, String cmdString, int timeout)
        throws IOException, ProcessTimeoutException {

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(timeoutWatchdog);

    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input);
    executor.setStreamHandler(streamHandler);
    if (baseDir != null) {
        executor.setWorkingDirectory(baseDir);
    }//from  w ww. j  a  v a  2  s  . co m

    int exitValue;
    try {
        logger.debug("About to execute command " + cmdString);
        exitValue = executor.execute(CommandLine.parse(cmdString));
        if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) {
            // it was killed on purpose by the watchdog
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        }

        return exitValue;
    } catch (ExecuteException e) {
        if (timeoutWatchdog.killedProcess()) {
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        } else {
            throw e;
        }

    }

}

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;/*from   ww  w .j  av  a  2  s.  com*/
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}/*  w w w  .j  ava 2s .c om*/
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}

From source file:org.jboss.tools.windup.runtime.WindupRmiClient.java

public void startWindup(final IProgressMonitor monitor, String jreHome) {
    logInfo("Begin start RHAMT."); //$NON-NLS-1$
    monitor.worked(1);/*from  w  w w.j a va 2 s . c o m*/

    String windupExecutable = WindupRuntimePlugin.computeWindupExecutable();

    if (windupExecutable == null) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not specified."); //$NON-NLS-1$
        return;
    }

    boolean executable = new File(windupExecutable).setExecutable(true);
    if (!executable) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not executable."); //$NON-NLS-1$
        return;
    }

    CommandLine cmdLine = CommandLine.parse(windupExecutable);

    Map<String, String> env = Maps.newHashMap();
    for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
        env.put(entry.getKey(), entry.getValue());
    }
    if (!jreHome.trim().isEmpty()) {
        env.put(JAVA_HOME, jreHome);
    }

    logInfo("Using " + JAVA_HOME + " - " + jreHome);

    cmdLine.addArgument("--startServer"); //$NON-NLS-1$
    cmdLine.addArgument(String.valueOf(getRmiPort()));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    ExecuteResultHandler handler = new ExecuteResultHandler() {
        @Override
        public void onProcessFailed(ExecuteException e) {
            logInfo("The RHAMT process failed:"); //$NON-NLS-1$
            logInfo(e.getMessage()); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }

        @Override
        public void onProcessComplete(int exitValue) {
            logInfo("The RHAMT process has completed."); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }
    };
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            logInfo("Message from RHAMT executor: " + line); //$NON-NLS-1$
            monitor.worked(1);
        }
    }));
    executor.setWatchdog(watchdog);
    executor.setExitValue(1);
    monitor.worked(1);
    try {
        logInfo("Starting RHAMT in server mode..."); //$NON-NLS-1$
        logInfo("Command-line: " + cmdLine); //$NON-NLS-1$
        executor.execute(cmdLine, env, handler);
    } catch (IOException e) {
        WindupRuntimePlugin.log(e);
    }
}

From source file:org.jboss.windup.decorator.java.decompiler.BackupOfJadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {//from w w w. j av a  2s  .  co  m
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    } catch (Exception e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jboss.windup.decorator.java.decompiler.JadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {/*from www  . j  a v a2s  .  com*/
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jfastcgi.client.FastCGIHandler.java

public void startProcess(final String cmd) throws IOException {
    final DefaultExecutor pe = new DefaultExecutor();
    processExecutor = pe;//from   ww  w  . j  a va  2 s .com
    pe.setWatchdog(new ExecuteWatchdog(60000));

    processExecutor.setStreamHandler(new ExecuteStreamHandler() {

        private final Set<StreamLogger> loggers = new HashSet<StreamLogger>();

        public void stop() throws IOException {

        }

        public void start() throws IOException {

        }

        public void setProcessOutputStream(final InputStream is) throws IOException {
            loggers.add(new StreamLogger(is,
                    LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stdout")));
        }

        public void setProcessInputStream(final OutputStream os) throws IOException {

        }

        public void setProcessErrorStream(final InputStream is) throws IOException {
            loggers.add(new StreamLogger(is,
                    LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stderr")));
        }
    });

    getLog().info("Starting external process : " + cmd);
    pe.execute(CommandLine.parse(cmd), new DefaultExecuteResultHandler() {
        @Override
        public void onProcessFailed(final ExecuteException e) {
            super.onProcessFailed(e);
            getLog().error("while running process", e);
        }

        @Override
        public void onProcessComplete(final int exitValue) {
            getLog().info(String.format("external process exited with code %s : %s", exitValue, cmd));
        }
    });

}

From source file:org.mail.bridge.FolderMonitor.java

public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) {
    if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles))
        return;//from   ww  w . j a v  a2 s. c o  m
    LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        CommandLine cmd = CommandLine.parse(config.getInboxScript());
        for (File file : inboxFiles)
            cmd.addArgument(file.getName(), true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out));
        executor.setWatchdog(new ExecuteWatchdog(SCRIPT_TIMEOUT));
        Map<String, String> environment = EnvironmentUtils.getProcEnvironment();
        environment.putAll(config.asEnvironmentMap());
        executor.setWorkingDirectory(new File(System.getProperty("user.dir")));
        executor.execute(cmd, environment);
        LOG.info("Script '{}' successfully finished", config.getInboxScript());
        LOG.debug("Script output:\n{}", out.toString());
    } catch (ExecuteException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
        int c = config.getInboxScriptStopCode();
        if (c != 0 && c == e.getExitValue())
            postMessage(new Main.StopMessage(
                    String.format("Script '%s' exited with code %d that is configured as stop code",
                            config.getInboxScript(), c)));
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
    }
}

From source file:org.mule.test.infrastructure.process.Controller.java

private int executeSyncCommand(String command, String[] args, Map<Object, Object> newEnv, int timeout)
        throws MuleControllerException {
    CommandLine commandLine = new CommandLine(muleBin);
    commandLine.addArgument(command);/*from   ww w.  ja v a 2  s .c o m*/
    commandLine.addArguments(args);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler());
    return doExecution(executor, commandLine, newEnv);
}