Example usage for org.apache.commons.exec Executor setProcessDestroyer

List of usage examples for org.apache.commons.exec Executor setProcessDestroyer

Introduction

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

Prototype

void setProcessDestroyer(ProcessDestroyer processDestroyer);

Source Link

Document

Get the handler for cleanup of started processes if the main process is going to terminate.

Usage

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//from  w  w w  . ja  v a2 s .  c  o m
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

From source file:name.martingeisse.webide.nodejs.AbstractNodejsServer.java

/**
 * Starts this server.//from   w w w .  j  a  v a 2s.c o  m
 */
public void start() {

    // determine the path of the associated script
    URL url = getScriptUrl();
    if (!url.getProtocol().equals("file")) {
        throw new RuntimeException("unsupported protocol for associated script URL: " + url);
    }
    File scriptFile = new File(url.getPath());

    // build the command line
    CommandLine commandLine = new CommandLine(Configuration.getBashPath());
    commandLine.addArgument("--login");
    commandLine.addArgument("-c");
    commandLine.addArgument("node " + scriptFile.getName(), false);

    // build I/O streams
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);

    // build an environment map that contains the path to the node_modules
    Map<String, String> environment = new HashMap<String, String>();
    environment.put("NODE_PATH", new File("lib/node_modules").getAbsolutePath());

    // run Node.js
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setStreamHandler(streamHandler);
    try {
        executor.setWorkingDirectory(scriptFile.getParentFile());
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
            }

            @Override
            public void onProcessComplete(int exitValue) {
            }

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

}

From source file:io.gatling.mojo.Fork.java

public void run() throws Exception {

    if (propagateSystemProperties) {
        for (Entry<Object, Object> systemProp : System.getProperties().entrySet()) {
            String name = systemProp.getKey().toString();
            String value = systemProp.getValue().toString();
            if (isPropagatableProperty(name)) {
                String escapedValue = StringUtils.escape(value);
                String safeValue = escapedValue.contains(" ") ? '"' + escapedValue + '"' : escapedValue;
                this.jvmArgs.add("-D" + name + "=" + safeValue);
            }/*from  ww w  .  j ava2 s  .  co m*/
        }
    }

    this.jvmArgs.add("-jar");
    this.jvmArgs
            .add(MojoUtils.createBooterJar(classpath, MainWithArgsInFile.class.getName()).getCanonicalPath());

    List<String> command = buildCommand();

    Executor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(javaExecutable);
    for (String arg : command) {
        cl.addArgument(arg, false);
    }

    int exitValue = exec.execute(cl);
    if (exitValue != 0) {
        throw new MojoFailureException("command line returned non-zero value:" + exitValue);
    }
}

From source file:io.gatling.mojo.GatlingJavaMainCallerByFork.java

@Override
public boolean run(boolean displayCmd, boolean throwFailure) throws Exception {
    List<String> cmd = buildCommand();
    displayCmd(displayCmd, cmd);//from w  w  w  .  j ava 2 s .  com
    Executor exec = new DefaultExecutor();

    // err and out are redirected to out
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));

    exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine cl = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        cl.addArgument(cmd.get(i), false);
    }
    try {
        int exitValue = exec.execute(cl);
        if (exitValue != 0) {
            if (throwFailure) {
                throw new MojoFailureException("command line returned non-zero value:" + exitValue);
            }
            return false;
        }
        return true;
    } catch (ExecuteException exc) {
        if (throwFailure) {
            throw exc;
        }
        return false;
    }
}

From source file:com.github.shyiko.hmp.AbstractHadoopMojo.java

protected void executeCommand(HadoopSettings hadoopSettings, String command, String automaticResponseOnPrompt,
        boolean bindProcessDestroyerToShutdownHook) throws IOException {
    if (getLog().isDebugEnabled()) {
        getLog().debug("Executing " + command);
    }/* w  ww  . j av  a2 s  . co m*/
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ExecutionStreamHandler(quiet, automaticResponseOnPrompt));
    executor.setWorkingDirectory(hadoopSettings.getHomeDirectory());
    if (bindProcessDestroyerToShutdownHook) {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }
    executor.execute(CommandLine.parse(command), hadoopSettings.getEnvironment());
}

From source file:name.martingeisse.webide.process.CompanionProcess.java

/**
 * Starts the subprocess./*from w  w  w.j  a v a2 s.  c  o m*/
 * 
 * @throws IOException on I/O errors
 */
public final synchronized void start() throws IOException {
    if (started) {
        throw new IllegalStateException("companion process has already been started");
    }
    started = true;
    onBeforeStart();
    CommandLine commandLine = buildCommandLine();
    Map<String, String> environment = buildEnvironment();
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    configureExecutor(executor);

    boolean successfullyStarted = false;
    try {
        runningProcesses.put(companionId, this);
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
                messageHandler = null;
                runningProcesses.remove(companionId);
                CompanionProcess.this.onProcessFailed(e.getExitValue(), e.getMessage());
            }

            @Override
            public void onProcessComplete(int exitValue) {
                messageHandler = null;
                runningProcesses.remove(companionId);
                CompanionProcess.this.onProcessComplete(exitValue);
            }

        });
        successfullyStarted = true;
    } finally {
        if (!successfullyStarted) {
            runningProcesses.remove(companionId);
        }
    }

    onAfterStart();
}

From source file:com.thinkbiganalytics.spark.shell.MultiUserProcessManager.java

/**
 * Calls kinit to request a new Kerberos ticket if the previous one is about to expire.
 *///from www .j av  a 2s  . c o m
private void refreshKerberosTicket() {
    // Determine if a new ticket is needed
    if (kerberos == null || kerberos.getInitInterval() <= 0
            || kerberosNextInit > DateTimeUtils.currentTimeMillis()) {
        return;
    }

    // Build executor
    final Executor executor = new DefaultExecutor();

    final ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();
    executor.setProcessDestroyer(processDestroyer);

    final Logger outputLogger = LoggerFactory.getLogger(getClass().getName() + ".kinit");
    final LoggerOutputStream outputStream = new LoggerOutputStream(outputLogger);
    final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(kerberos.getInitTimeout()));
    executor.setWatchdog(watchdog);

    // Run kinit to acquire a new ticket
    final CommandLine command = new CommandLine("kinit").addArgument("-kt")
            .addArgument(kerberos.getKeytabLocation()).addArgument(kerberos.getKerberosPrincipal());
    log.debug("Acquiring a new Kerberos ticket with command: {}", command);

    int exitCode;
    try {
        exitCode = executor.execute(command);
    } catch (final IOException e) {
        log.error("Failed to execute kinit", e);
        exitCode = -1;
    }

    // Record next time to acquire ticket
    if (!executor.isFailure(exitCode)) {
        kerberosNextInit = DateTimeUtils.currentTimeMillis()
                + TimeUnit.SECONDS.toMillis(kerberos.getInitInterval());
    } else {
        if (watchdog.killedProcess()) {
            log.error("Failed to acquire a Kerberos ticket within the allotted time: {}",
                    kerberos.getInitTimeout());
        } else {
            log.error("Kinit exited with non-zero status: {}", exitCode);
        }
        kerberosNextInit = DateTimeUtils.currentTimeMillis()
                + TimeUnit.SECONDS.toMillis(kerberos.getRetryInterval());
        throw new IllegalStateException("Failed to acquire a Kerberos ticket");
    }
}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

public Executor start() throws Exception {
    CommandLine startCmd = toEngineCommand(Command.start);
    context.log.info("Start Axon.ivy Engine in folder: " + context.engineDirectory);

    Executor executor = createEngineExecutor();
    executor.setStreamHandler(createEngineLogStreamForwarder(logLine -> findStartEngineUrl(logLine)));
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.execute(startCmd, asynchExecutionHandler());
    waitForEngineStart(executor);//from  w w  w .j av  a2s. com
    return executor;
}

From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {//  w w  w  .j av a2  s .  c o  m
        getLog().info("Skipping mongodb: mongodb.skip==true");
        return;
    }
    if (installation == null) {
        getLog().info("Using mongod from PATH");
    } else {
        getLog().info("Using mongod installed in " + installation);
    }
    getLog().info("Using database root of " + databaseRoot);
    final Logger mongoLogger = Logger.getLogger("com.mongodb");
    Level mongoLevel = mongoLogger.getLevel();
    try {
        mongoLogger.setLevel(Level.SEVERE);
        MongoOptions opts = new MongoOptions();
        opts.autoConnectRetry = false;
        opts.connectionsPerHost = 1;
        opts.connectTimeout = 50;
        opts.socketTimeout = 50;
        Mongo instance;
        try {
            instance = new Mongo(new ServerAddress("localhost", port), opts);
            List<String> databaseNames = instance.getDatabaseNames();
            throw new MojoExecutionException("Port " + port
                    + " is already running a MongoDb instance with the following databases " + databaseNames);
        } catch (MongoException.Network e) {
            // fine... no instance running
        } catch (MongoException e) {
            throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance");
        } catch (UnknownHostException e) {
            // ignore... localhost is always known!
        }
    } finally {
        mongoLogger.setLevel(mongoLevel);
    }

    CommandLine commandLine = null;
    if (installation != null && installation.isDirectory()) {
        File bin = new File(installation, "bin");
        File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
        if (exe.isFile()) {
            commandLine = new CommandLine(exe);
        } else {
            throw new MojoExecutionException("Could not find mongo executables in specified installation: "
                    + installation + " expected to find " + exe + " but it does not exist.");
        }
    }
    if (commandLine == null) {
        commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
    }
    if (databaseRoot.isFile()) {
        throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory");
    }
    if (databaseRoot.isDirectory() && cleanDatabaseRoot) {
        getLog().info("Cleaning database root directory: " + databaseRoot);
        try {
            FileUtils.deleteDirectory(databaseRoot);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e);
        }
    }
    if (!databaseRoot.isDirectory()) {
        getLog().debug("Creating database root directory: " + databaseRoot);
        if (!databaseRoot.mkdirs()) {
            throw new MojoExecutionException("Could not create database root directory " + databaseRoot);
        }
    }

    if (!verbose) {
        commandLine.addArgument("--quiet");
    }

    commandLine.addArgument("--logpath");
    commandLine.addArgument(logPath.getAbsolutePath());
    if (logAppend) {
        commandLine.addArgument("--logappend");
    }

    commandLine.addArgument(auth ? "--auth" : "--noauth");

    commandLine.addArgument("--port");
    commandLine.addArgument(Integer.toString(port));

    commandLine.addArgument("--dbpath");
    commandLine.addArgument(databaseRoot.getAbsolutePath());

    if (additionalArguments != null) {
        for (String aa : additionalArguments) {
            commandLine.addArgument(aa);
        }
    }

    Executor exec = new DefaultExecutor();
    DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
    exec.setWorkingDirectory(databaseRoot);
    ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer());
    exec.setProcessDestroyer(processObserver);

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

    getLog().info("Executing command line: " + commandLine);
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    try {
        exec.execute(commandLine, execHandler);
        getLog().info("Waiting for MongoDB to start...");
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120);
        mongoLevel = mongoLogger.getLevel();
        try {
            mongoLogger.setLevel(Level.SEVERE);
            while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) {
                MongoOptions opts = new MongoOptions();
                opts.autoConnectRetry = false;
                opts.connectionsPerHost = 1;
                opts.connectTimeout = 250;
                opts.socketTimeout = 250;
                Mongo instance;
                try {
                    instance = new Mongo(new ServerAddress("localhost", port), opts);
                    List<String> databaseNames = instance.getDatabaseNames();
                    getLog().info("MongoDb started.");
                    getLog().info("Databases: " + databaseNames);
                } catch (MongoException.Network e) {
                    // ignore, wait and try again
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                    continue;
                } catch (MongoException e) {
                    getLog().info("MongoDb started.");
                    getLog().info("Unable to list databases due to " + e.getMessage());
                }
                break;
            }
        } finally {
            mongoLogger.setLevel(mongoLevel);
        }
        if (execHandler.hasResult()) {
            ExecuteException exception = execHandler.getException();
            if (exception != null) {
                throw new MojoFailureException(exception.getMessage(), exception);
            }
            throw new MojoFailureException(
                    "Command " + commandLine + " exited with exit code " + execHandler.getExitValue());
        }
        Map pluginContext = session.getPluginContext(getPluginDescriptor(), project);
        pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory,
        List<String> compileClasspathElements, String mainClass, String[] clojureArgs)
        throws MojoExecutionException {

    outputDirectory.mkdirs();// w ww.j a  v  a  2  s.  c o m

    String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements);

    final String javaExecutable = getJavaExecutable();
    getLog().debug("Java exectuable used:  " + javaExecutable);
    getLog().debug("Clojure manifest classpath: " + classpath);
    CommandLine cl = null;

    if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS
            && spawnInteractiveConsoleOnWindows) {
        Scanner sc = new Scanner(windowsConsole);
        Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+");
        cl = new CommandLine(sc.findInLine(pattern));
        String param;
        while ((param = sc.findInLine(pattern)) != null) {
            cl.addArgument(param);
        }
        cl.addArgument(javaExecutable);
    } else {
        cl = new CommandLine(javaExecutable);
    }

    if (vmargs != null) {
        cl.addArguments(vmargs, false);
    }

    cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false);

    if (warnOnReflection)
        cl.addArgument("-Dclojure.compile.warn-on-reflection=true");

    cl.addArguments(clojureOptions, false);

    cl.addArgument("-jar");
    File jar;
    if (prependClasses != null && prependClasses.size() > 0) {
        jar = createJar(classpath, prependClasses.get(0));
        cl.addArgument(jar.getAbsolutePath(), false);
        List<String> allButFirst = prependClasses.subList(1, prependClasses.size());
        cl.addArguments(allButFirst.toArray(new String[allButFirst.size()]));
        cl.addArgument(mainClass);
    } else {
        jar = createJar(classpath, mainClass);
        cl.addArgument(jar.getAbsolutePath(), false);
    }

    if (clojureArgs != null) {
        cl.addArguments(clojureArgs, false);
    }

    getLog().debug("Command line: " + cl.toString());

    Executor exec = new DefaultExecutor();
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    //        env.put("path", ";");
    //        env.put("path", System.getProperty("java.home"));

    ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(handler);
    exec.setWorkingDirectory(getWorkingDirectory());
    ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer();
    exec.setProcessDestroyer(destroyer);

    int status;
    try {
        status = exec.execute(cl, env);
    } catch (ExecuteException e) {
        status = e.getExitValue();
    } catch (IOException e) {
        status = 1;
    }

    if (status != 0) {
        throw new MojoExecutionException("Clojure failed.");
    }

}