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

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

Introduction

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

Prototype

public ShutdownHookProcessDestroyer() 

Source Link

Document

Constructs a ProcessDestroyer and obtains Runtime.addShutdownHook() and Runtime.removeShutdownHook() through reflection.

Usage

From source file:org.codehaus.mojo.cassandra.Utils.java

/**
 * Starts the Cassandra server./*w ww. j  a v  a 2  s  .  co  m*/
 *
 * @param cassandraDir The directory to start the Server process in.
 * @param commandLine  The command line to use to start the Server process.
 * @param environment  The environment to start the Server process with.
 * @param log          The log to send the output to.
 * @return The {@link ExecuteResultHandler} for the started process.
 * @throws MojoExecutionException if something went wrong.
 */
protected static DefaultExecuteResultHandler startCassandraServer(File cassandraDir, CommandLine commandLine,
        Map environment, Log log) throws MojoExecutionException {

    try {
        Executor exec = new DefaultExecutor();
        DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
        exec.setWorkingDirectory(cassandraDir);
        exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

        LogOutputStream stdout = new MavenLogOutputStream(log);
        LogOutputStream stderr = new MavenLogOutputStream(log);

        log.debug("Executing command line: " + commandLine);

        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));

        exec.execute(commandLine, environment, execHandler);

        return execHandler;
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.codehaus.mojo.exec.ExecMojo.java

protected ProcessDestroyer getProcessDestroyer() {
    if (processDestroyer == null) {
        processDestroyer = new ShutdownHookProcessDestroyer();
    }/* ww  w  . j a v  a 2  s . com*/
    return processDestroyer;
}

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";
        }//ww w .j  a  v  a  2  s.c  o 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.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}/*from   ww  w . j a  v a  2  s .  c  o  m*/
 * <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.stem.ExternalNode.java

private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env)
        throws MojoExecutionException {
    try {/*from w w w.  j  a v a2 s. c  om*/
        DefaultExecutor exec = new DefaultExecutor();
        DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
        exec.setWorkingDirectory(nodeDir);
        exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

        LogOutputStream stdout = new MavenLogOutputStream(log);
        LogOutputStream stderr = new MavenLogOutputStream(log);

        log.debug("Executing command line: " + commandLine);

        PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr);
        streamHandler.start();
        exec.setStreamHandler(streamHandler);

        exec.execute(commandLine, env, execHandler);
        //            try
        //            {
        //                execHandler.waitFor();
        //            }
        //            catch (InterruptedException e)
        //            {
        //                e.printStackTrace();
        //            }
        return execHandler;
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Launches the Wisdom server. This method blocks until the wisdom server shuts down.
 * It uses the {@literal Java} executable directly.
 *
 * @param mojo        the mojo//from   w w  w.jav a2  s. c om
 * @param interactive enables the shell prompt
 * @param debug       the debug port (0 to disable it)
 * @param jvmArgs     JVM arguments to add to the `java` command (before the -jar argument).
 * @param destroyer   a process destroyer that can be used to destroy the process, if {@code null}
 *                    a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used.
 * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status
 *                                while being stopped.
 */
public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs,
        ProcessDestroyer destroyer) throws MojoExecutionException {
    // Get java
    File java = ExecUtils.find("java", new File(mojo.javaHome, "bin"));
    if (java == null) {
        throw new MojoExecutionException("Cannot find the java executable");
    }

    CommandLine cmdLine = new CommandLine(java);

    if (debug != 0) {
        cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false);
    }

    if (!Strings.isNullOrEmpty(jvmArgs)) {
        cmdLine.addArguments(jvmArgs, false);
    }

    cmdLine.addArgument("-jar");
    cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar");
    if (interactive) {
        cmdLine.addArgument("--interactive");
    }

    appendSystemPropertiesToCommandLine(mojo, cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (destroyer != null) {
        executor.setProcessDestroyer(destroyer);
    } else {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }

    executor.setWorkingDirectory(mojo.getWisdomRootDirectory());
    if (interactive) {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR
        // Using the interactive mode the framework should be stopped using the 'exit' command,
        // and produce a '0' status.
        executor.setExitValue(0);
    } else {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR
        // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1
        // 137 or 143 is used when stopped by the destroyer.
        executor.setExitValues(new int[] { 1, 137, 143 });
    }
    try {
        mojo.getLog().info("Launching Wisdom Server");
        mojo.getLog().debug("Command Line: " + cmdLine.toString());
        // The message is different whether or not we are in the interactive mode.
        if (interactive) {
            mojo.getLog().info("You are in interactive mode");
            mojo.getLog().info("Hit 'exit' to shutdown");
        } else {
            mojo.getLog().info("Hit CTRL+C to exit");
        }
        if (debug != 0) {
            mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug);
        }
        // Block execution until ctrl+c
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot execute Wisdom", e);
    }
}

From source file:org.zanata.client.commands.ConfigurableCommand.java

/**
 * @throws Exception//www  .  j a  va2s  .  c  om
 *             if any of the commands fail.
 */
private void runSystemCommands(List<String> commands) throws Exception {
    for (String command : commands) {
        log.info("[Running command]$ " + command);
        try {
            DefaultExecutor executor = new DefaultExecutor();
            executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
            CommandLine cmdLine = CommandLine.parse(command);
            int exitValue = executor.execute(cmdLine);

            if (exitValue != 0) {
                throw new Exception("Command returned non-zero exit value: " + exitValue);
            }
            log.info("    Completed with exit value: " + exitValue);
        } catch (java.io.IOException e) {
            throw new Exception("Failed to run command. " + e.getMessage(), e);
        } catch (InterruptedException e) {
            throw new Exception("Interrupted while running command. " + e.getMessage(), e);
        }
    }
}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {//from   w w w  .  j  a  v  a  2s.c  o  m
        //Command to be executed
        CommandLine command = new CommandLine(processParameters[0]);

        String[] params = new String[processParameters.length - 1];
        for (int i = 0; i < processParameters.length - 1; i++) {
            params[i] = processParameters[i + 1];
        }

        //Adding its arguments
        command.addArguments(params);

        //set timeout in seconds
        ExecuteWatchdog watchDog = new ExecuteWatchdog(
                this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000);
        this.watchdog = watchDog;

        //Result Handler for executing the process in a Asynch way
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        //MyResultHandler resultHandler = new MyResultHandler();

        //Using Std out for the output/error stream
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        //This is used to end the process when the JVM exits
        ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

        //Our main command executor
        DefaultExecutor executor = new DefaultExecutor();

        //Setting the properties
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.setWatchdog(watchDog);
        //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status

        //Setting the working directory
        //Use of recursion along with the ls makes this a long running process
        //executor.setWorkingDirectory(new File("/home"));
        executor.setProcessDestroyer(processDestroyer);

        //if set, use the java environment variables when running the command
        if (!this.environment.equals("")) {
            Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment);
            //Executing the command
            executor.execute(command, procEnv, resultHandler);
        } else {
            //Executing the command
            executor.execute(command, resultHandler);
        }

        //The below section depends on your need
        //Anything after this will be executed only when the command completes the execution
        resultHandler.waitFor();

        /*int exitValue = resultHandler.getExitValue();
         System.out.println(exitValue);
         if (executor.isFailure(exitValue)) {
         System.out.println("Execution failed");
         } else {
         System.out.println("Execution Successful");
         }
         System.out.println(outputStream.toString());*/
        //return outputStream.toString();
        if (watchdog.killedProcess()) {
            throw new JobExecutionException("Job Interrupted", new InterruptedException());
        }
        if (executor.isFailure(resultHandler.getExitValue())) {
            ExecuteException ex = resultHandler.getException();
            throw new JobExecutionException(ex.getMessage(), ex);
        }
        return "1";
    } catch (ExecuteException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    } catch (IOException | InterruptedException | JobExecutionException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}