Example usage for org.apache.commons.collections4.iterators PeekingIterator next

List of usage examples for org.apache.commons.collections4.iterators PeekingIterator next

Introduction

In this page you can find the example usage for org.apache.commons.collections4.iterators PeekingIterator next.

Prototype

public E next() 

Source Link

Usage

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;
    }/*from  w ww  .  j  a  v  a2 s .  c  om*/

    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

private ParseState<T> parseArg(ParseState<T> state, PeekingIterator<String> tokens, ArgumentsMetadata arguments,
        OptionMetadata defaultOption) {//from   www  . j a  v  a  2  s .c o  m
    if (arguments != null) {
        // Argument
        state = state.withArgument(arguments, tokens.next());
    } else if (defaultOption != null) {
        // Default Option
        state = state.pushContext(Context.OPTION).withOption(defaultOption);
        state = state.withOptionValue(defaultOption, tokens.next()).popContext();
    } else {
        // Unparsed input
        state = state.withUnparsedInput(tokens.next());
    }
    return state;
}

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();

            // 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);
            }// www.j  a  va2  s  . c  o  m
        } else {
            state = parseArg(state, tokens, arguments, defaultOption);
        }
    }

    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;
    }// www.jav  a  2 s  .c  om

    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.ListValueOptionParser.java

@Override
public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state,
        List<OptionMetadata> allowedOptions) {
    String name = tokens.peek();// w w  w  .  ja  v a 2 s .  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;
}

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();//from  w  w w . ja  v a 2 s.co  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.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);/*from   w w w.j a  v  a  2s.c  o  m*/
        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: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 w w  . ja  va  2 s . 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.ClassicGetOptParser.java

public ParseState<T> parseOptions(PeekingIterator<String> tokens, ParseState<T> state,
        List<OptionMetadata> allowedOptions) {
    if (!hasShortNamePrefix(tokens.peek())) {
        return null;
    }//from   www . j a  v  a2  s .  c o m

    // 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.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  ava 2  s . c o  m

    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;
}