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

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

Introduction

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

Prototype

public CommandLine addArguments(final String addArguments, final boolean handleQuoting) 

Source Link

Document

Add multiple arguments.

Usage

From source file:com.github.peterjanes.node.NpmPackMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//*ww  w .  j  a v  a 2s . com*/
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("pack");
    commandArguments.add("./commonjs");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        getLog().debug("Executing command line: " + commandLine);
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }

        Artifact artifact = mavenProject.getArtifact();
        String fileName = String.format("%s-%s.tgz", artifact.getArtifactId(),
                mavenProject.getProperties().getProperty("node.project.version"));
        artifact.setFile(new File(outputDirectory, fileName));
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }//from www.ja va2s  .c om

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            ByteArrayOutputStream stdOut = new ByteArrayOutputStream();
            ByteArrayOutputStream stdErr = new ByteArrayOutputStream();
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));
        }
    });

    return jobId;
}

From source file:com.netflix.spinnaker.halyard.core.job.v1.JobExecutorLocal.java

@Override
public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn,
        ByteArrayOutputStream stdOut, ByteArrayOutputStream stdErr) {
    List<String> tokenizedCommand = jobRequest.getTokenizedCommand();
    if (tokenizedCommand == null || tokenizedCommand.isEmpty()) {
        throw new IllegalArgumentException("JobRequest must include a tokenized command to run");
    }/* ww w. jav a2 s.c om*/

    final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT
            : jobRequest.getTimeoutMillis();

    String jobId = UUID.randomUUID().toString();

    pendingJobSet.add(jobId);

    log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId);

    scheduler.createWorker().schedule(new Action0() {
        @Override
        public void call() {
            PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn);
            CommandLine commandLine;

            log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand);

            // Grab the first element as the command.
            commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0));

            // Treat the rest as arguments.
            String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1,
                    tokenizedCommand.size());

            commandLine.addArguments(arguments, false);

            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) {
                @Override
                public void timeoutOccured(Watchdog w) {
                    // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely
                    // the result of calling watchdog.destroyProcess().
                    if (w != null) {
                        log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms.");

                        cancelJob(jobId);
                    }

                    super.timeoutOccured(w);
                }
            };

            Executor executor = new DefaultExecutor();
            executor.setStreamHandler(pumpStreamHandler);
            executor.setWatchdog(watchdog);
            try {
                executor.execute(commandLine, env, resultHandler);
            } catch (IOException e) {
                throw new RuntimeException("Execution of " + jobId + " failed ", e);
            }

            // Give the job some time to spin up.
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }

            jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler)
                    .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr));

            if (pendingJobSet.contains(jobId)) {
                pendingJobSet.remove(jobId);
            } else {
                // If the job was removed from the set of pending jobs by someone else, its deletion was requested
                jobIdToHandlerMap.remove(jobId);
                watchdog.destroyProcess();
            }
        }
    });

    return jobId;
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments over the pom specification.
 *
 * @throws MojoExecutionException if a failure happens
 *///from   w ww . ja va  2 s .c  om
public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }
    try {
        handleWorkingDirectory();
        String argsProp = getSystemProperty("exec.args");
        List<String> commandArguments = new ArrayList<String>();
        if (hasCommandlineArgs()) {
            handleCommandLineArgs(commandArguments);
        } else if (!StringUtils.isEmpty(argsProp)) {
            handleSystemPropertyArguments(argsProp, commandArguments);
        } else {
            if (arguments != null) {
                handleArguments(commandArguments);
            }
        }
        Map<String, String> enviro = handleSystemEnvVariables();
        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);
        String[] args = commandArguments.toArray(new String[commandArguments.size()]);
        commandLine.addArguments(args, false);
        Executor exec = new DefaultExecutor();
        exec.setWorkingDirectory(workingDirectory);
        fillSuccessCodes(exec);
        getLog().debug("Executing command line: " + commandLine);
        try {
            int resultCode;
            if (outputFile != null) {
                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
                    getLog().warn(
                            "Could not create non existing parent directories for log file: " + outputFile);
                }
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(outputFile);
                    resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
                } finally {
                    IOUtil.close(outputStream);
                }
            } else {
                resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
            }
            if (isResultCodeAFailure(resultCode)) {
                throw new MojoExecutionException(
                        "Result of " + commandLine + " execution is: '" + resultCode + "'.");
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        }
        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}

From source file:com.github.peterjanes.node.NpmTestMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *///w  w w .j  a va 2 s  .c  o m
public void execute() throws MojoExecutionException {
    if (!workingDirectory.exists()) {
        workingDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(workingDirectory);

    Map env = new HashMap();
    try {
        Map systemEnvVars = EnvironmentUtils.getProcEnvironment();
        env.putAll(systemEnvVars);
    } catch (IOException e) {
        getLog().error("Could not assign default system enviroment variables.", e);
    }
    env.put("NODE_PATH", new File(workingDirectory, "node_modules").getAbsolutePath());
    env.put("XUNIT_FILE", outputFile.getAbsolutePath());

    List commandArguments = new ArrayList();
    commandArguments.add("test");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        outputFile.getParentFile().mkdirs();
        getLog().debug("Executing command line " + commandLine + " in directory "
                + workingDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine, env);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments
 * over the pom specification./*from  w w w  .  j  a  va2s  .  co  m*/
 * 
 * @throws MojoExecutionException
 *             if a failure happens
 */
public void execute() throws MojoExecutionException {
    try {
        if (isSkip()) {
            getLog().info("skipping execute as per configuraion");
            return;
        }

        if (basedir == null) {
            throw new IllegalStateException("basedir is null. Should not be possible.");
        }

        String argsProp = getSystemProperty("exec.args");

        List commandArguments = new ArrayList();

        if (hasCommandlineArgs()) {
            String[] args = parseCommandlineArgs();
            for (int i = 0; i < args.length; i++) {
                if (isLongClassPathArgument(args[i])) {
                    // it is assumed that starting from -cp or -classpath
                    // the arguments
                    // are: -classpath/-cp %classpath mainClass
                    // the arguments are replaced with: -jar
                    // $TMP/maven-exec.jar
                    // NOTE: the jar will contain the classpath and the main
                    // class
                    commandArguments.add("-jar");
                    File tmpFile = createJar(computeClasspath(null), args[i + 2]);
                    commandArguments.add(tmpFile.getAbsolutePath());
                    i += 2;
                } else if (CLASSPATH_TOKEN.equals(args[i])) {
                    commandArguments.add(computeClasspathString(null));
                } else {
                    commandArguments.add(args[i]);
                }
            }
        } else if (!isEmpty(argsProp)) {
            getLog().debug("got arguments from system properties: " + argsProp);

            try {
                String[] args = CommandLineUtils.translateCommandline(argsProp);
                commandArguments.addAll(Arrays.asList(args));
            } catch (Exception e) {
                throw new MojoExecutionException("Couldn't parse systemproperty 'exec.args'");
            }
        } else {
            if (arguments != null) {
                for (int i = 0; i < arguments.size(); i++) {
                    Object argument = arguments.get(i);
                    String arg;
                    if (argument == null) {
                        throw new MojoExecutionException("Misconfigured argument, value is null. "
                                + "Set the argument to an empty value if this is the required behaviour.");
                    } else if (argument instanceof String && isLongClassPathArgument((String) argument)) {
                        // it is assumed that starting from -cp or
                        // -classpath the arguments
                        // are: -classpath/-cp %classpath mainClass
                        // the arguments are replaced with: -jar
                        // $TMP/maven-exec.jar
                        // NOTE: the jar will contain the classpath and the
                        // main class
                        commandArguments.add("-jar");
                        File tmpFile = createJar(computeClasspath((Classpath) arguments.get(i + 1)),
                                (String) arguments.get(i + 2));
                        commandArguments.add(tmpFile.getAbsolutePath());
                        i += 2;
                    } else if (argument instanceof Classpath) {
                        Classpath specifiedClasspath = (Classpath) argument;

                        arg = computeClasspathString(specifiedClasspath);
                        commandArguments.add(arg);
                    } else {
                        arg = argument.toString();
                        commandArguments.add(arg);
                    }
                }
            }
        }

        Map enviro = new HashMap();
        try {
            Properties systemEnvVars = CommandLineUtils.getSystemEnvVars();
            enviro.putAll(systemEnvVars);
        } catch (IOException x) {
            getLog().error("Could not assign default system enviroment variables.", x);
        }

        if (environmentVariables != null) {
            Iterator iter = environmentVariables.keySet().iterator();
            while (iter.hasNext()) {
                String key = (String) iter.next();
                String value = (String) environmentVariables.get(key);
                enviro.put(key, value);
            }
        }

        if (workingDirectory == null) {
            workingDirectory = basedir;
        }

        if (!workingDirectory.exists()) {
            getLog().debug("Making working directory '" + workingDirectory.getAbsolutePath() + "'.");
            if (!workingDirectory.mkdirs()) {
                throw new MojoExecutionException(
                        "Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'");
            }
        }

        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);

        Executor exec = new DefaultExecutor();

        String[] args = new String[commandArguments.size()];
        for (int i = 0; i < commandArguments.size(); i++) {
            args[i] = (String) commandArguments.get(i);
        }

        commandLine.addArguments(args, false);

        exec.setWorkingDirectory(workingDirectory);

        // this code ensures the output gets logged vai maven logging, but
        // at the same time prevents
        // partial line output, like input prompts.
        // final Log outputLog = getExecOutputLog();
        // LogOutputStream stdout = new LogOutputStream()
        // {
        // protected void processLine( String line, int level )
        // {
        // outputLog.info( line );
        // }
        // };
        //
        // LogOutputStream stderr = new LogOutputStream()
        // {
        // protected void processLine( String line, int level )
        // {
        // outputLog.info( line );
        // }
        // };
        OutputStream stdout = System.out;
        OutputStream stderr = System.err;

        try {
            getLog().debug("Executing command line: " + commandLine);

            int resultCode = executeCommandLine(exec, commandLine, enviro, stdout, stderr);

            if (isResultCodeAFailure(resultCode)) {
                throw new MojoExecutionException(
                        "Result of " + commandLine + " execution is: '" + resultCode + "'.");
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Command execution failed.", e);

        } catch (IOException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        }

        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}

From source file:kr.motd.maven.exec.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments over the pom specification.
 *
 * @throws MojoExecutionException if a failure happens
 *//*w  w w  .  jav a2s. c  o  m*/
public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }

    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }

    try {

        handleWorkingDirectory();

        String argsProp = getSystemProperty("exec.args");

        List<String> commandArguments = new ArrayList<String>();

        if (hasCommandlineArgs()) {
            handleCommandLineArgs(commandArguments);
        } else if (!StringUtils.isEmpty(argsProp)) {
            handleSystemPropertyArguments(argsProp, commandArguments);
        } else {
            if (arguments != null) {
                handleArguments(commandArguments);
            }
        }

        Map<String, String> enviro = handleSystemEnvVariables();

        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);

        String[] args = commandArguments.toArray(new String[commandArguments.size()]);

        commandLine.addArguments(args, false);

        Executor exec = new DefaultExecutor();
        exec.setWorkingDirectory(workingDirectory);
        fillSuccessCodes(exec);

        getLog().debug("Executing command line: " + commandLine);

        try {
            int resultCode;
            if (outputFile != null) {
                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
                    getLog().warn(
                            "Could not create non existing parent directories for log file: " + outputFile);
                }

                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(outputFile);

                    resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
                } finally {
                    IOUtil.close(outputStream);
                }
            } else {
                resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
            }

            if (isResultCodeAFailure(resultCode)) {
                throw new MojoExecutionException(
                        "Result of " + commandLine + " execution is: '" + resultCode + "'.");
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Command execution failed.", e);

        } catch (IOException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        }

        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}

From source file:com.github.peterjanes.node.AbstractNpmInstallMojo.java

/**
 *
 * @param outputDirectory The working directory for the npm command.
 * @param npmDependencies A comma-separated list of npm packages to install.
 * @param extraArguments Extra arguments to provide to the npm command.
 * @param artifactScope Scope of the artifacts to include.
 * @throws MojoExecutionException if anything unexpected happens.
 *///  w w  w. j  a v a 2 s.c om
void execute(File outputDirectory, String npmDependencies, String extraArguments, ResolutionScope artifactScope)
        throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("install");

    if (null != npmDependencies) {
        String[] packages = npmDependencies.split(",");
        for (String pkg : packages) {
            commandArguments.add(pkg);
        }
    }

    List<Artifact> nodeArtifacts = getNodeArtifacts(artifactScope);
    for (Artifact artifact : nodeArtifacts) {
        commandArguments.add(artifact.getFile().getAbsolutePath());
    }

    if (null != extraArguments) {
        String[] extraArgs = extraArguments.split(" ");
        for (String extraArg : extraArgs) {
            commandArguments.add(extraArg);
        }
    }

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();
    OutputStream stderr = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();

    try {
        getLog().debug(
                "Executing command line " + commandLine + " in directory " + outputDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            System.out.println("STDOUT: " + stdout);
            System.err.println("STDERR: " + stderr);
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory,
        List<String> compileClasspathElements, String mainClass, String[] clojureArgs)
        throws MojoExecutionException {

    outputDirectory.mkdirs();//  w  w w.  j  a  va  2 s.c o  m

    String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements);

    final String javaExecutable = getJavaExecutable();
    getLog().debug("Java exectuable used:  " + javaExecutable);
    getLog().debug("Clojure manifest classpath: " + classpath);
    CommandLine cl = null;

    if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS
            && spawnInteractiveConsoleOnWindows) {
        Scanner sc = new Scanner(windowsConsole);
        Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+");
        cl = new CommandLine(sc.findInLine(pattern));
        String param;
        while ((param = sc.findInLine(pattern)) != null) {
            cl.addArgument(param);
        }
        cl.addArgument(javaExecutable);
    } else {
        cl = new CommandLine(javaExecutable);
    }

    if (vmargs != null) {
        cl.addArguments(vmargs, false);
    }

    cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false);

    if (warnOnReflection)
        cl.addArgument("-Dclojure.compile.warn-on-reflection=true");

    cl.addArguments(clojureOptions, false);

    cl.addArgument("-jar");
    File jar;
    if (prependClasses != null && prependClasses.size() > 0) {
        jar = createJar(classpath, prependClasses.get(0));
        cl.addArgument(jar.getAbsolutePath(), false);
        List<String> allButFirst = prependClasses.subList(1, prependClasses.size());
        cl.addArguments(allButFirst.toArray(new String[allButFirst.size()]));
        cl.addArgument(mainClass);
    } else {
        jar = createJar(classpath, mainClass);
        cl.addArgument(jar.getAbsolutePath(), false);
    }

    if (clojureArgs != null) {
        cl.addArguments(clojureArgs, false);
    }

    getLog().debug("Command line: " + cl.toString());

    Executor exec = new DefaultExecutor();
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    //        env.put("path", ";");
    //        env.put("path", System.getProperty("java.home"));

    ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(handler);
    exec.setWorkingDirectory(getWorkingDirectory());
    ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer();
    exec.setProcessDestroyer(destroyer);

    int status;
    try {
        status = exec.execute(cl, env);
    } catch (ExecuteException e) {
        status = e.getExitValue();
    } catch (IOException e) {
        status = 1;
    }

    if (status != 0) {
        throw new MojoExecutionException("Clojure failed.");
    }

}

From source file:io.selendroid.standalone.android.impl.DefaultAndroidEmulator.java

@Override
public void start(Locale locale, int emulatorPort, Map<String, Object> options) throws AndroidDeviceException {
    if (isEmulatorStarted()) {
        throw new SelendroidException("Error - Android emulator is already started " + this);
    }/*from   w ww. j  a v a2s . c o m*/
    Long timeout = null;
    String emulatorOptions = null;
    String display = null;
    if (options != null) {
        if (options.containsKey(TIMEOUT_OPTION)) {
            timeout = (Long) options.get(TIMEOUT_OPTION);
        }
        if (options.containsKey(DISPLAY_OPTION)) {
            display = (String) options.get(DISPLAY_OPTION);
        }
        if (options.containsKey(EMULATOR_OPTIONS)) {
            emulatorOptions = (String) options.get(EMULATOR_OPTIONS);
        }
    }

    if (display != null) {
        log.info("Using display " + display + " for running the emulator");
    }
    if (timeout == null) {
        timeout = 120000L;
    }
    log.info("Using timeout of '" + timeout / 1000 + "' seconds to start the emulator.");
    this.locale = locale;

    CommandLine cmd = new CommandLine(AndroidSdk.emulator());

    cmd.addArgument("-no-snapshot-save", false);
    cmd.addArgument("-avd", false);
    cmd.addArgument(avdName, false);
    cmd.addArgument("-port", false);
    cmd.addArgument(String.valueOf(emulatorPort), false);
    if (locale != null) {
        cmd.addArgument("-prop", false);
        cmd.addArgument("persist.sys.language=" + locale.getLanguage(), false);
        cmd.addArgument("-prop", false);
        cmd.addArgument("persist.sys.country=" + locale.getCountry(), false);
    }
    if (emulatorOptions != null && !emulatorOptions.isEmpty()) {
        cmd.addArguments(emulatorOptions.split(" "), false);
    }

    long start = System.currentTimeMillis();
    long timeoutEnd = start + timeout;
    try {
        ShellCommand.execAsync(display, cmd);
    } catch (ShellCommandException e) {
        throw new SelendroidException("unable to start the emulator: " + this);
    }
    setSerial(emulatorPort);
    Boolean adbKillServerAttempted = false;

    // Without this one seconds, the call to "isDeviceReady" is
    // too quickly sent while the emulator is still starting and
    // not ready to receive any commands. Because of this the
    // while loops failed and sometimes hung in isDeviceReady function.
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    while (!isDeviceReady()) {
        if (!adbKillServerAttempted && System.currentTimeMillis() - start > 10000) {
            CommandLine adbDevicesCmd = new CommandLine(AndroidSdk.adb());
            adbDevicesCmd.addArgument("devices", false);

            String devices = "";
            try {
                devices = ShellCommand.exec(adbDevicesCmd, 20000);
            } catch (ShellCommandException e) {
                // pass
            }
            if (!devices.contains(String.valueOf(emulatorPort))) {
                CommandLine resetAdb = new CommandLine(AndroidSdk.adb());
                resetAdb.addArgument("kill-server", false);

                try {
                    ShellCommand.exec(resetAdb, 20000);
                } catch (ShellCommandException e) {
                    throw new SelendroidException("unable to kill the adb server");
                }
            }
            adbKillServerAttempted = true;
        }
        if (timeoutEnd >= System.currentTimeMillis()) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        } else {
            throw new AndroidDeviceException("The emulator with avd '" + getAvdName()
                    + "' was not started after " + (System.currentTimeMillis() - start) / 1000 + " seconds.");
        }
    }

    log.info("Emulator start took: " + (System.currentTimeMillis() - start) / 1000 + " seconds");
    log.info("Please have in mind, starting an emulator takes usually about 45 seconds.");
    unlockScreen();

    waitForLauncherToComplete();

    // we observed that emulators can sometimes not be 'fully loaded'
    // if we click on the All Apps button and wait for it to load it is more likely to be in a
    // usable state.
    allAppsGridView();

    waitForLauncherToComplete();
    setWasStartedBySelendroid(true);
}