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

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

Introduction

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

Prototype

public DefaultExecuteResultHandler() 

Source Link

Document

Constructor.

Usage

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ??  ??  ? ? .//from  w w  w . j  av  a  2 s.  com
 *
 * @param start     ??
 * @param end       ??
 * @param filename ?? ?
 * @return ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static String read(long start, long end, String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter
            .arrayFormat("sed '{},{}!d' {}", new Object[] { start, end, filename }).getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return new String(out.toByteArray());
}

From source file:org.openflamingo.engine.util.FileReader.java

/**
 * ? ?? ??  ? .// w w w  .  j  a v  a  2s .c o m
 *
 * @param filename ??  ? ?
 * @return  ?? ?? 
 * @throws IOException          ?? ??   
 * @throws InterruptedException       
 */
public static int lines(String filename) throws IOException, InterruptedException {
    String command = org.slf4j.helpers.MessageFormatter.arrayFormat("sed -n '$=' {}", new Object[] { filename })
            .getMessage();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(out);

    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(pumpStreamHandler);
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);

    resultHandler.waitFor();

    return Integer.parseInt(new String(out.toByteArray()).trim());
}

From source file:org.openhab.binding.exec.internal.ExecBinding.java

/**
 * <p>Executes <code>commandLine</code>. Sometimes (especially observed on 
 * MacOS) the commandLine isn't executed properly. In that cases another 
 * exec-method is to be used. To accomplish this please use the special 
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this 
 * delimiter it is split into a String[] array and the special exec-method
 * is used.</p>// w w  w .ja  v a 2s .com
 * <p>A possible {@link IOException} gets logged but no further processing is
 * done.</p> 
 * 
 * @param commandLine the command line to execute
 * @return response data from executed command line 
 */
private String executeCommandAndWaitResponse(String commandLine) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.openhab.io.net.exec.ExecUtil.java

/**
 * <p>/*from   w ww. ja  v  a 2 s . c o  m*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        if (resultHandler.getException() != null) {
            logger.warn(resultHandler.getException().getMessage());
        } else {
            logger.debug("exit code '{}', result '{}'", exitCode, retval);
        }

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.opennms.gizmo.k8s.portforward.KubeCtlPortForwardingStrategy.java

@Override
public ForwardedPort portForward(String namespace, String pod, int remotePort) {
    CommandLine cmdLine = new CommandLine("kubectl");
    cmdLine.addArgument("--namespace=${namespace}");
    cmdLine.addArgument("port-forward");
    cmdLine.addArgument("${pod}");
    cmdLine.addArgument(":${remotePort}");

    HashMap<String, String> map = new HashMap<>();
    map.put("namespace", namespace);
    map.put("pod", pod);
    map.put("remotePort", Integer.toString(remotePort));
    cmdLine.setSubstitutionMap(map);/*  ww  w.  j a v a 2s.c om*/

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(out, err);

    DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog wd = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(wd);
    executor.setStreamHandler(psh);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    final int localPort = waitForLocalPort(wd, out, err);
    return new ForwardedPort() {
        @Override
        public InetSocketAddress getAddress() {
            return new InetSocketAddress(InetAddress.getLoopbackAddress(), localPort);
        }

        @Override
        public void close() throws IOException {
            wd.destroyProcess();
        }

        @Override
        public String toString() {
            return String.format("ForwardedPort[localPort=%d]", localPort);
        }
    };
}

From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java

@Override
protected void startApplication() {
    File bundleDirectory = getBundleDirectory();
    List<String> javaOptions = getConfiguration().getJavaOptions();
    List<String> javaAgentOptions = getJavaAgentOptions();

    CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java"));
    if (javaAgentOptions.size() > 0) {
        cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()]));
    }//from w ww .  ja v a 2s  .  c  o  m
    if (javaOptions.size() > 0) {
        cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()]));
    }
    cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments())
            .addArgument("config.yaml");

    log.debug("Launching: {}", cmdLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(bundleDirectory);
    executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis()));

    try {
        executor.setStreamHandler(streamHandler = new PumpStreamHandler(
                new FileOutputStream(new File(bundleDirectory, "output.log"))));
        executor.execute(cmdLine, new DefaultExecuteResultHandler());
    } catch (IOException e) {
        throw Throwables.propagate(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();//ww  w  .  ja  v a 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 {/*ww  w  . java 2 s. co  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:ro.cosu.vampires.client.executors.fork.ForkExecutor.java

@Override
public Result execute(Computation computation) {

    acquireResources();//  ww  w.  j a va2  s  .  co  m

    CommandLine commandLine = getCommandLine(computation.command());

    CollectingLogOutputStream collectingLogOutputStream = new CollectingLogOutputStream();
    PumpStreamHandler handler = new PumpStreamHandler(collectingLogOutputStream);
    executor.setStreamHandler(handler);
    executor.setWatchdog(new ExecuteWatchdog(TIMEOUT_IN_MILIS));
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    LocalDateTime start = LocalDateTime.now();
    int exitCode;
    try {
        executor.execute(commandLine, resultHandler);
    } catch (IOException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    try {
        resultHandler.waitFor();
    } catch (InterruptedException e) {
        LOG.error("failed to exec", resultHandler.getException());
    }

    exitCode = resultHandler.hasResult() ? resultHandler.getExitValue() : -1;

    //TODO take different action for failed commands so we can collect the output (stderr or java exception)

    LocalDateTime stop = LocalDateTime.now();

    long duration = Duration.between(start, stop).toMillis();

    releaseResources();
    return Result.builder().duration(duration).exitCode(exitCode).trace(getTrace(start, stop))
            .output(collectingLogOutputStream.getLines()).build();

}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {//from  ww  w. jav a  2 s .  com
        //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);
    }
}