Example usage for org.apache.commons.cli Option hasArg

List of usage examples for org.apache.commons.cli Option hasArg

Introduction

In this page you can find the example usage for org.apache.commons.cli Option hasArg.

Prototype

public boolean hasArg() 

Source Link

Document

Query to see if this Option requires an argument

Usage

From source file:com.bc.fiduceo.matchup.MatchupToolTest.java

@Test
public void testGetOptions() {
    final Options options = MatchupTool.getOptions();
    assertNotNull(options);/*  w  w  w.  jav  a2  s  .c om*/

    final Option helpOption = options.getOption("h");
    assertNotNull(helpOption);
    assertEquals("h", helpOption.getOpt());
    assertEquals("help", helpOption.getLongOpt());
    assertEquals("Prints the tool usage.", helpOption.getDescription());
    assertFalse(helpOption.hasArg());

    final Option configOption = options.getOption("config");
    assertNotNull(configOption);
    assertEquals("c", configOption.getOpt());
    assertEquals("config", configOption.getLongOpt());
    assertEquals("Defines the configuration directory. Defaults to './config'.", configOption.getDescription());
    assertTrue(configOption.hasArg());

    final Option startOption = options.getOption("start");
    assertNotNull(startOption);
    assertEquals("start", startOption.getOpt());
    assertEquals("start-date", startOption.getLongOpt());
    assertEquals("Defines the processing start-date, format 'yyyy-DDD'", startOption.getDescription());
    assertTrue(startOption.hasArg());

    final Option endOption = options.getOption("end");
    assertNotNull(endOption);
    assertEquals("end", endOption.getOpt());
    assertEquals("end-date", endOption.getLongOpt());
    assertEquals("Defines the processing end-date, format 'yyyy-DDD'", endOption.getDescription());
    assertTrue(endOption.hasArg());

    final Option useCaseOption = options.getOption("usecase");
    assertNotNull(useCaseOption);
    assertEquals("u", useCaseOption.getOpt());
    assertEquals("usecase", useCaseOption.getLongOpt());
    assertEquals(
            "Defines the path to the use-case configuration file. Path is relative to the configuration directory.",
            useCaseOption.getDescription());
    assertTrue(useCaseOption.hasArg());
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Method for running the command line application.
 *
 * @param args The arguments passed into main()
 * @throws CommandLineException/* ww w . jav  a2s .c om*/
 */
public void parseAndRun(String args[]) throws CommandLineException {

    // Configure our environment
    configure();

    // Make sure there is a main helper
    if (mainHelper == null) {
        throw new CommandLineException("You must specify the main method with @CommandLineMain");
    }
    CommandLine line = null;
    CommandLineParser parser = null;

    try {
        // Parse the command line
        parser = new DefaultParser();
        line = parser.parse(options, args);
    } catch (ParseException e) {
        throw new CommandLineException("Unable to parse command line", e);
    } finally {
        parser = null;
    }

    // Assume we're continuing
    boolean runMain = true;

    // Loop through all our known options
    for (Map.Entry<Option, CommandLineMethodHelper> entry : optionHelperMap.entrySet()) {

        // See if this option was specified
        Option option = entry.getKey();
        CommandLineMethodHelper helper = entry.getValue();
        boolean present = option.getOpt() == null || option.getOpt().equals("")
                ? line.hasOption(option.getLongOpt())
                : line.hasOption(option.getOpt());
        if (present) {

            // The user specified this option. Now we have to handle the
            // values, if it has any
            if (option.hasArg()) {
                String[] arguments = option.getOpt() == null || option.getOpt().equals("")
                        ? line.getOptionValues(option.getLongOpt())
                        : line.getOptionValues(option.getOpt());
                runMain = helper.invokeMethod(this, arguments) && runMain;
            } else {
                runMain = helper.invokeMethod(this, new String[] {}) && runMain;
            }
        }
    }

    // Now handle all the extra arguments. In order to clean up memory,
    // we get rid of the structures that we needed in order to parse
    if (runMain) {

        // Get a reference to the arguments
        String[] arguments = line.getArgs();

        // Clean up the parsing variables
        line = null;
        optionHelperMap = null;

        // Now call the main method. This means we have to keep
        // the main helper around, but that's small
        mainHelper.invokeMethod(this, arguments);
    }
}

From source file:net.sf.clichart.main.FixedHelpFormatter.java

protected StringBuffer renderOptions(StringBuffer sb, int width, Options options, int leftPad, int descPad) {
    final String lpad = createPadding(leftPad);
    final String dpad = createPadding(descPad);

    //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is
    //long opt; in parallel look for the longest opt string
    //this list will be then used to sort options ascending
    int max = 0;/*from  w w  w.j a va 2s  .c o m*/
    StringBuffer optBuf;
    List prefixList = new ArrayList();
    Option option;

    //List optList = options.helpOptions();
    Collection optionsCollection = options.getOptions();
    List optList = new ArrayList(optionsCollection);

    Collections.sort(optList, new StringBufferComparator());
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuffer(8);

        if (option.getOpt().equals(" ")) {
            optBuf.append(lpad).append("   " + defaultLongOptPrefix).append(option.getLongOpt());
        } else {
            optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt());
            if (option.hasLongOpt()) {
                optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt());
            }

        }

        if (option.hasArg()) {
            if (option.hasArgName()) {
                optBuf.append(" <").append(option.getArgName()).append('>');
            } else {
                optBuf.append(' ');
            }
        }

        prefixList.add(optBuf);
        max = optBuf.length() > max ? optBuf.length() : max;
    }
    int x = 0;
    for (Iterator i = optList.iterator(); i.hasNext();) {
        option = (Option) i.next();
        optBuf = new StringBuffer(prefixList.get(x++).toString());

        if (optBuf.length() < max) {
            optBuf.append(createPadding(max - optBuf.length()));
        }
        optBuf.append(dpad);

        int nextLineTabStop = max + descPad;
        renderWrappedText(sb, width, nextLineTabStop, optBuf.append(option.getDescription()).toString());
        if (i.hasNext()) {
            sb.append(defaultNewLine);
        }
    }

    return sb;
}

From source file:com.buildml.main.BMLAdminMain.java

/**
 * Display a set of options (as defined by the Options class). This methods is used
 * in displaying the help text./*from w w  w. ja  v  a  2 s  . c  o  m*/
 * @param opts A set of command line options, as defined by the Options class.
 */
@SuppressWarnings("unchecked")
private void displayOptions(Options opts) {

    /* obtain a list of all the options */
    Collection<Option> optList = opts.getOptions();

    /* if there are no options for this command ... */
    if (optList.size() == 0) {
        System.err.println("    No options available.");
    }

    /* 
     * Else, we have options to display. Show them in a nicely tabulated
     * format, with the short option name (e.g. -p) and the long option name
     * (--show-pkgs) first, followed by a text description of the option.
     */
    else {
        for (Iterator<Option> iterator = optList.iterator(); iterator.hasNext();) {
            Option thisOpt = iterator.next();
            String shortOpt = thisOpt.getOpt();
            String longOpt = thisOpt.getLongOpt();
            String line = "    ";
            if (shortOpt != null) {
                line += "-" + shortOpt;
            } else {
                line += "  ";
            }
            if (shortOpt != null && longOpt != null) {
                line += " | ";
            } else {
                line += "   ";
            }
            if (longOpt != null) {
                line += "--" + thisOpt.getLongOpt();
            }
            if (thisOpt.hasArg()) {
                line += " <" + thisOpt.getArgName() + ">";
            }
            formattedDisplayLine(line, thisOpt.getDescription());
        }
    }
}

From source file:com.greenpepper.maven.runner.CommandLineRunner.java

@SuppressWarnings("unchecked")
private List<String> parseCommandLine(String[] args)
        throws ArgumentMissingException, IOException, ParseException {
    List<String> parameters = new ArrayList<String>();
    CommandLine commandLine = argumentsParser.parse(args);
    if (commandLine != null) {
        Option[] options = commandLine.getOptions();
        for (Option option : options) {
            if ("v".equals(option.getOpt())) {
                isDebug = true;/*  w  w w . ja v  a  2s . c om*/
                parameters.add("--debug");
            } else if ("p".equals(option.getOpt())) {
                projectDependencyDescriptor = option.getValue();
            } else if ("m".equals(option.getOpt())) {
                usingScopes(option.getValue());
            } else if ("o".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else if ("r".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else {
                parameters.add("--" + option.getLongOpt());
                if (option.hasArg()) {
                    parameters.add(option.getValue());
                }
            }
        }
        parameters.addAll(commandLine.getArgList());
    }
    return parameters;
}

From source file:nl.toolforge.karma.console.CommandRenderer.java

private static StringBuffer printCommand(CommandDescriptor descriptor, Option[] options, boolean showOptions,
        boolean showHelp) {

    StringBuffer buffer = new StringBuffer();
    String commandNameAlias = descriptor.getName() + " (" + descriptor.getAlias() + ")";

    buffer.append(commandNameAlias).append(StringUtils.repeat(" ", COMMAND_FILL - commandNameAlias.length()));
    if (!showOptions) {
        buffer.append(descriptor.getDescription());
    }//  ww w.  j a v  a  2  s.com
    buffer.append("\n");

    if (showOptions) {
        for (int j = 0; j < options.length; j++) {

            Option o = options[j];

            String leftPadding = "   ";

            buffer.append(leftPadding).append("-" + o.getOpt()).append(", --" + o.getLongOpt());

            String args = "";
            if (o.hasArg()) {
                args = " <".concat(o.getArgName()).concat(">");
            }

            // todo when the commands are described with too much of text, then FILL will run out of count ...
            //
            buffer.append(args.concat(StringUtils.repeat(" ", OPTION_FILL - (o.getLongOpt() + args).length())));
            buffer.append(leftPadding);
            if (!o.isRequired()) {
                buffer.append("(Optional) ");
            }
            buffer.append(o.getDescription());
            buffer.append("\n");
        }
    }

    if (showHelp) {
        buffer.append("\n");

        String trimmed = NiftyStringUtils.deleteWhiteSpaceExceptOne(descriptor.getHelp());
        String[] split = NiftyStringUtils.split(trimmed, " ", 120);
        String joined = StringUtils.join(split, "\n");

        buffer.append(joined);
        buffer.append("\n");
    }

    return buffer;
}

From source file:org.apache.cassandra.contrib.stress.Stress.java

/**
 * Printing out help message//w  w  w  . j a v a  2 s. c  o m
 */
public static void printHelpMessage() {
    System.out.println("Usage: ./bin/stress [options]\n\nOptions:");

    for (Object o : Session.availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }
}

From source file:org.apache.cassandra.staleness.Staleness.java

/**
 * Printing out help message/*from  w  w w  .j a  va  2 s. c o  m*/
 */
public static void printHelpMessage() {
    System.out.println("Usage: ./bin/cassandra-staleness [options]\n\nOptions:");

    for (Object o : Session.availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }
}

From source file:org.apache.cassandra.stress.settings.Legacy.java

public static void printHelpMessage() {
    System.out.println("Usage: ./bin/cassandra-stress legacy [options]\n\nOptions:");
    System.out.println("THIS IS A LEGACY SUPPORT MODE");

    for (Object o : availableOptions.getOptions()) {
        Option option = (Option) o;
        String upperCaseName = option.getLongOpt().toUpperCase();
        System.out.println(String.format("-%s%s, --%s%s%n\t\t%s%n", option.getOpt(),
                (option.hasArg()) ? " " + upperCaseName : "", option.getLongOpt(),
                (option.hasArg()) ? "=" + upperCaseName : "", option.getDescription()));
    }//from  ww w .j a  v  a  2 s  .c  o m
}

From source file:org.apache.flink.table.client.config.Deployment.java

/**
 * Parses the given command line options from the deployment properties. Ignores properties
 * that are not defined by options./*w  w  w.j  a v  a  2s.co m*/
 */
public CommandLine getCommandLine(Options commandLineOptions) throws Exception {
    final List<String> args = new ArrayList<>();

    properties.forEach((k, v) -> {
        // only add supported options
        if (commandLineOptions.hasOption(k)) {
            final Option o = commandLineOptions.getOption(k);
            final String argument = "--" + o.getLongOpt();
            // options without args
            if (!o.hasArg()) {
                final Boolean flag = Boolean.parseBoolean(v);
                // add key only
                if (flag) {
                    args.add(argument);
                }
            }
            // add key and value
            else if (!o.hasArgs()) {
                args.add(argument);
                args.add(v);
            }
            // options with multiple args are not supported yet
            else {
                throw new IllegalArgumentException("Option '" + o + "' is not supported yet.");
            }
        }
    });

    return CliFrontendParser.parse(commandLineOptions, args.toArray(new String[args.size()]), true);
}