Example usage for org.apache.commons.exec CommandLine parse

List of usage examples for org.apache.commons.exec CommandLine parse

Introduction

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

Prototype

public static CommandLine parse(final String line) 

Source Link

Document

Create a command line from a string.

Usage

From source file:org.sakuli.actions.environment.CommandLineUtil.java

static public CommandLineResult runCommand(String command, boolean throwException) throws SakuliException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    CommandLineResult result = new CommandLineResult();
    try {//from   w ww .  jav a 2  s .c om
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(outputStream, error));
        int exitCode = executor.execute(CommandLine.parse(command));
        result.setExitCode(exitCode);
        result.setOutput(error.toString() + outputStream.toString());
    } catch (Exception e) {
        if (throwException) {
            throw new SakuliException(e,
                    String.format("Error during execution of command '%s': %s", command, error.toString()));
        }
        result.setExitCode(resolveExitCode(e.getMessage()));
        result.setOutput(e.getMessage());
    }
    return result;
}

From source file:org.sakuli.aop.SahiCommandExecutionAspect.java

/**
 * Due to the fact, the parsing of the sahi method {@link net.sf.sahi.util.Utils#getCommandTokens(String)} won't
 * work correctly, this {@link Around} advice use the Apache libary {@link CommandLine#parse(String)} to modify it.
 * See http://community.sahipro.com/forums/discussion/8552/sahi-os-5-0-and-chrome-user-data-dir-containing-spaces-not-working.
 *
 * @param joinPoint     the {@link ProceedingJoinPoint} of the invoked method
 * @param commandString the original argument as{@link String}
 * @return the result of {@link CommandLine#parse(String)}
 *//*from  w w w  . j  av a 2 s.  co  m*/
@Around("execution(* net.sf.sahi.util.Utils.getCommandTokens(..)) && args(commandString)")
public String[] getCommandTokens(ProceedingJoinPoint joinPoint, String commandString) {
    Logger LOGGER = getLogger(joinPoint);
    CommandLine parsed = CommandLine.parse(commandString);
    String[] tokens = new String[] { parsed.getExecutable() };
    tokens = ArrayUtils.addAll(tokens, parsed.getArguments());
    try {
        Object result = joinPoint.proceed();
        if (result instanceof String[] && !Arrays.equals(tokens, (String[]) result)) {
            if (commandString.startsWith("sh -c \'")) { //exclude this kind of arguments, because the won't parsed correctly
                //LOGGER.info("SAHI-RESULT {}", printArray((Object[]) result));
                //LOGGER.info("SAKULI-RESULT {}", printArray(tokens));
                return (String[]) result;
            }
            LOGGER.info("MODIFIED SAHI COMMAND TOKENS: {} => {}", printArray((String[]) result),
                    printArray(tokens));
        }
    } catch (Throwable e) {
        LOGGER.error("Exception during execution of JoinPoint net.sf.sahi.util.Utils.getCommandTokens", e);
    }
    return tokens;
}

From source file:org.sakuli.aop.SahiCommandExecutionAspectTest.java

@Test
public void testGetCommandTokenNotModifySH() throws Exception {
    String cmd = "sh -c 'ps -ef | grep firefox | grep -v grep'";
    String[] parsed = Utils.getCommandTokens(cmd);
    Iterator<String> it = Arrays.asList(parsed).iterator();
    Assert.assertEquals(it.next(), "sh");
    Assert.assertEquals(it.next(), "-c");
    Assert.assertEquals(it.next(), "ps -ef | grep firefox | grep -v grep");
    //DOUBLE check so the CommanLine.parse really didn't called
    Assert.assertEquals(CommandLine.parse(cmd).getArguments()[1], "\"ps -ef | grep firefox | grep -v grep\"");
}

From source file:org.sikuli.natives.CommandExecutorHelper.java

public static CommandExecutorResult execute(String commandString, int expectedExitValue) throws Exception {
    ByteArrayOutputStream error = new ByteArrayOutputStream();
    ByteArrayOutputStream stout = new ByteArrayOutputStream();
    CommandLine cmd = CommandLine.parse(commandString);
    try {/*from   w w w . jav  a 2s  . co m*/
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(expectedExitValue);
        executor.setStreamHandler(new PumpStreamHandler(stout, error));
        //if exit value != expectedExitValue => Exception
        int exitValue = executor.execute(cmd);
        return new CommandExecutorResult(exitValue, stout.toString(), error.toString());

    } catch (Exception e) {
        int exitValue = -1;
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        }
        throw new CommandExecutorException("error in command " + cmd.toString(),
                new CommandExecutorResult(exitValue, stout.toString(), error.toString()));
    }
}

From source file:org.sikuli.natives.LinuxUtil.java

@Override
public void checkLibAvailability() {
    List<CommandLine> commands = Arrays.asList(CommandLine.parse("wmctrl -m"),
            CommandLine.parse("xdotool version"), CommandLine.parse("killall --version"));
    String msg = "";
    for (CommandLine cmd : commands) {
        try {/*from ww w.  java2 s  .c o m*/
            DefaultExecutor executor = new DefaultExecutor();
            executor.setExitValue(0);
            //suppress system output
            executor.setStreamHandler(new PumpStreamHandler(null));
            executor.execute(cmd);
        } catch (IOException e) {
            String executable = cmd.toStrings()[0];
            if (executable.equals("wmctrl")) {
                wmctrlAvail = false;
            }
            if (executable.equals("xdotool")) {
                xdoToolAvail = false;
            }
            msg += "command '" + executable + "' is not executable\n";
        }
    }
    if (!msg.isEmpty()) {
        msg += "Please check the availability - some features might not work without!";
        Debug.error(msg);
    }
}

From source file:org.sonatype.nexus.yum.internal.task.CommandLineExecutor.java

public int exec(String command) throws IOException {
    LOG.debug("Execute command : {}", command);

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler());

    int exitValue = executor.execute(cmdLine);
    LOG.debug("Execution finished with exit code : {}", exitValue);
    return exitValue;
}

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();/*from   w w  w. j  ava  2 s  . co  m*/

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

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

From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java

private static void launchPhantomJs(String appDir) {
    //        System.out.println("Locating open port for phantomjs...");
    REMOTE_DRIVER_PORT = findFreePort();
    //        System.out.println("Found open port for phantomjs: "+ REMOTE_DRIVER_PORT);

    String executionString = appDir + "phantomjs.exe --proxy-type=none --webdriver-loglevel=info --webdriver="
            + REMOTE_DRIVER_PORT; //--webdriver-loglevel=debug for full js output and phantomjs commands 
    System.out.println("Executing " + executionString);
    CommandLine commandLine = CommandLine.parse(executionString);
    try {//w  w w . ja  v  a2s . c om
        ProcessExecutor.runProcess(appDir, commandLine, new ProcessExecutorHandler() {
            @Override
            public void onStandardOutput(String msg) {
                System.out.println("phantomjs:" + msg);
            }

            @Override
            public void onStandardError(String msg) {
                System.err.println("phantomjs:" + msg);
            }
        }, 20 * 60 * 1000);
    } catch (IOException e) {
        throw new RuntimeException("Error starting phantomjs", e);
    }
}

From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java

/**
 * Execute shell command/*w  ww  .j a  va 2s  .  com*/
 *
 * @param commandText
 */
protected int executeCommand(final String commandText, Map<String, String> environment) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    int result;
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".."
                + PATH_SEP + CONFIGURATOR_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        result = exec.execute(commandline, environment);

    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.zanata.client.commands.ConfigurableCommand.java

/**
 * @throws Exception//from www  .j a v  a2 s . com
 *             if any of the commands fail.
 */
private void runSystemCommands(List<String> commands) throws Exception {
    for (String command : commands) {
        log.info("[Running command]$ " + command);
        try {
            DefaultExecutor executor = new DefaultExecutor();
            executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
            CommandLine cmdLine = CommandLine.parse(command);
            int exitValue = executor.execute(cmdLine);

            if (exitValue != 0) {
                throw new Exception("Command returned non-zero exit value: " + exitValue);
            }
            log.info("    Completed with exit value: " + exitValue);
        } catch (java.io.IOException e) {
            throw new Exception("Failed to run command. " + e.getMessage(), e);
        } catch (InterruptedException e) {
            throw new Exception("Interrupted while running command. " + e.getMessage(), e);
        }
    }
}