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

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

Introduction

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

Prototype

int execute(CommandLine command) throws ExecuteException, IOException;

Source Link

Document

Methods for starting synchronous execution.

Usage

From source file:com.impetus.ankush.common.utils.CommandExecutor.java

/**
 * Exec.//from  ww  w .j  a v a  2  s  .c  o m
 *
 * @param command the command
 * @param out the out
 * @param err the err
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws InterruptedException the interrupted exception
 */
public static int exec(String command, OutputStream out, OutputStream err)
        throws IOException, InterruptedException {
    CommandLine cmdLine = CommandLine.parse(command);
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(out, err, null));
    return executor.execute(cmdLine);
}

From source file:hu.bme.mit.trainbenchmark.sql.process.MySqlProcess.java

public static void runScript(final String scriptFile) throws ExecuteException, IOException {
    final Executor executor = new DefaultExecutor();
    final CommandLine commandLine = new CommandLine("/bin/bash");
    commandLine.addArgument(scriptFile, false);
    executor.execute(commandLine);
}

From source file:hu.bme.mit.trainbenchmark.sql.process.MySqlProcess.java

public static void runShell(final String shellCommand) throws ExecuteException, IOException {
    final Executor executor = new DefaultExecutor();
    final CommandLine commandLine = new CommandLine("/bin/bash");
    commandLine.addArgument("-c");
    commandLine.addArgument(shellCommand, false);
    executor.execute(commandLine);
}

From source file:net.ishchenko.idea.nginx.platform.NginxCompileParametersExtractor.java

/**
 * Runs file with -V argument and matches the output against OUTPUT_PATTERN.
 * @param from executable to be run with -V command line argument
 * @return Parameters parsed out from process output
 * @throws PlatformDependentTools.ThisIsNotNginxExecutableException if file could not be run, or
 * output would not match against expected pattern
 *//*from  ww  w .jav  a2 s .  c om*/
public static NginxCompileParameters extract(VirtualFile from)
        throws PlatformDependentTools.ThisIsNotNginxExecutableException {

    NginxCompileParameters result = new NginxCompileParameters();

    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    try {
        executor.setStreamHandler(new PumpStreamHandler(os, os));
        executor.execute(CommandLine.parse(from.getPath() + " -V"));
    } catch (IOException e) {
        throw new PlatformDependentTools.ThisIsNotNginxExecutableException(e);
    }

    String output = os.toString();
    Matcher versionMatcher = Pattern.compile("nginx version: nginx/([\\d\\.]+)").matcher(output);
    Matcher configureArgumentsMatcher = Pattern.compile("configure arguments: (.*)").matcher(output);

    if (versionMatcher.find() && configureArgumentsMatcher.find()) {

        String version = versionMatcher.group(1);
        String params = configureArgumentsMatcher.group(1);

        result.setVersion(version);

        Iterable<String> namevalues = StringUtil.split(params, " ");
        for (String namevalue : namevalues) {
            int eqPosition = namevalue.indexOf('=');
            if (eqPosition == -1) {
                handleFlag(result, namevalue);
            } else {
                handleNameValue(result, namevalue.substring(0, eqPosition),
                        namevalue.substring(eqPosition + 1));
            }
        }

    } else {
        throw new PlatformDependentTools.ThisIsNotNginxExecutableException(
                NginxBundle.message("run.configuration.outputwontmatch"));
    }

    return result;

}

From source file:com.bptselenium.jenkins.BPTSeleniumJenkins.RunCommand.java

public static void runCommand(String command, TaskListener listener, Run<?, ?> build) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine cmdLine = CommandLine.parse(command);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    Executor executor = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    executor.setExitValue(10);//from w ww. j  ava 2  s . com
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        //getting a non-standard execution value, set build result to unstable
        Result result = Result.UNSTABLE;
        if (build.getResult() == null) {
            build.setResult(result);
        } else if (build.getResult().isBetterThan(result)) {
            build.setResult(result.combine(build.getResult()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        listener.getLogger().println(outputStream.toString());
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public static void reset() throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("kill-server");
    LOG.debug("{}", cmdLine.toString());
    Executor executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }//www . jav  a  2 s  .c om
    cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("devices");
    LOG.debug("{}", cmdLine.toString());
    executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

private static void loadAllSerials() {
    SERIALS.clear();//from  w  w w  . j a  v a 2  s  .c om
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        SERIALS.addAll(Lists.newArrayList(serials.split(",")));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().filter((line) -> (line.endsWith("device"))).forEach((line) -> {
            String s = line.split("\\t")[0];
            LOG.info("serial {}", s);
            SERIALS.add(s);
        });
    }
    if (SERIALS.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

private static void loadSerialProductMap() {
    SERIAL_PRODUCT.clear();//from   w  w  w  .  j a  va 2  s. c om
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        Lists.newArrayList(serials.split(",")).forEach(s -> SERIAL_PRODUCT.put(s, "na"));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        cmdLine.addArgument("-l");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().map(line -> StringUtils.split(line, " ", 3))
                .filter(ss -> ss.length == 3 && ss[1].equals("device")).forEach(ss -> {
                    LOG.info("device {} -> {}", ss[0], ss[2]);
                    SERIAL_PRODUCT.put(ss[0], ss[2]);
                });
    }
    if (SERIAL_PRODUCT.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
    SERIALS.addAll(SERIAL_PRODUCT.keySet());
}

From source file:eu.forgestore.ws.util.Utils.java

public static int executeSystemCommand(String cmdStr) {

    CommandLine cmdLine = CommandLine.parse(cmdStr);
    final Executor executor = new DefaultExecutor();
    // create the executor and consider the exitValue '0' as success
    executor.setExitValue(0);/*from  w  ww  .j  a v  a2  s .co m*/
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(out);
    executor.setStreamHandler(streamHandler);

    int exitValue = -1;
    try {
        exitValue = executor.execute(cmdLine);

    } catch (ExecuteException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return exitValue;

}

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Execute given system command with arguments.
 * /*from   w w  w.  j a va 2s.co m*/
 * @param command
 *            to execute
 * @param args
 *            as command arguments
 * @return command output as String, null otherwise
 */
public static String executeCommand(final String command, String... args) {
    if (StringUtils.isNotEmpty(command)) {

        // create string output for executor
        ProcessStringOutput processOutput = new ProcessStringOutput(PROCESS_OUTPUT_LEVEL);
        // create external process
        Executor executor = createExecutor(processOutput);

        // create command line without any arguments
        final CommandLine commandLine = new CommandLine(command);

        if (ArrayUtils.isNotEmpty(args)) {
            // add command arguments
            commandLine.addArguments(args);
        }
        int exitValue = -1;

        try {
            // execute command
            exitValue = executor.execute(commandLine);
        } catch (IOException e) {
            // ignore exception
        }

        if (!executor.isFailure(exitValue)) {
            return processOutput.getOutput();
        }
    }
    return null;
}