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) 

Source Link

Document

Add multiple arguments.

Usage

From source file:io.takari.maven.testing.executor.ForkedLauncher.java

public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory,
        File workingDirectory, File logFile) throws IOException, LauncherException {
    String javaHome;/*  w ww . j ava2s. c o m*/
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        javaHome = System.getProperty("java.home");
    } else {
        javaHome = envVars.get("JAVA_HOME");
    }

    File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java");

    CommandLine cli = new CommandLine(executable);
    cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath());
    cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath());
    cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath());
    cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath());
    cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher");

    cli.addArguments(args.toArray(new String[args.size()]));
    if (extensions != null && !extensions.isEmpty()) {
        cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions));
    }

    cli.addArguments(cliArgs);

    Map<String, String> env = new HashMap<>();
    if (mavenHome != null) {
        env.put("M2_HOME", mavenHome.getAbsolutePath());
    }
    if (envVars != null) {
        env.putAll(envVars);
    }
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        env.put("JAVA_HOME", System.getProperty("java.home"));
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(workingDirectory.getAbsoluteFile());

    try (OutputStream log = new FileOutputStream(logFile)) {
        PrintStream out = new PrintStream(log);
        out.format("Maven Executor implementation: %s\n", getClass().getName());
        out.format("Maven home: %s\n", mavenHome);
        out.format("Build work directory: %s\n", workingDirectory);
        out.format("Environment: %s\n", env);
        out.format("Command line: %s\n\n", cli.toString());
        out.flush();

        PumpStreamHandler streamHandler = new PumpStreamHandler(log);
        executor.setStreamHandler(streamHandler);
        return executor.execute(cli, env); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e);
    }
}

From source file:com.devesion.maven.jsr308.CheckersPlugin.java

/**
 * Plugin Entry point.//from www  .java  2  s . c om
 * 
 * @throws MojoExecutionException exception
 * @throws MojoFailureException exception
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    getLog().info("Executing JSR-308 Checkers");

    if (checkers.size() <= 0) {
        getLog().info("No checkers found, omitting checkers execution");
        return;
    }

    final SourceContext sourceCtx = new SourceContext(compileSourceDirs, includes, excludes);
    final List<String> sources = SourceUtils.getProjectSources(sourceCtx);
    if (sources.isEmpty()) {
        getLog().info("The project does not contains any sources, omitting checkers execution");
        return;
    }

    final CommandLine cl = new CommandLine("java");
    if (checkerJar == null || checkerJar.isEmpty()) {
        checkerJar = ArtifactUtils.getArtifactPath(JSR308_ALL_GROUP_ID, JSR308_ALL_ARTIFACT_ID, dependencies);
        if (checkerJar == null) {
            throw new MojoExecutionException("Cannot find " + JSR308_ALL_GROUP_ID + ":" + JSR308_ALL_ARTIFACT_ID
                    + " artifact jar in the local repository.");
        }
    }

    cl.addArgument("-Xbootclasspath/p:" + checkerJar);
    cl.addArgument("-ea:com.sun.tools");
    if (userJavaParams != null) {
        cl.addArgument(userJavaParams);
    }
    cl.addArgument("-jar");
    cl.addArgument(checkerJar);
    cl.addArgument("-proc:only");

    // adding checkers
    for (String checker : checkers) {
        cl.addArgument("-processor");
        cl.addArgument(checker);
    }

    // adding project sources
    cl.addArguments(sources.toArray(new String[sources.size()]));

    // adding classpath
    final StringBuilder sb = new StringBuilder();
    for (String element : compileClasspathElements) {
        sb.append(element);
        sb.append(File.pathSeparator);
    }

    cl.addArgument("-classpath");
    cl.addArgument(sb.toString());
    if (userJavacParams != null) {
        cl.addArgument(userJavacParams);
    }

    // executing compiler
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(EXIT_CODE_OK);

    try {
        executor.execute(cl);
    } catch (ExecuteException ex) {

        if (failOnError) {
            throw new MojoExecutionException(
                    "Unable to continue because of some errors reported by checkers - " + ex.getMessage());
        } else {
            getLog().error("Some errors has been reported by checkers - " + ex.getMessage());
        }
    } catch (IOException ex) {
        throw new MojoExecutionException("cannot execute checkers", ex);
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Start the TG server synchronously.//from   w ww.j  av a2  s .  c  om
 * 
 * @param timeout
 *            Number of milliseconds allowed to start the server
 * @throws TGStartException Start operation fails
 */
public void start(long timeout) throws TGStartException {

    if (this.configFile == null)
        throw new TGStartException("TGServer - Config file not set");

    if (this.logFile == null)
        this.setLogFile("tgdb_" + this.dbName);

    //this.outStream = new ByteArrayOutputStream(); // reset
    //this.errStream = new ByteArrayOutputStream(); // reset
    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    Executor tgExec = new DefaultExecutor();
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    tgExec.setStreamHandler(psh);
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase });

    System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " "));
    try {
        tgExec.execute(tgCL, resultHandler);
    } catch (IOException ioe) {
        try {
            Thread.sleep(1000); // Make sure output/error fill up
        } catch (InterruptedException ie) {
            ;
        }
        throw new TGStartException(ioe.getMessage());
    }

    if (timeout > 0) {
        Calendar future = Calendar.getInstance();
        future.add(Calendar.MILLISECOND, (int) timeout);
        boolean started = false;
        boolean error = false;
        List<String> acceptedClients = new ArrayList<String>();
        String acceptedClient;
        while (!future.before(Calendar.getInstance())) {
            try {
                Thread.sleep(1000);
                BufferedReader reader = new BufferedReader(new StringReader(this.getOutput()));
                String line = reader.readLine();
                while (line != null) {
                    if (line.contains("Process pid:"))
                        this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12,
                                line.indexOf(",", line.lastIndexOf("Process pid:") + 12))));
                    if (line.contains("[Error]")) {
                        error = true;
                    }
                    if (line.contains("Accepting clients on")) {
                        started = true;
                        acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2);
                        if (!acceptedClients.contains(acceptedClient))
                            acceptedClients.add(acceptedClient);
                    }
                    line = reader.readLine();
                }
                reader.close();
                if (started)
                    break;
            } catch (Exception e) {
                throw new TGStartException("TGServer - " + e.getMessage());
            }
        }
        if (!started)
            throw new TGStartException(
                    "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile);
        else {
            this.running = true;
            System.out.println("TGServer - Started successfully with pid " + this.pid + " :");
            System.out.println("\t\t- Log file: " + this.logFile);
            if (error)
                System.out.println("\t\t- With some error(s) - See log");
            for (String client : acceptedClients)
                System.out.println("\t\t- " + client);
            try {
                this.setBanner(this.getOutput());
            } catch (TGGeneralException tge) {
                throw new TGStartException(tge.getMessage());
            }
        }
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * Initialize the TG server synchronously. This Init operation blocks until
 * it is completed.//www .ja  va  2  s.  c om
 * 
 * @param initFile
 *            TG server init config file
 * @param forceCreation
 *            Force creation. Delete all the data in the db directory first.
 * @param timeout
 *            Number of milliseconds allowed to initialize the server
 * @return the output stream of init operation 
 * @throws TGInitException
 *             Init operation fails or timeout occurs 
 */
public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException {

    File initF = new File(initFile);
    if (!initF.exists())
        throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist");
    try {
        this.setInit(initF);
    } catch (TGGeneralException e) {
        throw new TGInitException(e.getMessage());
    }

    //ByteArrayOutputStream output = new ByteArrayOutputStream();

    PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream());
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));
    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());
    if (forceCreation)
        tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase });
    else
        tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase });

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " "));
    String output = "";
    try {
        tgExec.execute(tgCL);
        output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI())));
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms");
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up

            } catch (InterruptedException ie) {
                ;
            }
            throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output);
        }
    }
    try {
        this.setBanner(output);
    } catch (TGGeneralException tge) {
        throw new TGInitException(tge.getMessage());
    }

    if (output.contains("TGSuccess")) {
        System.out.println("TGServer - Initialized successfully");
        return output;
    } else
        throw new TGInitException("TGServer - Init failed", output);
}

From source file:info.pancancer.arch3.worker.WorkerRunnable.java

/**
 * This function will execute a workflow, based on the content of the Job object that is passed in.
 *
 * @param message/*from   w w  w  .  j a va2 s .c o  m*/
 *            - The message that will be published on the queue when the worker starts running the job.
 * @param job
 *            - The job contains information about what workflow to execute, and how.
 * @return The complete stdout and stderr from the workflow execution will be returned.
 */
private WorkflowResult launchJob(String message, Job job, String seqwareEngine, String seqwareSettingsFile,
        String dockerImage) {
    WorkflowResult workflowResult = null;
    ExecutorService exService = Executors.newFixedThreadPool(2);
    WorkflowRunner workflowRunner = new WorkflowRunner();
    try {

        Path pathToINI = writeINIFile(job);
        resultsChannel.basicPublish(this.resultsQueueName, this.resultsQueueName,
                MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));
        resultsChannel.waitForConfirms();

        //TODO: Parameterize dockerImage
        if (dockerImage == null || dockerImage.trim() == null) {
            dockerImage = "pancancer/seqware_whitestar_pancancer:latest";
        }
        CommandLine cli = new CommandLine("docker");
        cli.addArgument("run");
        List<String> args = new ArrayList<>(
                Arrays.asList("--rm", "-h", "master", "-t", "-v", "/var/run/docker.sock:/var/run/docker.sock",
                        "-v", job.getWorkflowPath() + ":/workflow", "-v", pathToINI + ":/ini", "-v",
                        "/datastore:/datastore", "-v", "/home/" + this.userName + "/.gnos:/home/ubuntu/.gnos"));
        if (seqwareSettingsFile != null) {
            args.addAll(Arrays.asList("-v", seqwareSettingsFile + ":/home/seqware/.seqware/settings"));
        }
        args.addAll(Arrays.asList(dockerImage, "seqware", "bundle", "launch", "--dir", "/workflow", "--ini",
                "/ini", "--no-metadata", "--engine", seqwareEngine));

        String[] argsArray = new String[args.size()];
        cli.addArguments(args.toArray(argsArray));

        WorkerHeartbeat heartbeat = new WorkerHeartbeat();
        heartbeat.setQueueName(this.resultsQueueName);
        // channels should not be shared between threads https://www.rabbitmq.com/api-guide.html#channel-threads
        // heartbeat.setReportingChannel(resultsChannel);
        heartbeat.setSettings(settings);
        heartbeat.setSecondsDelay(
                settings.getDouble(Constants.WORKER_HEARTBEAT_RATE, WorkerHeartbeat.DEFAULT_DELAY));
        heartbeat.setJobUuid(job.getUuid());
        heartbeat.setVmUuid(this.vmUuid);
        heartbeat.setNetworkID(this.networkAddress);
        heartbeat.setStatusSource(workflowRunner);

        long presleep = settings.getLong(Constants.WORKER_PREWORKER_SLEEP, WorkerRunnable.DEFAULT_PRESLEEP);
        long postsleep = settings.getLong(Constants.WORKER_POSTWORKER_SLEEP, WorkerRunnable.DEFAULT_POSTSLEEP);
        long presleepMillis = Base.ONE_SECOND_IN_MILLISECONDS * presleep;
        long postsleepMillis = Base.ONE_SECOND_IN_MILLISECONDS * postsleep;

        workflowRunner.setCli(cli);
        workflowRunner.setPreworkDelay(presleepMillis);
        workflowRunner.setPostworkDelay(postsleepMillis);
        // Submit both
        @SuppressWarnings("unused")
        // We will never actually do submit.get(), because the heartbeat should keep running until it is terminated by
        // exService.shutdownNow().
        Future<?> submit = exService.submit(heartbeat);
        Future<WorkflowResult> workflowResultFuture = exService.submit(workflowRunner);
        // make sure both are complete
        workflowResult = workflowResultFuture.get();
        // don't get the heartbeat if the workflow is complete already

        log.info("Docker execution result: " + workflowResult.getWorkflowStdout());
    } catch (SocketException e) {
        // This comes from trying to get the IP address.
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        // This could be caused by a problem writing the file, or publishing a message to the queue.
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error("Error executing workflow: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        log.error("Workflow may have been interrupted: " + e.getMessage(), e);
    } finally {
        exService.shutdownNow();
    }

    return workflowResult;
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. /* www .j  a  va2  s  . c  o m*/
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. //from   w w w  .  j  a  v  a2s.c  om
 * Admin operation blocks until it is completed.
 * 
 * @param url Url to connect to TG server
 * @param user User name
 * @param pwd User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmdFile TG admin command file - Need to exist before invoking admin
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public String invoke(String url, String user, String pwd, String logFile, String logLevel, String cmdFile,
        int memSize, long timeout) throws TGAdminException {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(this.home + "/bin"));

    CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }
    if (cmdFile == null)
        throw new TGAdminException("TGAdmin - Command file is required.");
    args.add("--file");
    args.add(cmdFile);

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));
    long startProcTime = 0;
    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (!output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server", output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - startProcTime;
    System.out.println(
            "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:net.tkausl.RunMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    File plugins = pluginfolder == null ? new File(serverPath, "plugins") : new File(serverPath, pluginfolder);
    if (!plugins.exists())
        plugins.mkdirs();//from   w ww.j  a  va  2s . co m

    File pluginFile = new File(plugins, fileName + ".dev");
    if (!pluginFile.exists()) {
        try {
            PrintWriter w = new PrintWriter(pluginFile);
            w.print(outputDir);
            w.close();
        } catch (FileNotFoundException ex) {
            throw new MojoExecutionException("Could not write .dev-file");
        }
    }
    Executor ex = new DefaultExecutor();
    CommandLine commandLine = CommandLine.parse("java");
    String execArgs = System.getProperty("exec.args");
    if (execArgs != null && execArgs.trim().length() > 0) {
        commandLine.addArguments(execArgs.split(" "));
    }
    commandLine.addArguments(new String[] { "-jar", serverJar });

    if (pluginfolder != null)
        commandLine.addArguments(new String[] { "--plugins", pluginfolder });

    ex.setWorkingDirectory(serverPath);
    //PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in);
    //ex.setStreamHandler(psh);
    ex.setStreamHandler(new ExecuteStreamHandler() {
        private PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err);
        InputStreamPumper isp;
        Thread ispt;

        public void setProcessInputStream(OutputStream os) throws IOException {
            isp = new InputStreamPumper(System.in, os);
        }

        public void setProcessErrorStream(InputStream is) throws IOException {
            psh.setProcessErrorStream(is);
        }

        public void setProcessOutputStream(InputStream is) throws IOException {
            psh.setProcessOutputStream(is);
        }

        public void start() throws IOException {
            if (isp != null) {
                ispt = new Thread(isp);
                ispt.setDaemon(true);
                ispt.start();
            }
            psh.start();
        }

        public void stop() throws IOException {
            if (ispt != null)
                ispt.interrupt();
            psh.stop();
        }
    });
    try {
        ex.execute(commandLine);
    } catch (IOException ex1) {
        throw new MojoExecutionException("Error in Execution");
    }
}

From source file:org.apache.maven.plugin.cxx.utils.svn.SvnService.java

public static void execSvnCommand(File basedir, Credential cred, String[] specificParams, OutputStream out,
        Log log) throws MojoExecutionException {
    Properties enviro = null;//from   w w w  .  ja  va 2s.  c  o  m
    try {
        enviro = ExecutorService.getSystemEnvVars();
        enviro.put("LC_MESSAGES", "C");
    } catch (IOException e) {
        log.error("Could not assign default system environment variables.", e);
    }

    CommandLine commandLine = ExecutorService.getExecutablePath("svn", enviro, basedir);

    if (cred != null && !StringUtils.isEmpty(cred.getUsername())) {
        commandLine.addArguments(new String[] { "--username", cred.getUsername() });
    }
    if (cred != null && !StringUtils.isEmpty(cred.getPassword())) {
        commandLine.addArguments(new String[] { "--password", cred.getPassword() });
    }
    /* TODO later :
    commandLine.addArguments( new String[] {"--config-dir", "todo" } );
    commandLine.addArgument( "--no-auth-cache" ); 
    commandLine.addArgument( "--non-interactive" );
    commandLine.addArgument( "--trust-server-cert" );
    */

    commandLine.addArguments(specificParams);

    Executor exec = new DefaultExecutor();

    try {
        log.debug("Execute command '" + commandLine + "'");
        int resultCode = ExecutorService.executeCommandLine(exec, commandLine, enviro, out, System.err,
                System.in);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command '" + commandLine + "' execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command '" + commandLine + "' execution failed.", e);
    }
}

From source file:org.apache.sling.testing.serversetup.jarexec.JarExecutor.java

/** Start the jar if not done yet, and setup runtime hook
 *  to stop it.//w w  w  .  ja va2s.  com
 */
public void start() throws Exception {
    final ExecuteResultHandler h = new ExecuteResultHandler() {
        public void onProcessFailed(ExecuteException ex) {
            log.error("Process execution failed:" + ex, ex);
        }

        public void onProcessComplete(int result) {
            log.info("Process execution complete, exit code=" + result);
        }
    };

    final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
    executor = new DefaultExecutor();
    final CommandLine cl = new CommandLine(jvmFullPath);
    if (vmOptions != null && vmOptions.length() > 0) {
        cl.addArguments(vmOptions);
    }
    cl.addArgument("-jar");
    cl.addArgument(jarToExecute.getAbsolutePath());

    // Additional options for the jar that's executed.
    // $JAREXEC_SERVER_PORT$ is replaced our serverPort value
    String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
    if (jarOptions != null && jarOptions.length() > 0) {
        jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
        log.info("Executable jar options: {}", jarOptions);
        cl.addArguments(jarOptions);
    }

    final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
    if (workFolderOption != null && workFolderOption.length() > 0) {
        final File workFolder = new File(workFolderOption);
        if (!workFolder.isDirectory()) {
            throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: "
                    + workFolder.getAbsolutePath());
        }
        log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
        executor.setWorkingDirectory(workFolder);
    }

    String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
    final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);

    if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
        final long start = System.currentTimeMillis();
        log.info("Executing and waiting for result: " + cl);
        final int result = executor.execute(cl);
        final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
        log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
        if (result != expected) {
            throw new ExecutorException("Expected result code " + expected + ", got " + result);
        }
    } else {
        log.info("Executing asynchronously: " + cl);
        executor.setStreamHandler(new PumpStreamHandler());
        final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer(
                "java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
        final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
        log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
        pd.setWaitOnShutdown(waitOnShutdown);
        executor.setProcessDestroyer(pd);
        executor.execute(cl, h);
    }
}