Example usage for org.apache.commons.cli OptionBuilder hasOptionalArgs

List of usage examples for org.apache.commons.cli OptionBuilder hasOptionalArgs

Introduction

In this page you can find the example usage for org.apache.commons.cli OptionBuilder hasOptionalArgs.

Prototype

public static OptionBuilder hasOptionalArgs(int numArgs) 

Source Link

Document

The next Option can have the specified number of optional arguments.

Usage

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.spi.CliOptionsBuilder.java

public CliOptionsBuilder hasOptionalArgs(int numArgs) {
    OptionBuilder.hasOptionalArgs(numArgs);
    return this;
}

From source file:cmd.ArgumentHandler.java

/**
 * Parses the options in the command line arguments and returns an array of
 * strings corresponding to the filenames given as arguments only
 *
 * @param args/*from w w  w. ja  va 2s .c om*/
 * @throws org.apache.commons.cli.ParseException
 */
@SuppressWarnings("static-access")
public void parseCommandLineOptions(String[] args) throws ParseException {

    options = new Options();

    options.addOption("h", "help", false, "Help page for command usage");

    options.addOption("s", false, "SubStructure detection");

    options.addOption("a", false, "Add Hydrogen");

    options.addOption("x", false, "Match Atom Type");

    options.addOption("r", false, "Remove Hydrogen");

    options.addOption("z", false, "Ring matching");

    options.addOption("b", false, "Match Bond types (Single, Double etc)");

    options.addOption(
            OptionBuilder.hasArg().withDescription("Query filename").withArgName("filepath").create("q"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Target filename").withArgName("filepath").create("t"));

    options.addOption(OptionBuilder.hasArg().withDescription("Add suffix to the files").withArgName("suffix")
            .create("S"));

    options.addOption("g", false, "create png of the mapping");

    options.addOption(OptionBuilder.hasArg().withDescription("Dimension of the image in pixels")
            .withArgName("WIDTHxHEIGHT").create("d"));

    options.addOption("m", false, "Report all Mappings");

    String filterDescr = "Default: 0, Stereo: 1, " + "Stereo+Fragment: 2, Stereo+Fragment+Energy: 3";
    options.addOption(OptionBuilder.hasArg().withDescription(filterDescr).withArgName("number").create("f"));

    options.addOption("A", false, "Appends output to existing files, else creates new files");

    options.addOption(OptionBuilder.withDescription("Do N-way MCS on the target SD file").create("N"));

    options.addOption(OptionBuilder.hasArg().withDescription("Query type (MOL, SMI, etc)").withArgName("type")
            .create("Q"));

    options.addOption(OptionBuilder.hasArg().withDescription("Target type (MOL, SMI, SMIF, etc)")
            .withArgName("type").create("T"));

    options.addOption(OptionBuilder.hasArg().withDescription("Output the substructure to a file")
            .withArgName("filename").create("o"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Output type (SMI, MOL)").withArgName("type").create("O"));

    options.addOption(OptionBuilder.hasOptionalArgs(2).withValueSeparator().withDescription("Image options")
            .withArgName("option=value").create("I"));

    PosixParser parser = new PosixParser();
    CommandLine line = parser.parse(options, args, true);

    if (line.hasOption('Q')) {
        queryType = line.getOptionValue("Q");
    } //else {
    //            queryType = "MOL";
    //        } //XXX default type?

    if (line.hasOption('T')) {
        targetType = line.getOptionValue("T");
    } else {
        targetType = "MOL";
    }

    if (line.hasOption('a')) {
        this.setApplyHAdding(true);
    }

    if (line.hasOption('r')) {
        this.setApplyHRemoval(true);
    }

    if (line.hasOption('m')) {
        this.setAllMapping(true);
    }

    if (line.hasOption('s')) {
        this.setSubstructureMode(true);
    }

    if (line.hasOption('g')) {
        this.setImage(true);
    }

    if (line.hasOption('b')) {
        this.setMatchBondType(true);
    }

    if (line.hasOption('z')) {
        this.setMatchRingType(true);
    }

    if (line.hasOption('x')) {
        this.setMatchAtomType(true);
    }

    remainingArgs = line.getArgs();

    if (line.hasOption('h') || line.getOptions().length == 0) {
        //            System.out.println("Hello");
        helpRequested = true;
    }

    if (line.hasOption('S')) {
        String[] suffix_reader = line.getOptionValues('S');
        if (suffix_reader.length < 1) {
            System.out.println("Suffix required!");
            helpRequested = true;
        }
        setSuffix(suffix_reader[0]);
        setApplySuffix(true);
    }

    if (line.hasOption('f')) {
        String[] filters = line.getOptionValues('f');
        if (filters.length < 1) {
            System.out.println("Chemical filter required (Ranges: 0 to 3)!");
            helpRequested = true;
        }
        setChemFilter((int) new Integer(filters[0]));
    }

    if (line.hasOption('q')) {
        queryFilepath = line.getOptionValue('q');
    }

    if (line.hasOption('t')) {
        targetFilepath = line.getOptionValue('t');
    }

    if (line.hasOption("A")) {
        this.setAppendMode(true);
    }

    if (line.hasOption("N")) {
        setNMCS(true);
    }

    if (line.hasOption("o")) {
        outputSubgraph = true;
        outputFilepath = line.getOptionValue("o");
    }

    if (line.hasOption("O")) {
        outputFiletype = line.getOptionValue("O");
    } else {
        outputFiletype = "MOL";
    }

    if (line.hasOption("d")) {
        String dimensionString = line.getOptionValue("d");
        if (dimensionString.contains("x")) {
            String[] parts = dimensionString.split("x");
            try {
                setImageWidth(Integer.parseInt(parts[0]));
                setImageHeight(Integer.parseInt(parts[1]));
                System.out.println("set image dim to " + getImageWidth() + "x" + getImageHeight());
            } catch (NumberFormatException nfe) {
                throw new ParseException("Malformed dimension string " + dimensionString);
            }
        } else {
            throw new ParseException("Malformed dimension string " + dimensionString);
        }
    }

    if (line.hasOption("I")) {
        imageProperties = line.getOptionProperties("I");
        if (imageProperties.isEmpty()) {
            // used just "-I" by itself
            isImageOptionHelp = true;
        }
    }
}

From source file:com.bol.crazypigs.HBaseStorage15.java

private static void populateValidOptions() {
    Option loadKey = OptionBuilder.hasOptionalArgs(1).withArgName("loadKey").withLongOpt("loadKey")
            .withDescription("Load Key").create();
    validOptions_.addOption(loadKey);//  w w w.j a  v a  2  s  .c  om
    validOptions_.addOption("gt", true,
            "Records must be greater than this value " + "(binary, double-slash-escaped)");
    validOptions_.addOption("lt", true, "Records must be less than this value (binary, double-slash-escaped)");
    validOptions_.addOption("gte", true, "Records must be greater than or equal to this value");
    validOptions_.addOption("lte", true, "Records must be less than or equal to this value");
    validOptions_.addOption("regex", true, "Record must match this regular expression");
    validOptions_.addOption("cacheBlocks", true, "Set whether blocks should be cached for the scan");
    validOptions_.addOption("caching", true, "Number of rows scanners should cache");
    validOptions_.addOption("limit", true, "Per-region limit");
    validOptions_.addOption("delim", true, "Column delimiter");
    validOptions_.addOption("ignoreWhitespace", true, "Ignore spaces when parsing columns");
    validOptions_.addOption("caster", true, "Caster to use for converting values. A class name, "
            + "HBaseBinaryConverter, or Utf8StorageConverter. For storage, casters must implement LoadStoreCaster.");
    Option noWal = OptionBuilder.hasOptionalArgs(1).withArgName("noWAL").withLongOpt("noWAL").withDescription(
            "Sets the write ahead to false for faster loading. To be used with extreme caution since this could result in data loss (see http://hbase.apache.org/book.html#perf.hbase.client.putwal).")
            .create();
    validOptions_.addOption(noWal);
    validOptions_.addOption("minTimestamp", true, "Record must have timestamp greater or equal to this value");
    validOptions_.addOption("maxTimestamp", true, "Record must have timestamp less then this value");
    validOptions_.addOption("timestamp", true, "Record must have timestamp equal to this value");
    validOptions_.addOption("includeTimestamp", false,
            "Record will include the timestamp after the rowkey on store (rowkey, timestamp, ...)");
    validOptions_.addOption("includeTombstone", false,
            "Record will include a tombstone marker on store after the rowKey and timestamp (if included) (rowkey, [timestamp,] tombstone, ...)");
}

From source file:org.apache.pig.backend.hadoop.hbase.HBaseStorage.java

private static void populateValidOptions() {
    Option loadKey = OptionBuilder.hasOptionalArgs(1).withArgName("loadKey").withLongOpt("loadKey")
            .withDescription("Load Key").create();
    validOptions_.addOption(loadKey);// w  ww  . ja v a  2  s .  c om
    validOptions_.addOption("gt", true,
            "Records must be greater than this value " + "(binary, double-slash-escaped)");
    validOptions_.addOption("lt", true, "Records must be less than this value (binary, double-slash-escaped)");
    validOptions_.addOption("gte", true, "Records must be greater than or equal to this value");
    validOptions_.addOption("lte", true, "Records must be less than or equal to this value");
    validOptions_.addOption("regex", true, "Record must match this regular expression");
    validOptions_.addOption("cacheBlocks", true, "Set whether blocks should be cached for the scan");
    validOptions_.addOption("caching", true, "Number of rows scanners should cache");
    validOptions_.addOption("limit", true, "Per-region limit");
    validOptions_.addOption("maxResultsPerColumnFamily", true,
            "Limit the maximum number of values returned per row per column family");
    validOptions_.addOption("delim", true, "Column delimiter");
    validOptions_.addOption("ignoreWhitespace", true, "Ignore spaces when parsing columns");
    validOptions_.addOption("caster", true, "Caster to use for converting values. A class name, "
            + "HBaseBinaryConverter, or Utf8StorageConverter. For storage, casters must implement LoadStoreCaster.");
    Option noWal = OptionBuilder.hasOptionalArgs(1).withArgName("noWAL").withLongOpt("noWAL").withDescription(
            "Sets the write ahead to false for faster loading. To be used with extreme caution since this could result in data loss (see http://hbase.apache.org/book.html#perf.hbase.client.putwal).")
            .create();
    validOptions_.addOption(noWal);
    validOptions_.addOption("minTimestamp", true, "Record must have timestamp greater or equal to this value");
    validOptions_.addOption("maxTimestamp", true, "Record must have timestamp less then this value");
    validOptions_.addOption("timestamp", true, "Record must have timestamp equal to this value");
    validOptions_.addOption("includeTimestamp", false,
            "Record will include the timestamp after the rowkey on store (rowkey, timestamp, ...)");
    validOptions_.addOption("includeTombstone", false,
            "Record will include a tombstone marker on store after the rowKey and timestamp (if included) (rowkey, [timestamp,] tombstone, ...)");
}

From source file:org.lib4j.cli.Options.java

public static Options parse(final Cli binding, final Class<?> mainClass, final String[] args) {
    final Set<String> requiredNames = new HashSet<>();
    final Map<String, String> nameToAltName = new HashMap<>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    short argumentsMinOccurs = 0;
    short argumentsMaxOccurs = 0;
    final Cli.Arguments cliArguments;
    if (binding != null) {
        cliArguments = binding.getArguments();
        if (cliArguments != null) {
            argumentsMinOccurs = cliArguments.getMinOccurs();
            argumentsMaxOccurs = "unbounded".equals(cliArguments.getMaxOccurs()) ? Short.MAX_VALUE
                    : Short.parseShort(cliArguments.getMaxOccurs());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);//from   w ww.  java2  s . c  om
            }
        }

        if (binding.getOption() != null) {
            for (final Cli.Option option : binding.getOption()) {
                final Cli.Option.Name optionName = option.getName();
                final String longName = optionName.getLong() == null ? null : optionName.getLong();
                final String shortName = optionName.getShort() == null ? null : optionName.getShort();
                final String name = longName != null ? longName : shortName;
                if (longName == null && shortName == null) {
                    logger.error("both [long] and [short] option names are null in cli spec");
                    System.exit(1);
                }

                nameToAltName.put(name, shortName != null ? shortName : longName);
                OptionBuilder.withLongOpt(name == longName ? longName : null);

                // Record which options are required
                if (option.getArgument() != null) {
                    final Cli.Option.Argument argument = option.getArgument();
                    final boolean isRequired = Use.REQUIRED == argument.getUse();
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument.getMaxOccurs() == null ? 1
                            : "unbounded".equals(argument.getMaxOccurs()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument.getMaxOccurs());
                    if (maxOccurs == 1) {
                        if (isRequired)
                            OptionBuilder.hasArgs(1);
                        else
                            OptionBuilder.hasOptionalArgs(1);
                    } else if (maxOccurs == Integer.MAX_VALUE) {
                        if (isRequired)
                            OptionBuilder.hasArgs();
                        else
                            OptionBuilder.hasOptionalArgs();
                    } else {
                        if (isRequired)
                            OptionBuilder.hasArgs(maxOccurs);
                        else
                            OptionBuilder.hasOptionalArgs(maxOccurs);
                    }

                    final char valueSeparator = argument.getValueSeparator() != null
                            ? argument.getValueSeparator().charAt(0)
                            : ' ';
                    OptionBuilder
                            .withArgName(formatArgumentName(argument.getLabel(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option.getDescription() == null) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option.getDescription());
                    if (option.getArgument().getDefault() != null)
                        description.append("\nDefault: ").append(option.getArgument().getDefault());

                    OptionBuilder.withDescription(description.toString());
                }

                apacheOptions.addOption(OptionBuilder.create(shortName));
            }
        }
    } else {
        cliArguments = null;
    }

    final Map<String, Option> optionsMap = new HashMap<>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<>();
        final CommandLineParser parser = new PosixParser();
        do {
            try {
                commandLine = parser.parse(apacheOptions, args);
            } catch (final UnrecognizedOptionException e) {
                if (e.getMessage().startsWith("Unrecognized option: ")) {
                    final String unrecognizedOption = e.getMessage().substring(21);
                    logger.error("Unrecognized option: " + unrecognizedOption);
                    for (int i = 0; i < args.length; i++)
                        if (args[i].equals(unrecognizedOption))
                            args[i] = "--help";
                } else {
                    throw new IllegalArgumentException(e);
                }
            } catch (final org.apache.commons.cli.ParseException e) {
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
            }
        } while (commandLine == null);
    } else {
        specifiedLongNames = null;
    }

    final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null;
    if (arguments != null && arguments.size() > 0) {
        if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) {
            Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
        }
    } else if (argumentsMinOccurs > 0) {
        Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
    }

    if (commandLine != null) {
        for (final org.apache.commons.cli.Option option : commandLine.getOptions()) {
            specifiedLongNames.add(option.getLongOpt());
            if ("help".equals(option.getLongOpt()))
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out);

            final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt();
            optionsMap.put(optionName,
                    option.getValue() != null
                            ? new Option(optionName, option.getValueSeparator(), option.getValues())
                            : new Option(optionName, option.getValueSeparator(), "true"));
        }
    }

    // See if some arguments are missing
    if (requiredNames.size() != 0) {
        if (specifiedLongNames != null)
            requiredNames.removeAll(specifiedLongNames);

        if (requiredNames.size() != 0) {
            final StringBuilder builder = new StringBuilder();
            for (final String longName : requiredNames) {
                final String shortName = nameToAltName.get(longName);
                if (shortName.equals(longName))
                    builder.append("\nMissing argument: -").append(shortName);
                else
                    builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName);
            }

            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
        }
    }

    // Include default values for options that are not specified
    if (binding.getOption() != null) {
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getDefault() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option.getArgument().getValueSeparator();
                    final String defaultValue = option.getArgument().getDefault();
                    optionsMap.put(optionName,
                            valueSeparator != null
                                    ? new Option(optionName, valueSeparator.charAt(0), defaultValue)
                                    : new Option(optionName, defaultValue));
                }
            }
        }
    }

    // Check pattern for specified and default options
    if (binding.getOption() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getPattern() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option.getArgument().getPattern())) {
                            if (option.getName().getLong() == null || option.getName().getShort() == null)
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option.getName().getShort()).append(",--")
                                        .append(option.getName().getLong());

                            builder.append(' ').append(value).append("\n  Required: ")
                                    .append(option.getArgument().getPattern());
                        }
                    }
                }
            }
        }

        if (builder.length() > 0)
            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
    }

    return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null
            : arguments.toArray(new String[arguments.size()]));
}

From source file:org.libx4j.cli.Options.java

public static Options parse(final cli_cli binding, final Class<?> mainClass, final String[] args)
        throws OptionsException {
    final Set<String> requiredNames = new HashSet<String>();
    final Map<String, String> nameToAltName = new HashMap<String, String>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    int argumentsMinOccurs = 0;
    int argumentsMaxOccurs = 0;
    final cli_cli._arguments cliArguments;
    if (binding != null) {
        cliArguments = binding._arguments(0);
        if (!cliArguments.isNull()) {
            argumentsMinOccurs = cliArguments._minOccurs$().text();
            argumentsMaxOccurs = "unbounded".equals(cliArguments._maxOccurs$().text()) ? Integer.MAX_VALUE
                    : Integer.parseInt(cliArguments._maxOccurs$().text());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);/*from w  w w.j a  v  a  2 s.  c om*/
            }
        }

        if (binding._option() != null) {
            for (final cli_cli._option option : binding._option()) {
                final cli_cli._option._name optionName = option._name(0);
                final String longName = optionName._long$().isNull() ? null : optionName._long$().text();
                final String shortName = optionName._short$().isNull() ? null : optionName._short$().text();
                final String name = longName != null ? longName : shortName;
                if (longName == null && shortName == null) {
                    logger.error("both [long] and [short] option names are null in cli spec");
                    System.exit(1);
                }

                nameToAltName.put(name, shortName != null ? shortName : longName);
                OptionBuilder.withLongOpt(name == longName ? longName : null);

                // Record which options are required
                if (option._argument() != null && option._argument().size() != 0) {
                    final cli_cli._option._argument argument = option._argument(0);
                    final boolean isRequired = $cli_use.required.text().equals(argument._use$().text());
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument._maxOccurs$().isNull() ? 1
                            : "unbounded".equals(argument._maxOccurs$().text()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument._maxOccurs$().text());
                    if (maxOccurs == 1) {
                        if (isRequired)
                            OptionBuilder.hasArgs(1);
                        else
                            OptionBuilder.hasOptionalArgs(1);
                    } else if (maxOccurs == Integer.MAX_VALUE) {
                        if (isRequired)
                            OptionBuilder.hasArgs();
                        else
                            OptionBuilder.hasOptionalArgs();
                    } else {
                        if (isRequired)
                            OptionBuilder.hasArgs(maxOccurs);
                        else
                            OptionBuilder.hasOptionalArgs(maxOccurs);
                    }

                    final char valueSeparator = argument._valueSeparator$().text() != null
                            ? argument._valueSeparator$().text().charAt(0)
                            : ' ';
                    OptionBuilder.withArgName(
                            formatArgumentName(argument._label$().text(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option._description(0).isNull()) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option._description(0).text());
                    if (!option._argument(0)._default$().isNull())
                        description.append("\nDefault: ").append(option._argument(0)._default$().text());

                    OptionBuilder.withDescription(description.toString());
                }

                apacheOptions.addOption(OptionBuilder.create(shortName));
            }
        }
    } else {
        cliArguments = null;
    }

    final Map<String, Option> optionsMap = new HashMap<String, Option>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<String>();
        final CommandLineParser parser = new PosixParser();
        do {
            try {
                commandLine = parser.parse(apacheOptions, args);
            } catch (final UnrecognizedOptionException e) {
                if (e.getMessage().startsWith("Unrecognized option: ")) {
                    final String unrecognizedOption = e.getMessage().substring(21);
                    logger.error("Unrecognized option: " + unrecognizedOption);
                    for (int i = 0; i < args.length; i++)
                        if (args[i].equals(unrecognizedOption))
                            args[i] = "--help";
                } else {
                    throw new OptionsException(e);
                }
            } catch (final org.apache.commons.cli.ParseException e) {
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
            }
        } while (commandLine == null);
    } else {
        specifiedLongNames = null;
    }

    final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null;
    if (arguments != null && arguments.size() > 0) {
        if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) {
            Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
        }
    } else if (argumentsMinOccurs > 0) {
        Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
    }

    if (commandLine != null) {
        for (final org.apache.commons.cli.Option option : commandLine.getOptions()) {
            specifiedLongNames.add(option.getLongOpt());
            if ("help".equals(option.getLongOpt()))
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out);

            final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt();
            optionsMap.put(optionName,
                    option.getValue() != null
                            ? new Option(optionName, option.getValueSeparator(), option.getValues())
                            : new Option(optionName, option.getValueSeparator(), "true"));
        }
    }

    // See if some arguments are missing
    if (requiredNames.size() != 0) {
        if (specifiedLongNames != null)
            requiredNames.removeAll(specifiedLongNames);

        if (requiredNames.size() != 0) {
            final StringBuilder builder = new StringBuilder();
            for (final String longName : requiredNames) {
                final String shortName = nameToAltName.get(longName);
                if (shortName.equals(longName))
                    builder.append("\nMissing argument: -").append(shortName);
                else
                    builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName);
            }

            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
        }
    }

    // Include default values for options that are not specified
    if (binding._option() != null) {
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._default$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option._argument(0)._valueSeparator$().text();
                    final String defaultValue = option._argument(0)._default$().text();
                    optionsMap.put(optionName,
                            valueSeparator != null
                                    ? new Option(optionName, valueSeparator.charAt(0), defaultValue)
                                    : new Option(optionName, defaultValue));
                }
            }
        }
    }

    // Check pattern for specified and default options
    if (binding._option() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._pattern$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option._argument(0)._pattern$().text())) {
                            if (option._name(0)._long$().isNull() || option._name(0)._short$().isNull())
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option._name(0)._short$().text()).append(",--")
                                        .append(option._name(0)._long$().text());

                            builder.append(" ").append(value).append("\n  Required: ")
                                    .append(option._argument(0)._pattern$().text());
                        }
                    }
                }
            }
        }

        if (builder.length() > 0)
            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
    }

    return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null
            : arguments.toArray(new String[arguments.size()]));
}

From source file:org.neovera.jdiablo.internal.OptionAnnotatedProperty.java

@SuppressWarnings("static-access")
public org.apache.commons.cli.Option getCliOption() {
    if (_cliOption != null) {
        return _cliOption;
    } else {/*  w  w  w  .jav a 2 s .  c o m*/
        Option option = getOption();
        OptionBuilder builder = OptionBuilder.withDescription(option.description());
        if (StringUtils.isNotBlank(option.argName())) {
            builder = builder.withArgName(option.argName());
        }
        if (option.args() != 0) {
            builder = builder.hasArgs(option.args());
        }
        if (option.hasArgs()) {
            builder = builder.hasArgs();
        }
        if (StringUtils.isNotBlank(option.longOption())) {
            builder = builder.withLongOpt(option.longOption());
        }
        if (option.optionalArgs() != 0) {
            builder = builder.hasOptionalArgs(option.optionalArgs());
        }
        if (option.required() && !getOptionProperty().isOptionNotRequiredOverride()) {
            builder = builder.isRequired();
        }
        if (option.valueSeparator() != ' ') {
            builder = builder.withValueSeparator(option.valueSeparator());
        }

        setCliOption(builder.create(option.shortOption()));
        return getCliOption();
    }
}

From source file:org.vivoweb.harvester.util.args.ArgParser.java

/**
 * Create the Options from this ArgParser
 */// w  ww .j a  v  a  2s .  co m
@SuppressWarnings("static-access")
private void createOptions() {
    this.parser = new Options();
    for (ArgDef arg : getArgDefs()) {
        OptionBuilder ob = OptionBuilder.isRequired(false);
        if (arg.getLongOption() != null) {
            ob = ob.withLongOpt(arg.getLongOption());
            this.optMap.put(arg.getLongOption(), arg);
        }
        if (arg.getDescription() != null) {
            ob = ob.withDescription(arg.getDescription());
        }
        if (arg.hasParameter()) {
            ob = ob.withArgName(arg.getParameterDescription());
            int num = arg.numParameters();
            if (num == 1) {
                ob = ob.hasArg(arg.isParameterRequired());
            } else if (num == -1) {
                if (arg.isParameterRequired()) {
                    ob = ob.hasArgs();
                } else {
                    if (arg.isParameterValueMap()) {
                        ob = ob.hasOptionalArgs(2).withValueSeparator();
                    } else {
                        ob = ob.hasOptionalArgs();
                    }
                }
            } else {
                if (arg.isParameterRequired()) {
                    ob = ob.hasArgs(num);
                } else {
                    ob = ob.hasOptionalArgs(num);
                }
            }
        }
        Option o;
        if (arg.getShortOption() != null) {
            o = ob.create(arg.getShortOption().charValue());
            this.optMap.put(arg.getShortOption().toString(), arg);
        } else {
            o = ob.create();
        }
        this.parser.addOption(o);
    }
}