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

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

Introduction

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

Prototype

public CommandLine addArgument(final String argument, final boolean handleQuoting) 

Source Link

Document

Add a single argument.

Usage

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();//  w w w .j a  v a  2s.com

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

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

From source file:org.stanwood.media.info.MediaFileInfoFetcher.java

private String getCommandOutput(boolean captureStdout, boolean captureStderr, boolean failOnExitCode,
        String command, Object... args) throws StanwoodException {
    CommandLine cmdLine = new CommandLine(command);
    for (Object arg : args) {
        if (arg instanceof File) {
            cmdLine.addArgument(((File) arg).getAbsolutePath(), false);
        } else if (arg instanceof String) {
            cmdLine.addArgument((String) arg, false);
        }//  w  ww.  j  a v  a2 s  .  c o m
    }
    if (log.isDebugEnabled()) {
        log.debug("About to execute: " + cmdLine.toString()); //$NON-NLS-1$
    }
    Executor exec = new DefaultExecutor();
    exec.setExitValues(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, -1 });

    try {
        ByteArrayOutputStream capture = new ByteArrayOutputStream();
        OutputStream out;
        if (captureStdout) {
            out = capture;
        } else {
            out = new LoggerOutputStream(Level.INFO);
        }
        OutputStream err;
        ;
        if (captureStderr) {
            err = capture;
        } else {
            err = new LoggerOutputStream(Level.ERROR);
        }
        exec.setStreamHandler(new PumpStreamHandler(out, err));
        int exitCode = exec.execute(cmdLine);
        if (failOnExitCode && exitCode != 0) {
            log.error(capture.toString());
            throw new StanwoodException(MessageFormat
                    .format(Messages.getString("MediaFileInfoFetcher.NON_ZERO"), exitCode, cmdLine.toString())); //$NON-NLS-1$
        }
        return capture.toString();
    } catch (IOException e) {
        throw new StanwoodException(MessageFormat
                .format(Messages.getString("MediaFileInfoFetcher.UnableExecuteSysCmd"), cmdLine.toString()), e); //$NON-NLS-1$
    }
}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM.//from   w  ww  . j  av a  2  s  .  c  o  m
 * NPM can have several executable attached to them, so the 'binary' argument specifies which
 * one has to be executed. Check the 'bin' entry of the package.json file to determine which
 * one you need. 'Binary' is the key associated with the executable to invoke. For example, in
 * <code>
 * <pre>
 *      "bin": {
 *           "coffee": "./bin/coffee",
 *           "cake": "./bin/cake"
 *      },
 *     </pre>
 * </code>
 * <p/>
 * we have two alternatives: 'coffee' and 'cake'.
 *
 * @param binary the key of the binary to invoke
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(String binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("The npm module " + this.npmName + " is not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());
    File npmExec = null;
    try {
        npmExec = findExecutable(binary);
    } catch (IOException | ParseException e) { //NOSONAR
        log.error(e);
    }
    if (npmExec == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - cannot find the JavaScript file " + "matching "
                        + binary + " in the " + PACKAGE_JSON + " file");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(npmExec.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM using the given binary file.
 *
 * @param binary the program to run/*from  w w  w  .j ava  2s . c o m*/
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(File binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("NPM " + this.npmName + " not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());

    if (binary == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - the given binary is 'null'.");
    }

    if (!binary.isFile()) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not "
                + "exist: " + binary.getAbsoluteFile() + ".");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(binary.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);

    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}

From source file:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Launches the Wisdom server. This method blocks until the wisdom server shuts down.
 * It uses the {@literal Java} executable directly.
 *
 * @param mojo        the mojo/*from   w w w  .  j  a  v  a2 s  . c  o m*/
 * @param interactive enables the shell prompt
 * @param debug       the debug port (0 to disable it)
 * @param jvmArgs     JVM arguments to add to the `java` command (before the -jar argument).
 * @param destroyer   a process destroyer that can be used to destroy the process, if {@code null}
 *                    a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used.
 * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status
 *                                while being stopped.
 */
public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs,
        ProcessDestroyer destroyer) throws MojoExecutionException {
    // Get java
    File java = ExecUtils.find("java", new File(mojo.javaHome, "bin"));
    if (java == null) {
        throw new MojoExecutionException("Cannot find the java executable");
    }

    CommandLine cmdLine = new CommandLine(java);

    if (debug != 0) {
        cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false);
    }

    if (!Strings.isNullOrEmpty(jvmArgs)) {
        cmdLine.addArguments(jvmArgs, false);
    }

    cmdLine.addArgument("-jar");
    cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar");
    if (interactive) {
        cmdLine.addArgument("--interactive");
    }

    appendSystemPropertiesToCommandLine(mojo, cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (destroyer != null) {
        executor.setProcessDestroyer(destroyer);
    } else {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }

    executor.setWorkingDirectory(mojo.getWisdomRootDirectory());
    if (interactive) {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR
        // Using the interactive mode the framework should be stopped using the 'exit' command,
        // and produce a '0' status.
        executor.setExitValue(0);
    } else {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR
        // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1
        // 137 or 143 is used when stopped by the destroyer.
        executor.setExitValues(new int[] { 1, 137, 143 });
    }
    try {
        mojo.getLog().info("Launching Wisdom Server");
        mojo.getLog().debug("Command Line: " + cmdLine.toString());
        // The message is different whether or not we are in the interactive mode.
        if (interactive) {
            mojo.getLog().info("You are in interactive mode");
            mojo.getLog().info("Hit 'exit' to shutdown");
        } else {
            mojo.getLog().info("Hit CTRL+C to exit");
        }
        if (debug != 0) {
            mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug);
        }
        // Block execution until ctrl+c
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot execute Wisdom", e);
    }
}

From source file:org.wisdom.ractivejs.RactiveJsTemplateCompilerMojo.java

/**
 * Parse the ractive template into a JavaScript file.
 * Run the ractive script from the plugin resource with node, and ractive module.
 *
 * @param template the ractive template file
 * @throws WatchingException if the template cannot be parsed
 *//*  ww w  . jav  a2s . com*/
private void parseTemplate(File template) throws WatchingException {
    File destination = getOutputJSFile(template);

    // Create the destination folder.
    if (!destination.getParentFile().isDirectory()) {
        destination.getParentFile().mkdirs();
    }

    // Parse with Ractive.js
    CommandLine cmdLine = new CommandLine(getNodeManager().getNodeExecutable());
    cmdLine.addArgument(ractiveExec.getAbsolutePath(), false);
    cmdLine.addArgument(ractiveModule.getAbsolutePath(), false);
    cmdLine.addArgument(template.getAbsolutePath(), false);
    cmdLine.addArgument(destination.getAbsolutePath(), false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    PumpStreamHandler streamHandler = new PumpStreamHandler(new LoggedOutputStream(getLog(), false),
            new LoggedOutputStream(getLog(), true));

    executor.setStreamHandler(streamHandler);

    getLog().info("Executing " + cmdLine.toString());

    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new WatchingException("Error during the execution of " + RACTIVE_SCRIPT_NPM_NAME, e);
    }
}

From source file:org.zanata.rest.service.VirusScanner.java

private CommandLine buildCommandLine(File file) {
    CommandLine cmdLine = new CommandLine(SCANNER_NAME);
    if (USING_CLAM) {
        cmdLine.addArguments(CLAMDSCAN_ARGS, false);
    }/* w w w. j  av a 2s.  c  o m*/
    cmdLine.addArgument(file.getPath(), false);
    return cmdLine;
}

From source file:processing.app.debug.Compiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 *///from  ww w. j av a 2s . c  o  m
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, Compiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(_("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(_("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:processing.app.debug.OldCompiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 *//* w w  w . ja  v a2s.com*/
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, OldCompiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(tr("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}