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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:npanday.plugin.wix.CandleMojo.java

public void execute() throws MojoExecutionException {
    String paths = "";
    for (int x = 0; x < sourceFiles.length; x++) {
        File f = sourceFiles[x];//  w w  w  .  j  av a2s. c  o  m
        if (!f.exists()) {
            throw new MojoExecutionException("Source file does not exist " + sourceFiles[x]);
        } else {
            paths = paths + sourceFiles[x].getAbsolutePath() + " ";
        }
    }

    try {
        String line = "candle " + paths;
        CommandLine commandLine = CommandLine.parse(line);
        DefaultExecutor executor = new DefaultExecutor();
        int exitValue = executor.execute(commandLine);

        if (exitValue != 0) {
            throw new MojoExecutionException("Problem executing candle, return code " + exitValue);
        }

    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing candle", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing candle", e);
    }
}

From source file:npanday.plugin.wix.LightMojo.java

public void execute() throws MojoExecutionException {

    String paths = "";
    for (int x = 0; x < objectFiles.length; x++) {
        File f = objectFiles[x];/*from   w ww .j av  a 2 s  .c om*/
        if (!f.exists()) {
            throw new MojoExecutionException("Object file does not exist " + objectFiles[x]);
        } else {
            paths = paths + objectFiles[x].getAbsolutePath() + " ";
        }
    }

    try {
        String line = "light " + paths;

        if (outputFile != null) {
            line = line + " -o " + outputFile;
        }

        CommandLine commandLine = CommandLine.parse(line);
        DefaultExecutor executor = new DefaultExecutor();
        int exitValue = executor.execute(commandLine);

        if (exitValue != 0) {
            throw new MojoExecutionException("Problem executing light, return code " + exitValue);
        }

    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing light", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing light", e);
    }
}

From source file:org.apache.bigtop.itest.hive.HiveHelper.java

public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) {

    System.out.println("Executing command:");
    System.out.println(commandline.toString());
    Map<String, String> env = null;
    Map<String, String> entry = new HashMap<String, String>();
    try {//  www.j a v a2  s . c  o m
        env = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to get process environment: " + e1.getMessage());
        e1.printStackTrace();
    }
    if (envVars != null) {
        for (String key : envVars.keySet()) {
            env.put(key, envVars.get(key));
        }
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandline, env, resultHandler);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    }

    try {
        resultHandler.waitFor();
        /*System.out.println("Command output: "+outputStream.toString());*/
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        return entry;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        /*System.out.println("Command output: "+outputStream.toString());*/
        LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        e.printStackTrace();
        return entry;
    }
}

From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java

protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);/* w  ww  . j  av  a 2 s  .c o  m*/

    if (execCommand.getWorkingDir() != null) {
        executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile());
    }
    if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) {
        executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout()));
    }
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    return executor;
}

From source file:org.apache.cloudstack.wix.HeatMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from   w w w.  j a va  2 s  . c o m
        CommandLine commandLine = new CommandLine("heat");

        if (dir != null && !dir.trim().isEmpty()) {
            commandLine.addArgument("dir");
            commandLine.addArgument(dir);
        }

        commandLine.addArgument("-gg");
        commandLine.addArgument("-cg");
        commandLine.addArgument(componentGroup);
        commandLine.addArgument("-ke");
        commandLine.addArgument("-sfrag");

        if (template == null || template.trim().isEmpty()) {
            commandLine.addArgument("-template");
            commandLine.addArgument("fragment");
        } else {
            commandLine.addArgument("-template");
            commandLine.addArgument(template);
        }

        if (outputFile != null) {
            commandLine.addArgument("-out");
            commandLine.addArgument(outputFile.getAbsolutePath());
        }

        if (directoryName != null) {
            commandLine.addArgument("-dr");
            commandLine.addArgument(directoryName);
        }

        if (vars != null) {
            commandLine.addArguments(vars, false);
        }

        DefaultExecutor executor = new DefaultExecutor();
        getLog().debug("working directory " + commandLine.toString());
        executor.setWorkingDirectory(getWorkingDirectory(workingDirectory));
        int exitValue = executor.execute(commandLine);

        if (exitValue != 0) {
            throw new MojoExecutionException("Problem executing heat, return code " + exitValue);
        }

    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    }
}

From source file:org.apache.drill.exec.client.DrillClient.java

/**
 * Run external script/*from w  ww  .ja v a2s.c o  m*/
 *
 * @param command
 */
public void runScript(String command) {
    //System.out.println("RUNNING COMMAND: " + command);
    String sCommandString = command;
    CommandLine oCmdLine = CommandLine.parse(sCommandString);
    DefaultExecutor oDefaultExecutor = new DefaultExecutor();
    oDefaultExecutor.setExitValue(0);
    try {
        int iExitValue = oDefaultExecutor.execute(oCmdLine);
    } catch (ExecuteException e) {
        System.err.println("Execution failed.");
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("permission denied.");
        e.printStackTrace();
    }
}

From source file:org.apache.falcon.regression.core.util.ExecUtil.java

public static ExecResult executeCommand(CommandLine commandLine) {
    LOGGER.info("Command to be executed: " + commandLine);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(5 * 1000)); //timeout of 5 seconds
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));
    int exitVal = 1;
    String exception = "";
    try {/*  ww  w  .  jav  a  2 s.  c  o m*/
        exitVal = executor.execute(commandLine);
    } catch (IOException e) {
        LOGGER.warn("Caught exception: " + e);
        exception = e.toString();
    }
    final String output = outStream.toString();
    String errors = errStream.toString();
    errors = errors.isEmpty() ? exception : errors;

    LOGGER.info("exitVal: " + exitVal);
    LOGGER.info("output: " + output);
    LOGGER.info("errors: " + errors);
    return new ExecResult(commandLine, exitVal, output.trim(), errors.trim());
}

From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//from ww  w . ja  va 2s. c  o  m

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();
    res.exitcode = executor.execute(cmd, execEnv(env));
    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);

    return res;
}

From source file:org.apache.hive.hcatalog.templeton.StreamOutputWriter.java

private ExecBean auxRun(String program, List<String> args, Map<String, String> env)
        throws NotAuthorizedException, ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);//w  w  w.ja  v  a2 s . c o  m

    // Setup stdout and stderr
    int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1);
    ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes);
    ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes);
    executor.setStreamHandler(new PumpStreamHandler(outStream, errStream));

    // Only run for N milliseconds
    int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);

    CommandLine cmd = makeCommandLine(program, args);

    LOG.info("Running: " + cmd);
    ExecBean res = new ExecBean();

    res.exitcode = executor.execute(cmd, execEnv(env));

    String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME);
    res.stdout = outStream.toString(enc);
    res.stderr = errStream.toString(enc);
    try {
        watchdog.checkException();
    } catch (Exception ex) {
        LOG.error("Command: " + cmd + " failed. res=" + res, ex);
    }
    if (watchdog.killedProcess()) {
        String msg = " was terminated due to timeout(" + timeout + "ms).  See " + AppConfig.EXEC_TIMEOUT_NAME
                + " property";
        LOG.warn("Command: " + cmd + msg + " res=" + res);
        res.stderr += " Command " + msg;
    }
    if (res.exitcode != 0) {
        LOG.info("Command: " + cmd + " failed. res=" + res);
    }
    return res;
}

From source file:org.apache.karaf.decanter.collector.system.SystemCollector.java

@Override
public void run() {
    if (properties != null) {
        String karafName = System.getProperty("karaf.name");
        String hostAddress = null;
        String hostName = null;/*from   w  ww . java  2  s. c  o m*/
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            // nothing to do
        }
        Enumeration<String> keys = properties.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            try {
                if (key.startsWith("command.")) {
                    HashMap<String, Object> data = new HashMap<>();
                    String command = (String) properties.get(key);
                    LOGGER.debug("Executing {} ({})", command, key);
                    CommandLine cmdLine = CommandLine.parse(command);
                    DefaultExecutor executor = new DefaultExecutor();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
                    executor.setStreamHandler(streamHandler);
                    data.put("timestamp", System.currentTimeMillis());
                    data.put("type", "system");
                    data.put("karafName", karafName);
                    data.put("hostAddress", hostAddress);
                    data.put("hostName", hostName);
                    executor.execute(cmdLine);
                    outputStream.flush();
                    String output = outputStream.toString();
                    if (output.endsWith("\n")) {
                        output = output.substring(0, output.length() - 1);
                    }
                    // try to convert to number
                    try {
                        if (output.contains(".")) {
                            Double value = Double.parseDouble(output);
                            data.put(key, value);
                        } else {
                            Integer value = Integer.parseInt(output);
                            data.put(key, value);
                        }
                    } catch (NumberFormatException e) {
                        data.put(key, outputStream.toString());
                    }
                    streamHandler.stop();
                    Event event = new Event("decanter/collect/system/" + key.replace(".", "_"), data);
                    eventAdmin.postEvent(event);
                    try {
                        outputStream.close();
                    } catch (Exception e) {
                        // nothing to do
                    }
                }
            } catch (Exception e) {
                LOGGER.warn("Command {} execution failed", key, e);
            }
        }
    }
}