List of usage examples for org.apache.commons.cli OptionBuilder isRequired
public static OptionBuilder isRequired()
From source file:org.graphwalker.CLI.java
/** * Build the command source command line parser *///from w ww.j ava2 s . c o m @SuppressWarnings("static-access") private void buildSourceCLI() { opt.addOption(OptionBuilder.isRequired().withArgName("file|folder") .withDescription("The file (or folder) containing graphml formatted files.").hasArg() .withLongOpt("input_graphml").create("f")); opt.addOption(OptionBuilder.isRequired().withArgName("file").withDescription("The template file").hasArg() .withLongOpt("template").create("t")); }
From source file:org.graphwalker.CLI.java
/** * Build the command xml command line parser *//*from w ww . j av a 2 s. c om*/ @SuppressWarnings("static-access") private void buildXmlCLI() { opt.addOption("a", false, "Prints the statistics of the test, at the end of the run."); opt.addOption(OptionBuilder.isRequired().withArgName("file") .withDescription("The xml file containing the mbt settings.").hasArg().create("f")); opt.addOption(OptionBuilder.withArgName("seconds").withDescription( "Prints the test coverage of the graph during execution every <n second>. The printout goes to the log file defined in " + "mbt.properties, and only, if at least INFO level is set in " + "that same file.") .hasArg().create("o")); opt.addOption("d", "dry-run", false, "Will execute a dry-run of the model. Dialog will pop up for every edge and vertex."); }
From source file:org.graphwalker.CLI.java
/** * Build the command analyze command line parser *//*from www .ja v a 2s. c o m*/ @SuppressWarnings("static-access") private void buildAnalyzeCLI() { opt.addOption(OptionBuilder.isRequired().withArgName("file|folder") .withDescription("The file (or folder) containing graphml formatted files.").hasArg() .withLongOpt("input_graphml").create("f")); }
From source file:org.jnotary.client.DvcsCheck.java
@SuppressWarnings("static-access") private static Option createOption(String shortOptionName, String optionName, String description, boolean hasValue, boolean isMandatory) { OptionBuilder opt = OptionBuilder.withLongOpt(optionName).withArgName(shortOptionName) .withDescription(description); if (hasValue) opt = opt.hasArg();/*from ww w . j av a 2s . co m*/ if (isMandatory) opt = opt.isRequired(); return opt.create(shortOptionName); }
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);/*ww w.j a v a2 s. c o m*/ } } 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);/* w ww .jav 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.midonet.midolman.tools.MmCtl.java
private static OptionGroup getMutuallyExclusiveOptionGroup() { // The command line tool can only accept one of these options: OptionGroup mutuallyExclusiveOptions = new OptionGroup(); OptionBuilder.hasArgs(2);//from w w w . ja v a2 s.co m OptionBuilder.isRequired(); OptionBuilder.withLongOpt("bind-port"); OptionBuilder.withDescription("Bind a port to an interface"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.hasArg(); OptionBuilder.isRequired(); OptionBuilder.withLongOpt("unbind-port"); OptionBuilder.withDescription("Unbind a port from an interface"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.withLongOpt("list-hosts"); OptionBuilder.withDescription("List MidolMan agents in the system"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); // make sure that there is at least one. mutuallyExclusiveOptions.setRequired(true); return mutuallyExclusiveOptions; }
From source file:org.midonet.mmdpctl.Mmdpctl.java
public static void main(String... args) { Options options = new Options(); // The command line tool can only accept one of these options: OptionGroup mutuallyExclusiveOptions = new OptionGroup(); OptionBuilder.withDescription("List all the installed datapaths"); OptionBuilder.isRequired(); OptionBuilder.withLongOpt("list-dps"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.withDescription("Show all the information related to a given datapath."); OptionBuilder.hasArg();/*from w ww . ja va 2 s .co m*/ OptionBuilder.isRequired(); OptionBuilder.withLongOpt("show-dp"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.withDescription("Show all the flows installed for a given datapath."); OptionBuilder.hasArg(); OptionBuilder.isRequired(); OptionBuilder.withLongOpt("dump-dp"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.withDescription("Add a new datapath."); OptionBuilder.hasArg(); OptionBuilder.withLongOpt("add-dp"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); OptionBuilder.withDescription("Delete a datapath."); OptionBuilder.hasArg(); OptionBuilder.withLongOpt("delete-dp"); mutuallyExclusiveOptions.addOption(OptionBuilder.create()); // make sure that there is at least one. mutuallyExclusiveOptions.setRequired(true); options.addOptionGroup(mutuallyExclusiveOptions); // add an optional timeout to the command. OptionBuilder.withDescription( "Specifies a timeout in seconds. " + "If the program is not able to get the results in less than " + "this amount of time it will stop and return with an error code"); OptionBuilder.hasArg(); OptionBuilder.withLongOpt("timeout"); options.addOption(OptionBuilder.create()); CommandLineParser parser = new PosixParser(); try { CommandLine cl = parser.parse(options, args); Mmdpctl mmdpctl = new Mmdpctl(); // check if the user sets a (correct) timeout. if (cl.hasOption("timeout")) { String timeoutString = cl.getOptionValue("timeout"); Integer timeout = Integer.parseInt(timeoutString); if (timeout > 0) { log.info("Installing a timeout of {} seconds", timeout); mmdpctl.setTimeout(timeout); } else { System.out.println("The timeout needs to be a positive number, bigger than 0."); System.exit(1); } } if (cl.hasOption("list-dps")) { System.exit(mmdpctl.execute(new ListDatapathsCommand())); } else if (cl.hasOption("show-dp")) { System.exit(mmdpctl.execute(new GetDatapathCommand(cl.getOptionValue("show-dp")))); } else if (cl.hasOption("dump-dp")) { System.exit(mmdpctl.execute(new DumpDatapathCommand(cl.getOptionValue("dump-dp")))); } else if (cl.hasOption("add-dp")) { System.exit(mmdpctl.execute(new AddDatapathCommand(cl.getOptionValue("add-dp")))); } else if (cl.hasOption("delete-dp")) { System.exit(mmdpctl.execute(new DeleteDatapathCommand(cl.getOptionValue("delete-dp")))); } } catch (ParseException e) { showHelpAndExit(options, e.getMessage()); } System.exit(0); }
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 {//from w w w . j a v 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.schreibubi.JCombinationsTools.binaryDiff.BinaryDiff.java
/** * Compares two binary files of equal size for differences. Output is somwhow similar to gnu unified diff: <br> * --- old file <br>/* ww w. j a va2s . c o m*/ * +++ new file <br> * @ start pos, end pos <br> * followed by line pairs preceded by - and +. The line preceded by - list the values which are replaced by the * values in the + line. * <p> * One patch file can contain this whole block more than once, to patch different files in one go. * * @param args * two binary files to compare, plus output file for the diff */ @SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); try { int difflength = 1; int beforeLength = 0; int afterLength = 0; String outfile = ""; CommandLineParser CLparser = new PosixParser(); // create the Options options.addOption(OptionBuilder.isRequired().withLongOpt("length") .withDescription("how many bytes should be compared at once").hasArg().withArgName("length") .create('l')); options.addOption(OptionBuilder.isRequired().withLongOpt("outfile").withDescription("output file") .hasArg().withArgName("file").create('o')); options.addOption(OptionBuilder.withLongOpt("version").withDescription("version").create('v')); options.addOption(OptionBuilder.withLongOpt("before").withDescription("prepend context number bytes") .hasArg().withArgName("bytes").create('b')); options.addOption(OptionBuilder.withLongOpt("after").withDescription("postpend context number bytes") .hasArg().withArgName("bytes").create('a')); CommandLine line = CLparser.parse(options, args); if (line.hasOption("l")) difflength = Integer.parseInt(line.getOptionValue("l")); if (line.hasOption("o")) outfile = line.getOptionValue("o"); if (line.hasOption("b")) beforeLength = Integer.parseInt(line.getOptionValue("b")); if (line.hasOption("a")) afterLength = Integer.parseInt(line.getOptionValue("a")); if (line.hasOption("v")) { Info.printVersion("BinaryDiff"); Runtime.getRuntime().exit(0); } String[] leftargs = line.getArgs(); if (leftargs.length == 2) exec(leftargs[0], leftargs[1], outfile, difflength, beforeLength, afterLength); else { Info.printVersion("BinaryDiff"); Runtime.getRuntime().exit(0); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Info.getVersionString("BinaryDiff"), options); } }