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: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 a 2  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  ww w.j a  v  a 2s .  c  om
 */
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.GatlingJavaMainCallerByFork.java

@Override
public boolean run(boolean displayCmd, boolean throwFailure) throws Exception {
    List<String> cmd = buildCommand();
    displayCmd(displayCmd, cmd);//from   www.  j ava2  s  .c o  m
    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: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  ww  w  .  j a  v  a2  s.  c om
    return executor;
}

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  a v  a  2s .c om*/
        }
    }

    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:com.sonar.it.jenkins.orchestrator.container.JenkinsWrapper.java

@VisibleForTesting
DefaultExecutor createExecutor(ExecuteWatchdog watchDog) {
    DefaultExecutor newExecutor = new DefaultExecutor();
    newExecutor.setWatchdog(watchDog);//from w w  w .j a  v  a2  s  . c o m
    newExecutor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    return newExecutor;
}

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

@Inject
ExecBuildin(ExecBuildinLogger logger, Executor executor, CommandParser parser) {
    this.log = logger;
    this.executor = executor;
    this.command = null;
    this.env = null;
    this.handler = new DefaultExecuteResultHandler();
    this.destroyer = new ShutdownHookProcessDestroyer();
    this.watchdog = null;
    this.parser = parser;
}

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);
    }// ww  w  . ja  va 2  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:io.takari.maven.plugins.compile.javac.CompilerJavacLauncher.java

private void compile(File options, File output, final Map<File, Resource<File>> sources) throws IOException {
    new CompilerConfiguration(getSourceEncoding(), getCompilerOptions(), sources.keySet()).write(options);

    // use the same JVM as the one used to run Maven (the "java.home" one)
    String executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    if (File.separatorChar == '\\') {
        executable = executable + ".exe";
    }//from   w  ww  .  j  a v a 2  s. c  om

    CommandLine cli = new CommandLine(executable);

    // jvm options
    cli.addArguments(new String[] { "-cp", jar.getAbsolutePath() });
    if (meminitial != null) {
        cli.addArgument("-Xms" + meminitial);
    }
    if (maxmem != null) {
        cli.addArgument("-Xmx" + maxmem);
    }

    // main class and program arguments
    cli.addArgument(CompilerJavacForked.class.getName());
    cli.addArgument(options.getAbsolutePath(), false);
    cli.addArgument(output.getAbsolutePath(), false);

    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(basedir);

    log.debug("External java process command line:\n   {}", cli);
    try {
        executor.execute(cli); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        if (!log.isDebugEnabled()) {
            log.info("External java process command line:\n   {}", cli);
        }
        throw e;
    }

    final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>();

    CompilerOutput.process(output, new CompilerOutputProcessor() {
        @Override
        public void processOutput(File inputFile, File outputFile) {
            outputs.put(outputFile, context.processOutput(outputFile));
        }

        @Override
        public void addMessage(String path, int line, int column, String message, MessageSeverity kind) {
            if (".".equals(path)) {
                context.addPomMessage(message, kind, null);
            } else {
                File file = new File(path);
                Resource<File> resource = sources.get(file);
                if (resource == null) {
                    resource = outputs.get(file);
                }
                if (resource != null) {
                    if (isShowWarnings() || kind != MessageSeverity.WARNING) {
                        resource.addMessage(line, column, message, kind, null);
                    }
                } else {
                    log.warn("Unexpected java resource {}", file);
                }
            }
        }

        @Override
        public void addLogMessage(String message) {
            log.warn(message);
        }
    });
}

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

/**
 * Starts the subprocess.//from ww w . ja  v  a 2  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();
}