List of usage examples for org.apache.commons.collections4.iterators PeekingIterator hasNext
public boolean hasNext()
From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java
protected ParseState<T> parseCommandOptionsAndArguments(PeekingIterator<String> tokens, ParseState<T> state, CommandMetadata command) {// w w w . j a v a 2 s. c om while (tokens.hasNext()) { state = parseOptions(tokens, state, command.getCommandOptions()); state = parseArgs(state, tokens, command.getArguments(), command.getDefaultOption()); } 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);/* w w w . j a v a2 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.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 {//from w w w. ja v a 2 s . c om // 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; }
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 w w .ja v a2 s .c o 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
private ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { // Get the option parsers in use List<OptionParser<T>> optionParsers = state.getParserConfiguration().getOptionParsers(); while (tokens.hasNext()) { // Try to parse next option(s) using different styles. If code // matches it returns the next parser state, otherwise it returns // null./*from ww w . ja v a 2 s .c o m*/ // Try each option parser in turn boolean matched = false; for (OptionParser<T> optionParser : optionParsers) { ParseState<T> nextState = optionParser.parseOptions(tokens, state, allowedOptions); if (nextState != null) { // If the current parser matched an option this token is // processed and we don't need to consider other parsers state = nextState; matched = true; break; } } // Parsed an option so continue parsing options if (matched) continue; // Otherwise did not match an option so parse no further options break; } return state; }
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 ww . j a va 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.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(); }//from w w w. j a v 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:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java
private WorkflowModellingResult compileWorkFlow(List<Map<String, Map<String, Object>>> workFlowRawData, Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection, String namespace, SensitivityLevel sensitivityLevel) { List<RuntimeException> errors = new ArrayList<>(); Deque<Step> steps = new LinkedList<>(); Set<String> stepNames = new HashSet<>(); Deque<Step> onFailureSteps = !(onFailureSection || onFailureWorkFlow == null) ? onFailureWorkFlow.getSteps() : new LinkedList<Step>(); List<String> onFailureStepNames = getStepNames(onFailureSteps); boolean onFailureStepFound = onFailureStepNames.size() > 0; String defaultFailure = onFailureStepFound ? onFailureStepNames.get(0) : ScoreLangConstants.FAILURE_RESULT; PeekingIterator<Map<String, Map<String, Object>>> iterator = new PeekingIterator<>( workFlowRawData.iterator()); while (iterator.hasNext()) { Map<String, Map<String, Object>> stepRawData = iterator.next(); String stepName = getStepName(stepRawData); validateStepName(stepName, errors); if (stepNames.contains(stepName) || onFailureStepNames.contains(stepName)) { errors.add(new RuntimeException("Step name: \'" + stepName + "\' appears more than once in the workflow. " + UNIQUE_STEP_NAME_MESSAGE_SUFFIX)); }/*from w ww .ja v a 2s .com*/ stepNames.add(stepName); Map<String, Object> stepRawDataValue; String message = "Step: " + stepName + " syntax is illegal.\nBelow step name, there should " + "be a map of values in the format:\ndo:\n\top_name:"; try { stepRawDataValue = stepRawData.values().iterator().next(); if (MapUtils.isNotEmpty(stepRawDataValue)) { boolean loopKeyFound = stepRawDataValue.containsKey(LOOP_KEY); boolean parallelLoopKeyFound = stepRawDataValue.containsKey(PARALLEL_LOOP_KEY); if (loopKeyFound) { if (parallelLoopKeyFound) { errors.add(new RuntimeException( "Step: " + stepName + " syntax is illegal.\nBelow step name, " + "there can be either \'loop\' or \'aync_loop\' key.")); } message = "Step: " + stepName + " syntax is illegal.\nBelow the 'loop' keyword, there " + "should be a map of values in the format:\nfor:\ndo:\n\top_name:"; @SuppressWarnings("unchecked") Map<String, Object> loopRawData = (Map<String, Object>) stepRawDataValue.remove(LOOP_KEY); stepRawDataValue.putAll(loopRawData); } if (parallelLoopKeyFound) { message = "Step: " + stepName + " syntax is illegal.\nBelow the 'parallel_loop' keyword, there " + "should be a map of values in the format:\nfor:\ndo:\n\top_name:"; @SuppressWarnings("unchecked") Map<String, Object> parallelLoopRawData = (Map<String, Object>) stepRawDataValue .remove(PARALLEL_LOOP_KEY); errors.addAll(preCompileValidator.checkKeyWords(stepName, SlangTextualKeys.PARALLEL_LOOP_KEY, parallelLoopRawData, Collections.emptyList(), parallelLoopValidKeywords, null)); parallelLoopRawData.put(PARALLEL_LOOP_KEY, parallelLoopRawData.remove(FOR_KEY)); stepRawDataValue.putAll(parallelLoopRawData); } } } catch (ClassCastException ex) { stepRawDataValue = new HashMap<>(); errors.add(new RuntimeException(message)); } String defaultSuccess; Map<String, Map<String, Object>> nextStepData = iterator.peek(); if (nextStepData != null) { defaultSuccess = nextStepData.keySet().iterator().next(); } else { defaultSuccess = onFailureSection ? ScoreLangConstants.FAILURE_RESULT : SUCCESS_RESULT; } String onFailureStepName = onFailureStepFound ? onFailureStepNames.get(0) : null; StepModellingResult stepModellingResult = compileStep(stepName, stepRawDataValue, defaultSuccess, imports, defaultFailure, namespace, onFailureStepName, onFailureSection, sensitivityLevel); errors.addAll(stepModellingResult.getErrors()); steps.add(stepModellingResult.getStep()); } if (onFailureStepFound) { steps.addAll(onFailureSteps); } return new WorkflowModellingResult(new Workflow(steps), errors); }
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();// w ww .j a va 2s . c o m 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; } 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.parser.options.ListValueOptionParser.java
@Override public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state, List<OptionMetadata> allowedOptions) { String name = tokens.peek();/*www .jav a2s.c o m*/ 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; } 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; }