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

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

Introduction

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

Prototype

public PeekingIterator(final Iterator<? extends E> iterator) 

Source Link

Document

Constructor.

Usage

From source file:ca.nines.ise.transformer.Transformer.java

public DOM transform(DOM dom) throws IOException {
    this.dom = new DOM();
    this.dom.setLines(dom.getLines());
    this.dom.setSource(dom.getSource());
    iterator = new PeekingIterator<>(dom.iterator());

    while (iterator.hasNext()) {
        Node n = iterator.next();
        dispatch(n);/*  ww  w .  jav a  2  s . c o m*/
    }
    return this.dom;
}

From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java

/**
 * Tries to parse the arguments/*www. j  a  v  a 2  s .  c  o m*/
 * 
 * @param metadata
 *            Global Metadata
 * @param args
 *            Arguments
 * @return Parser State
 */
protected ParseState<T> tryParse(GlobalMetadata<T> metadata, Iterable<String> args) {
    PeekingIterator<String> tokens = new PeekingIterator<String>(args.iterator());

    //@formatter:off
    ParseState<T> state = ParseState.<T>newInstance().pushContext(Context.GLOBAL).withGlobal(metadata);
    //@formatter:on

    // Parse global options
    state = parseOptions(tokens, state, metadata.getOptions());

    // Apply aliases
    tokens = applyAliases(tokens, state);

    // Parse group
    state = parseGroup(tokens, state);

    // parse command
    state = parseCommand(tokens, state);

    return state;
}

From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java

/**
 * Tries to parse the arguments//from  ww w.  j  a v  a  2 s  .  c  o m
 * 
 * @param parserConfig
 *            Parser Configuration
 * @param command
 *            Command meta-data
 * @param args
 *            Arguments
 * @return Parser State
 */
protected ParseState<T> tryParse(ParserMetadata<T> parserConfig, CommandMetadata command,
        Iterable<String> args) {
    PeekingIterator<String> tokens = new PeekingIterator<String>(args.iterator());
    //@formatter:off
    ParseState<T> state = ParseState.<T>newInstance().pushContext(Context.GLOBAL)
            .withConfiguration(parserConfig).withCommand(command).pushContext(Context.COMMAND);
    //@formatter:off

    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 {/*  w  w  w.  j  a  va  2  s. c  o 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;
}

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 www  .  j ava  2 s .c o m*/
        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:org.openscore.lang.compiler.modeller.ExecutableBuilder.java

private Workflow compileWorkFlow(List<Map<String, Map<String, Object>>> workFlowRawData,
        Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection) {

    Deque<Task> tasks = new LinkedList<>();

    Validate.notEmpty(workFlowRawData, "Flow must have tasks in its workflow");

    PeekingIterator<Map<String, Map<String, Object>>> iterator = new PeekingIterator<>(
            workFlowRawData.iterator());

    boolean isOnFailureDefined = onFailureWorkFlow != null;

    String defaultFailure = isOnFailureDefined ? onFailureWorkFlow.getTasks().getFirst().getName()
            : FAILURE_RESULT;//w  w w. j a  va  2 s .com

    Set<String> taskNames = new HashSet<>();

    while (iterator.hasNext()) {
        Map<String, Map<String, Object>> taskRawData = iterator.next();
        Map<String, Map<String, Object>> nextTaskData = iterator.peek();
        String taskName = taskRawData.keySet().iterator().next();
        if (taskNames.contains(taskName)) {
            throw new RuntimeException("Task name: \'" + taskName
                    + "\' appears more than once in the workflow. Each task name in the workflow must be unique");
        }
        taskNames.add(taskName);
        Map<String, Object> taskRawDataValue;
        String message = "Task: " + taskName
                + " syntax is illegal.\nBelow task name, there should be a map of values in the format:\ndo:\n\top_name:";
        try {
            taskRawDataValue = taskRawData.values().iterator().next();
            if (MapUtils.isNotEmpty(taskRawDataValue) && taskRawDataValue.containsKey(LOOP_KEY)) {
                message = "Task: " + taskName
                        + " syntax is illegal.\nBelow the 'loop' keyword, there should be a map of values in the format:\nfor:\ndo:\n\top_name:";
                taskRawDataValue.putAll((Map<String, Object>) taskRawDataValue.remove(LOOP_KEY));
            }
        } catch (ClassCastException ex) {
            throw new RuntimeException(message);
        }

        String defaultSuccess;
        if (nextTaskData != null) {
            defaultSuccess = nextTaskData.keySet().iterator().next();
        } else {
            defaultSuccess = onFailureSection ? FAILURE_RESULT : SUCCESS_RESULT;
        }
        Task task = compileTask(taskName, taskRawDataValue, defaultSuccess, imports, defaultFailure);
        tasks.add(task);
    }

    if (isOnFailureDefined) {
        tasks.addAll(onFailureWorkFlow.getTasks());
    }

    return new Workflow(tasks);
}

From source file:org.openscore.lang.compiler.utils.ExecutableBuilder.java

private Workflow compileWorkFlow(LinkedHashMap<String, Map<String, Object>> workFlowRawData,
        Map<String, String> imports, Workflow onFailureWorkFlow, boolean onFailureSection) {

    Deque<Task> tasks = new LinkedList<>();

    Validate.notEmpty(workFlowRawData, "Flow must have tasks in its workflow");

    PeekingIterator<Map.Entry<String, Map<String, Object>>> iterator = new PeekingIterator<>(
            workFlowRawData.entrySet().iterator());

    boolean isOnFailureDefined = onFailureWorkFlow != null;

    String defaultFailure = isOnFailureDefined ? onFailureWorkFlow.getTasks().getFirst().getName()
            : FAILURE_RESULT;// ww w. j  a v  a 2 s .  c o m

    while (iterator.hasNext()) {
        Map.Entry<String, Map<String, Object>> taskRawData = iterator.next();
        Map.Entry<String, Map<String, Object>> nextTaskData = iterator.peek();
        String taskName = taskRawData.getKey();
        Map<String, Object> taskRawDataValue;
        try {
            taskRawDataValue = taskRawData.getValue();
        } catch (ClassCastException ex) {
            throw new RuntimeException("Task: " + taskName
                    + " syntax is illegal.\nBelow task name, there should be a map of values in the format:\ndo:\n\top_name:");
        }

        String defaultSuccess;
        if (nextTaskData != null) {
            defaultSuccess = nextTaskData.getKey();
        } else {
            defaultSuccess = onFailureSection ? FAILURE_RESULT : SUCCESS_RESULT;
        }
        Task task = compileTask(taskName, taskRawDataValue, defaultSuccess, imports, defaultFailure);
        tasks.add(task);
    }

    if (isOnFailureDefined) {
        tasks.addAll(onFailureWorkFlow.getTasks());
    }

    return new Workflow(tasks);
}

From source file:org.openvpms.archetype.rules.workflow.FreeSlotIterators.java

/**
 * Constructs a {@link FreeSlotIterators}.
 *
 * @param iterators the underlying iterators
 * @param predicate the predicate, used to filter slots
 *//*from  w w  w .j a  va  2  s  .  c  om*/
public FreeSlotIterators(List<FreeSlotIterator> iterators, Predicate<Slot> predicate) {
    this.iterators = new ArrayList<PeekingIterator<Slot>>();
    for (FreeSlotIterator iterator : iterators) {
        Iterator<Slot> filtered = new FilterIterator<Slot>(iterator, predicate);
        this.iterators.add(new PeekingIterator<Slot>(filtered));
    }
}