Example usage for org.apache.commons.exec DefaultExecutor execute

List of usage examples for org.apache.commons.exec DefaultExecutor execute

Introduction

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

Prototype

public void execute(final CommandLine command, final Map<String, String> environment,
        final ExecuteResultHandler handler) throws ExecuteException, IOException 

Source Link

Usage

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

    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.springframework.data.release.io.CommonsExecOsCommandOperations.java

private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent)
        throws IOException {

    StringWriter writer = new StringWriter();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try (WriterOutputStream outputStream = new WriterOutputStream(writer)) {

        String outerCommand = "/bin/bash -lc";

        CommandLine outer = CommandLine.parse(outerCommand);
        outer.addArgument(command, false);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(executionDirectory);
        executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null));
        executor.execute(outer, ENVIRONMENT, resultHandler);

        resultHandler.waitFor();// www .ja  va 2s.c  om

    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }

    return new AsyncResult<CommandResult>(
            new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}

From source file:org.stem.ExternalNode.java

private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env)
        throws MojoExecutionException {
    try {/*from  ww w .j  a  v  a  2  s .c  o  m*/
        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:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {// w w w.  j a v  a2  s .  c  om
        //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);
    }
}