List of usage examples for org.apache.commons.collections4.iterators PeekingIterator peek
public E peek()
From source file:com.github.rvesse.airline.parser.options.StandardOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { OptionMetadata option = findOption(state, allowedOptions, tokens.peek()); if (option == null) { return null; }/* w w w.j ava 2 s .c o m*/ tokens.next(); state = state.pushContext(Context.OPTION).withOption(option); if (option.getArity() == 0) { state = state.withOptionValue(option, Boolean.TRUE.toString()).popContext(); } else if (option.getArity() == 1) { if (tokens.hasNext()) { state = state.withOptionValue(option, tokens.next()).popContext(); } } else { int count = 0; boolean hasSeparator = false; boolean foundNextOption = false; String argsSeparator = state.getParserConfiguration().getArgumentsSeparator(); while (count < option.getArity() && tokens.hasNext() && !hasSeparator) { String peekedToken = tokens.peek(); hasSeparator = peekedToken.equals(argsSeparator); foundNextOption = findOption(state, allowedOptions, peekedToken) != null; if (hasSeparator || foundNextOption) break; state = state.withOptionValue(option, tokens.next()); ++count; } if (count != option.getArity()) { throw new ParseOptionMissingValueException( "Too few option values received for option %s (%d values expected but only found %d)", option.getTitle(), option.getOptions().iterator().next(), option.getArity(), count); } state = state.popContext(); } return state; }
From source file:com.github.rvesse.airline.parser.options.AbstractNameValueOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { List<String> parts = AirlineUtils.unmodifiableListCopy( StringUtils.split(tokens.peek(), new String(new char[] { this.separator }), 2)); if (parts.size() != 2) { return null; }/*w ww .j a v a 2 s.c o m*/ OptionMetadata option = findOption(state, allowedOptions, parts.get(0)); if (option == null || option.getArity() != 1) { // Only supported for arity 1 options currently return null; } // we have a match so consume the token tokens.next(); // update state state = state.pushContext(Context.OPTION).withOption(option); state = state.withOptionValue(option, parts.get(1)).popContext(); return state; }
From source file:com.github.rvesse.airline.parser.options.ClassicGetOptParser.java
public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { if (!hasShortNamePrefix(tokens.peek())) { return null; }//from w ww . j a v a2s . c om // remove leading dash from token String remainingToken = tokens.peek().substring(1); ParseState<T> nextState = state; boolean first = true; while (!remainingToken.isEmpty()) { char tokenCharacter = remainingToken.charAt(0); // is the current token character a single letter option? OptionMetadata option = findOption(state, allowedOptions, "-" + tokenCharacter); if (option == null) { return null; } nextState = nextState.pushContext(Context.OPTION).withOption(option); // remove current token character remainingToken = remainingToken.substring(1); // for no argument options, process the option and remove the // character from the token if (option.getArity() == 0) { nextState = nextState.withOptionValue(option, Boolean.TRUE.toString()).popContext(); first = false; continue; } if (option.getArity() == 1) { // we must, consume the current token so we can see the next // token tokens.next(); // if current token has more characters, this is the value; // otherwise it is the next token if (!remainingToken.isEmpty()) { nextState = nextState.withOptionValue(option, remainingToken).popContext(); } else if (tokens.hasNext()) { nextState = nextState.withOptionValue(option, tokens.next()).popContext(); } return nextState; } // Don't throw an error if this is the first option we have seen as // in that case the option may legitimately be processed by another // option parser if (first) return null; throw new ParseOptionUnexpectedException("Short options style can not be used with option %s", option); } // consume the current token tokens.next(); return nextState; }
From source file:com.github.rvesse.airline.parser.options.ListValueOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { String name = tokens.peek(); boolean noSep = false; OptionMetadata option = findOption(state, allowedOptions, name); if (option == null) { // Check if we are looking at a maven style -Pa,b,c argument if (hasShortNamePrefix(name) && name.length() > 2) { String shortName = name.substring(0, 2); option = findOption(state, allowedOptions, shortName); noSep = option != null;//from w w w. j a v a 2 s . c om } if (!noSep) return null; } tokens.next(); state = state.pushContext(Context.OPTION).withOption(option); String list = noSep ? name.substring(2) : null; if (option.getArity() == 0) { // Zero arity option, consume token and continue state = state.withOptionValue(option, Boolean.TRUE.toString()).popContext(); } else { if (list == null) { // Can't parse list value if there are no further tokens if (!tokens.hasNext()) return state; // Consume the value immediately, this option parser will now // either succeed to parse the option or will error list = tokens.next(); } // Parse value as a list List<String> listValues = getValues(list); if (listValues.size() < option.getArity()) throw new ParseOptionMissingValueException( "Too few option values received for option %s in list value '%s' (%d values expected but only found %d)", option.getTitle(), option.getOptions().iterator().next(), list, option.getArity(), listValues.size()); if (listValues.size() > option.getArity()) throw new ParseOptionUnexpectedException( "Too many option values received for option %s in list value '%s' (%d values expected but found %d)", option.getOptions().iterator().next(), list, option.getArity(), listValues.size()); // Parse individual values and assign to option for (String value : listValues) { state = state.withOptionValue(option, value); } state = state.popContext(); } return state; }
From source file:com.github.rvesse.airline.parser.options.MaybePairValueOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { String name = tokens.peek(); boolean noSep = false; OptionMetadata option = findOption(state, allowedOptions, name); if (option == null) { // Check if we are looking at a maven style -Pa,b,c argument if (hasShortNamePrefix(name) && name.length() > 2) { String shortName = name.substring(0, 2); option = findOption(state, allowedOptions, shortName); noSep = option != null;//from w w w .j a v a 2 s. com } if (!noSep) return null; } // Only works with arity 2 options if (option.getArity() != 2) return null; tokens.next(); state = state.pushContext(Context.OPTION).withOption(option); String maybePair = noSep ? name.substring(2) : null; if (maybePair == null) { // Can't parse pair value if there are no further tokens if (!tokens.hasNext()) return state; // Consume the value immediately, this option parser will now // either succeed to parse the option or will error maybePair = tokens.next(); } // Parse value as a pair List<String> pairValues = getValues(maybePair); if (pairValues.size() < 2) { // If we didn't get a pair as x=y then need to grab the second half // of the pair from the next token if (!tokens.hasNext()) return state; // If the next thing is actually an option abort String peekedToken = tokens.peek(); if (findOption(state, allowedOptions, peekedToken) != null) return state; pairValues.add(tokens.next()); } // Parse the values and assign to option for (String value : pairValues) { state = state.withOptionValue(option, value); } state = state.popContext(); return state; }
From source file:com.github.rvesse.airline.examples.userguide.parser.options.JdbcStyleOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { // Peek at the first input String options = tokens.peek(); // Must have at least one name=value pair for this to be a JDBC style // option specification if (!options.contains(NAME_VALUE_SEPARATOR)) return null; // May potentially be multiple name value pairs in the string separated // by a semicolon String[] optionPairs = options.split(OPTION_SEPARATOR); // Try and parse the options ParseState<T> nextState = state; boolean first = true; for (String pair : optionPairs) { // Allow for empty pair, this may occur if the user terminates the // options with a semicolon which is legitimate if (StringUtils.isEmpty(pair)) continue; if (!pair.contains(NAME_VALUE_SEPARATOR)) { // This would be invalid for us but if this is the first option // we've seen might be valid for another option parser if (first) return null; // Otherwise treat as an invalid option state.getParserConfiguration().getErrorHandler() .handleError(new ParseOptionMissingValueException(pair)); }/*w w w. j av a 2 s . com*/ // Find the relevant option String[] nameValue = pair.split(NAME_VALUE_SEPARATOR, 2); OptionMetadata option = findOption(state, allowedOptions, nameValue[0]); if (option == null) { // No such option, let another option parser try to parse the // option string if (first) return null; state.getParserConfiguration().getErrorHandler().handleError(new ParseOptionUnexpectedException( "JDBC style option '%s' refers to option '%s' which does not refer to a known option", pair, nameValue[0])); } // Tell the parser we're parsing an option nextState = nextState.pushContext(Context.OPTION).withOption(option); if (option.getArity() == 1) { if (first) { // If this is the first valid option we've seen we now // consume the input token tokens.next(); first = false; } // Set the option value nextState = nextState.withOptionValue(option, nameValue[1]).popContext(); } else { // We only permit arity 1 options if (first) return null; state.getParserConfiguration().getErrorHandler().handleError(new ParseOptionUnexpectedException( "JDBC style option '%s' refers to option '%s' which has arity %d, only arity 1 options are supported", pair, nameValue[0], option.getArity())); } } // If we didn't parse anything let other parsers try if (first) return null; // Otherwise return the new state return nextState; }
From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java
private ParseState<T> parseArgs(ParseState<T> state, PeekingIterator<String> tokens, ArgumentsMetadata arguments, OptionMetadata defaultOption) { String sep = state.getParserConfiguration().getArgumentsSeparator(); if (tokens.hasNext()) { if (tokens.peek().equals(sep)) { state = state.pushContext(Context.ARGS); tokens.next();/*from w ww .j av a2 s . co m*/ // Consume all remaining tokens as arguments // Default option can't possibly apply at this point because we // saw the arguments separator while (tokens.hasNext()) { state = parseArg(state, tokens, arguments, null); } } else { state = parseArg(state, tokens, arguments, defaultOption); } } return state; }
From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java
protected ParseState<T> parseGroup(PeekingIterator<String> tokens, ParseState<T> state) { Predicate<CommandGroupMetadata> findGroupPredicate; if (tokens.hasNext()) { //@formatter:off findGroupPredicate = state.getParserConfiguration().allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(tokens.peek(), state.getGlobal().getCommandGroups()) : new GroupFinder(tokens.peek()); //@formatter:on CommandGroupMetadata group = CollectionUtils.find(state.getGlobal().getCommandGroups(), findGroupPredicate);// www. j a va2 s . c om if (group != null) { tokens.next(); state = state.withGroup(group).pushContext(Context.GROUP); state = parseOptions(tokens, state, state.getGroup().getOptions()); // Possibly may have sub-groups specified while (tokens.hasNext() && state.getGroup().getSubGroups().size() > 0) { //@formatter:off findGroupPredicate = state.getParserConfiguration().allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(tokens.peek(), state.getGroup().getSubGroups()) : new GroupFinder(tokens.peek()); //@formatter:on group = CollectionUtils.find(state.getGroup().getSubGroups(), findGroupPredicate); if (group != null) { tokens.next(); state = state.withGroup(group).pushContext(Context.GROUP); state = parseOptions(tokens, state, state.getGroup().getOptions()); } else { // Either a group that has a mixture of sub-groups and // commands in which case we need to break out of this // loop and flow will go onto to try the token as a // command name instead or actually invalid input and // we'll hit an error break; } } } } return state; }
From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java
protected ParseState<T> parseCommand(PeekingIterator<String> tokens, ParseState<T> state) { Predicate<CommandMetadata> findCommandPredicate; List<CommandMetadata> expectedCommands = state.getGlobal().getDefaultGroupCommands(); if (state.getGroup() != null) { expectedCommands = state.getGroup().getCommands(); }/* ww w . j av a 2 s .c om*/ if (tokens.hasNext()) { //@formatter:off findCommandPredicate = state.getParserConfiguration().allowsAbbreviatedCommands() ? new AbbreviatedCommandFinder(tokens.peek(), expectedCommands) : new CommandFinder(tokens.peek()); //@formatter:on CommandMetadata command = AirlineUtils.find(expectedCommands, findCommandPredicate, state.getGroup() != null ? state.getGroup().getDefaultCommand() : null); boolean usingDefault = false; if (command == null && state.getGroup() == null && state.getGlobal().getDefaultCommand() != null) { usingDefault = true; command = state.getGlobal().getDefaultCommand(); } if (command == null) { while (tokens.hasNext()) { state = state.withUnparsedInput(tokens.next()); } } else { if (tokens.peek().equals(command.getName()) || (!usingDefault && state.getParserConfiguration().allowsAbbreviatedCommands())) { tokens.next(); } state = state.withCommand(command).pushContext(Context.COMMAND); state = parseCommandOptionsAndArguments(tokens, state, command); } } return state; }
From source file:com.github.rvesse.airline.parser.aliases.AliasResolver.java
public PeekingIterator<String> resolveAliases(PeekingIterator<String> tokens, ParseState<T> state) { Predicate<? super CommandGroupMetadata> findGroupPredicate; Predicate<? super CommandMetadata> findCommandPredicate; // Nothing to do if no further tokens if (!tokens.hasNext()) return tokens; // Nothing to do if no aliases defined if (state.getParserConfiguration().getAliases().size() == 0) return tokens; Set<String> aliasesSeen = new TreeSet<String>(); do {/* ww w.j a va 2s . co m*/ // Try to find an alias AliasMetadata alias = CollectionUtils.find(state.getParserConfiguration().getAliases(), new AliasFinder(tokens.peek())); // Nothing further to do if no aliases found if (alias == null) return tokens; // Check for circular references if (!aliasesSeen.add(alias.getName())) { throw new ParseAliasCircularReferenceException(alias.getName(), aliasesSeen); } // Can we override built-ins? if (!state.getParserConfiguration().aliasesOverrideBuiltIns()) { // If not we must check we don't have a default // group/command with the same name as otherwise that // would take precedence if (state.getGlobal() != null) { GlobalMetadata<T> metadata = state.getGlobal(); findGroupPredicate = new GroupFinder(tokens.peek()); findCommandPredicate = new CommandFinder(tokens.peek()); if (CollectionUtils.find(metadata.getCommandGroups(), findGroupPredicate) != null || CollectionUtils.find(metadata.getDefaultGroupCommands(), findCommandPredicate) != null) return tokens; } } // Discard the alias token tokens.next(); // Apply the alias List<String> newParams = new ArrayList<String>(); List<String> remainingParams = new ArrayList<String>(); while (tokens.hasNext()) { remainingParams.add(tokens.next()); } // Process alias arguments Set<Integer> used = new TreeSet<Integer>(); for (String arg : alias.getArguments()) { if (arg.startsWith("$")) { // May be a positional parameter try { int num = Integer.parseInt(arg.substring(1)); num--; if (num >= 0 && num < remainingParams.size()) { // Valid positional parameter newParams.add(remainingParams.get(num)); used.add(num); continue; } } catch (NumberFormatException e) { // Ignore - the number was invalid so we'll // treat it as an ordinary parameter } } // Some other parameter newParams.add(arg); } // Remove used positional parameters int removed = 0; for (int pos : used) { remainingParams.remove(pos - removed); removed++; } // Pass through any remaining parameters for (String arg : remainingParams) { newParams.add(arg); } // Prepare a new tokens iterator tokens = new PeekingIterator<String>(newParams.iterator()); } while (state.getParserConfiguration().aliasesMayChain()); return tokens; }