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

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

Introduction

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

Prototype

ExecuteResultHandler

Source Link

Usage

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

/**
 * Starts this server./*from ww  w. ja v  a 2 s  .co  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:de.woq.osgi.java.itestsupport.ContainerRunner.java

public synchronized void start() throws Exception {

    started.set(true);/*www .  jav a  2 s .  co m*/

    Runnable runner = new Runnable() {
        @Override
        public void run() {
            try {

                String command = getContainerCommand();
                String script = findContainerDirectory() + "/bin/" + command;

                LOGGER.info("Using Container start command [{}] with profile [{}].", command, profile);
                LOGGER.info("Start script is [{}].", script);

                CommandLine cl = new CommandLine(script).addArguments(profile);
                executor.execute(cl, new ExecuteResultHandler() {
                    @Override
                    public void onProcessComplete(int exitValue) {
                        latch.countDown();
                    }

                    @Override
                    public void onProcessFailed(ExecuteException e) {
                        latch.countDown();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    new Thread(runner).start();
}

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

/**
 * Starts the subprocess.//from  w w  w  . ja  va 2 s  . c om
 * 
 * @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.k42b3.sacmis.Sacmis.java

private void executeCommand() {
    out.setText("");

    try {//from   www.  j  a  va  2s .c  om
        // save file
        saveFile();

        CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText());

        // set timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setExitValue(this.exitCode);

        this.baos = new ByteArrayOutputStream();

        this.baosErr = new ByteArrayOutputStream();

        if (this.writerStdIn) {
            this.bais = new ByteArrayInputStream(in.getText().getBytes());

            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        } else {
            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr));
        }

        executor.setWatchdog(watchdog);

        executor.execute(commandLine, new ExecuteResultHandler() {

            public void onProcessComplete(int e) {
                out.setText(baos.toString());
            }

            public void onProcessFailed(ExecuteException e) {
                out.setText(baosErr.toString());
            }

        });
    } catch (Exception e) {
        out.setText(e.getMessage());
    }
}

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

private ExecuteResultHandler asynchExecutionHandler() {
    return new ExecuteResultHandler() {
        @Override//from  w ww .ja v a  2s . c o  m
        public void onProcessFailed(ExecuteException ex) {
            throw new RuntimeException("Engine operation failed.", ex);
        }

        @Override
        public void onProcessComplete(int exitValue) {
            context.log.info("Engine process stopped.");
        }
    };
}

From source file:org.apache.sling.testing.serversetup.jarexec.JarExecutor.java

/** Start the jar if not done yet, and setup runtime hook
 *  to stop it./*from ww  w .ja v a2s.  c o  m*/
 */
public void start() throws Exception {
    final ExecuteResultHandler h = new ExecuteResultHandler() {
        public void onProcessFailed(ExecuteException ex) {
            log.error("Process execution failed:" + ex, ex);
        }

        public void onProcessComplete(int result) {
            log.info("Process execution complete, exit code=" + result);
        }
    };

    final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
    executor = new DefaultExecutor();
    final CommandLine cl = new CommandLine(jvmFullPath);
    if (vmOptions != null && vmOptions.length() > 0) {
        cl.addArguments(vmOptions);
    }
    cl.addArgument("-jar");
    cl.addArgument(jarToExecute.getAbsolutePath());

    // Additional options for the jar that's executed.
    // $JAREXEC_SERVER_PORT$ is replaced our serverPort value
    String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
    if (jarOptions != null && jarOptions.length() > 0) {
        jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
        log.info("Executable jar options: {}", jarOptions);
        cl.addArguments(jarOptions);
    }

    final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
    if (workFolderOption != null && workFolderOption.length() > 0) {
        final File workFolder = new File(workFolderOption);
        if (!workFolder.isDirectory()) {
            throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: "
                    + workFolder.getAbsolutePath());
        }
        log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
        executor.setWorkingDirectory(workFolder);
    }

    String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
    final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);

    if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
        final long start = System.currentTimeMillis();
        log.info("Executing and waiting for result: " + cl);
        final int result = executor.execute(cl);
        final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
        log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
        if (result != expected) {
            throw new ExecutorException("Expected result code " + expected + ", got " + result);
        }
    } else {
        log.info("Executing asynchronously: " + cl);
        executor.setStreamHandler(new PumpStreamHandler());
        final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer(
                "java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
        final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
        log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
        pd.setWaitOnShutdown(waitOnShutdown);
        executor.setProcessDestroyer(pd);
        executor.execute(cl, h);
    }
}

From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java

/**
 * Execute shell command/*from w  w w .j  ava  2 s.co m*/
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText, File workingDir) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        if (workingDir != null) {
            exec.setWorkingDirectory(workingDir);
        }
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        log.info("Executing command: " + commandText
                + (workingDir == null ? "" : " at " + workingDir.getCanonicalPath()));
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

/**
 * Execute shell command//from w w  w .ja va 2  s. co  m
 *
 * @param commandText Command string to be executed
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText, int timeout) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentIntegrationTest.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonAgentTestManager.java

/**
 * Execute shell command/*from ww w . ja  v a2  s  .c  o  m*/
 *
 * @param commandText
 */
protected ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(PythonAgentTestManager.class.getResource(PATH_SEP).getPath()
                + PATH_SEP + ".." + PATH_SEP + PYTHON_AGENT_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.stratos.python.cartridge.agent.test.PythonCartridgeAgentTest.java

/**
 * Execute shell command//from  ww  w  . j  a v  a2  s. c om
 *
 * @param commandText
 */
private ByteArrayOutputStreamLocal executeCommand(final String commandText) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        exec.execute(commandline, new ExecuteResultHandler() {
            @Override
            public void onProcessComplete(int i) {
                log.info(commandText + " process completed");
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                log.error(commandText + " process failed", e);
            }
        });
        executorList.put(commandText, exec);
        return outputStream;
    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
}