Example usage for com.google.common.collect PeekingIterator next

List of usage examples for com.google.common.collect PeekingIterator next

Introduction

In this page you can find the example usage for com.google.common.collect PeekingIterator next.

Prototype

@Override
E next();

Source Link

Document

The objects returned by consecutive calls to #peek() then #next() are guaranteed to be equal to each other.

Usage

From source file:org.eclipse.xtext.ide.editor.contentassist.IndentationAwareCompletionPrefixProvider.java

private PeekingIterator<ILeafNode> createReversedLeafIterator(INode root, INode candidate,
        LinkedList<ILeafNode> sameGrammarElement) {
    EObject grammarElement = null;// ww  w. ja va  2 s .  com
    PeekingIterator<ILeafNode> iterator = Iterators
            .peekingIterator(Iterators.filter(root.getAsTreeIterable().reverse().iterator(), ILeafNode.class));
    // traverse until we find the current candidate
    while (iterator.hasNext()) {
        ILeafNode next = iterator.next();
        if (candidate.equals(next)) {
            break;
        } else if (next.getTotalLength() == 0) {
            EObject otherGrammarElement = tryGetGrammarElementAsRule(next);
            if (grammarElement == null) {
                grammarElement = otherGrammarElement;
            }
            if (otherGrammarElement.equals(grammarElement)) {
                sameGrammarElement.add(next);
            } else {
                sameGrammarElement.removeLast();
            }
        }
    }
    return iterator;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticmi.read.InterfaceInformationFlowConsistencyValidator.java

@Override
public boolean validate(Model model, MessageListener messageListener) {
    if (isSentientMode()) {
        LOGGER.warn("Can't perform model validation! The metamodel is in invalid state for this validator.");
        return true;
    }//  w w w .j  a v a  2  s. co m

    boolean result = true;

    Collection<ObjectExpression> allISIs = informationSystemInterface.apply(model).getMany();
    for (ObjectExpression isi : allISIs) {

        ElasticValue<ObjectExpression> connectedInfoFlowEV = isiToIf.apply(isi);
        if (connectedInfoFlowEV.isMany()) {
            PeekingIterator<ObjectExpression> infoFlowsIterator = Iterators
                    .peekingIterator(connectedInfoFlowEV.getMany().iterator());

            while (infoFlowsIterator.hasNext()) {
                ObjectExpression currentInfoFlow = infoFlowsIterator.next();

                ElasticValue<ObjectExpression> currentIsr1EV = ifToIsr1.apply(currentInfoFlow);
                ElasticValue<ObjectExpression> currentIsr2EV = ifToIsr2.apply(currentInfoFlow);
                // check if exactly two ISR are connected:
                if (!(currentIsr1EV.isOne() && currentIsr2EV.isOne())) {
                    result = false;
                    String nameOfInterface = getNameOrDefault(informationSystemInterface, isi, "NULL", ",");
                    String nameOfInfoFlow = getNameOrDefault(informationFlow, currentInfoFlow, "NULL", ",");
                    messageListener.onMessage(new InterfaceInformationFlowConsistencyViolationMessage(
                            nameOfInterface, nameOfInfoFlow));
                    continue;
                }

                if (!infoFlowsIterator.hasNext()) {
                    break; // reached last pair
                }
                ObjectExpression nextInfoFlow = infoFlowsIterator.peek();
                ElasticValue<ObjectExpression> nextIsr1EV = ifToIsr1.apply(nextInfoFlow);
                ElasticValue<ObjectExpression> nextIsr2EV = ifToIsr2.apply(nextInfoFlow);
                if (!(nextIsr1EV.isOne() && nextIsr2EV.isOne())) {
                    continue;
                }

                // check if connected ISR and/or their order are equal compared to the previous InformationFlow:
                ImmutableList<ObjectExpression> currentList = ImmutableList.of(currentIsr1EV.getOne(),
                        currentIsr2EV.getOne());
                ImmutableList<ObjectExpression> nextList = ImmutableList.of(nextIsr1EV.getOne(),
                        nextIsr2EV.getOne());

                if (!currentList.equals(nextList)) {
                    result = false;
                    String nameOfInterface = getNameOrDefault(informationSystemInterface, isi, "NULL", ", ");
                    String nameOfInfoFlow1 = getNameOrDefault(informationFlow, currentInfoFlow, "NULL", ",");
                    String nameOfInfoFlow2 = getNameOrDefault(informationFlow, nextInfoFlow, "NULL", ",");
                    messageListener.onMessage(new InterfaceInformationFlowConsistencyViolationMessage(
                            nameOfInterface, nameOfInfoFlow1, nameOfInfoFlow2));
                }
            }
        }
    }
    return result;
}

From source file:co.cask.cdap.data.tools.HBaseQueueDebugger.java

/**
 * Only works for {@link co.cask.cdap.data2.transaction.queue.hbase.ShardedHBaseQueueStrategy}.
 *//*from  w  w w.ja va  2 s  . co m*/
public QueueStatistics scanQueue(final QueueName queueName, @Nullable Long consumerGroupId) throws Exception {
    HBaseConsumerStateStore stateStore;
    try {
        stateStore = queueAdmin.getConsumerStateStore(queueName);
    } catch (IllegalStateException e) {
        throw new NotFoundException(queueName);
    }

    TransactionExecutor txExecutor = Transactions.createTransactionExecutor(txExecutorFactory, stateStore);
    Multimap<Long, QueueBarrier> barriers = txExecutor
            .execute(new TransactionExecutor.Function<HBaseConsumerStateStore, Multimap<Long, QueueBarrier>>() {
                @Override
                public Multimap<Long, QueueBarrier> apply(HBaseConsumerStateStore input) throws Exception {
                    return input.getAllBarriers();
                }
            }, stateStore);
    System.out.printf("Got %d barriers\n", barriers.size());

    QueueStatistics stats = new QueueStatistics();

    if (consumerGroupId != null) {
        barriers = Multimaps.filterKeys(barriers, Predicates.equalTo(consumerGroupId));
    }

    for (Map.Entry<Long, Collection<QueueBarrier>> entry : barriers.asMap().entrySet()) {
        long groupId = entry.getKey();
        Collection<QueueBarrier> groupBarriers = entry.getValue();

        System.out.printf("Scanning barriers for group %d\n", groupId);

        int currentSection = 1;
        PeekingIterator<QueueBarrier> barrierIterator = Iterators.peekingIterator(groupBarriers.iterator());
        while (barrierIterator.hasNext()) {
            QueueBarrier start = barrierIterator.next();
            QueueBarrier end = barrierIterator.hasNext() ? barrierIterator.peek() : null;

            System.out.printf("Scanning section %d/%d...\n", currentSection, groupBarriers.size());
            scanQueue(txExecutor, stateStore, queueName, start, end, stats);
            System.out.printf("Current results: %s\n", stats.getReport());
            currentSection++;
        }
        System.out.println("Scanning complete");
    }

    System.out.printf("Total results: %s\n", stats.getReport());
    return stats;
}

From source file:com.ardor3d.input.PhysicalLayer.java

private void readControllerState() {
    final PeekingIterator<ControllerEvent> eventIterator = _controllerWrapper.getEvents();

    if (eventIterator.hasNext()) {
        _currentControllerState = new ControllerState(_currentControllerState);
        while (eventIterator.hasNext()) {
            final ControllerEvent event = eventIterator.next();
            _currentControllerState.addEvent(event);
        }//from w  w  w .  j  a v  a 2 s.co  m
    }
}

From source file:org.apache.hadoop.hbase.regionserver.CompactorScanner.java

public boolean next(List<Cell> result, int limit) throws IOException {

    if (currentRowWorthValues.isEmpty()) {
        // 1) Read next row
        List<Cell> scanResult = new ArrayList<Cell>();
        hasMoreRows = internalScanner.next(scanResult);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Row: Result {} limit {} more rows? {}", scanResult, limit, hasMoreRows);
        }/*from   www.j a v a  2s.  c  om*/
        // 2) Traverse result list separating normal cells from shadow
        // cells and building a map to access easily the shadow cells.
        SortedMap<Cell, Optional<Cell>> cellToSc = CellUtils.mapCellsToShadowCells(scanResult);

        // 3) traverse the list of row key values isolated before and
        // check which ones should be discarded
        Map<String, CellInfo> lastTimestampedCellsInRow = new HashMap<>();
        PeekingIterator<Map.Entry<Cell, Optional<Cell>>> iter = Iterators
                .peekingIterator(cellToSc.entrySet().iterator());
        while (iter.hasNext()) {
            Map.Entry<Cell, Optional<Cell>> entry = iter.next();
            Cell cell = entry.getKey();
            Optional<Cell> shadowCellOp = entry.getValue();

            if (cell.getTimestamp() > lowWatermark) {
                retain(currentRowWorthValues, cell, shadowCellOp);
                continue;
            }

            if (shouldRetainNonTransactionallyDeletedCell(cell)) {
                retain(currentRowWorthValues, cell, shadowCellOp);
                continue;
            }

            // During a minor compaction the coprocessor may only see a
            // subset of store files and may not have the all the versions
            // of a cell available for consideration. Therefore, if it
            // deletes a cell with a tombstone during a minor compaction,
            // an older version of the cell may become visible again. So,
            // we have to remove tombstones only in major compactions.
            if (isMajorCompaction) {
                if (CellUtils.isTombstone(cell)) {
                    if (shadowCellOp.isPresent()) {
                        skipToNextColumn(cell, iter);
                    } else {
                        Optional<CommitTimestamp> commitTimestamp = queryCommitTimestamp(cell);
                        // Clean the cell only if it is valid
                        if (commitTimestamp.isPresent() && commitTimestamp.get().isValid()) {
                            skipToNextColumn(cell, iter);
                        }
                    }
                    continue;
                }
            }

            if (shadowCellOp.isPresent()) {
                saveLastTimestampedCell(lastTimestampedCellsInRow, cell, shadowCellOp.get());
            } else {
                Optional<CommitTimestamp> commitTimestamp = queryCommitTimestamp(cell);
                if (commitTimestamp.isPresent() && commitTimestamp.get().isValid()) {
                    // Build the missing shadow cell...
                    byte[] shadowCellValue = Bytes.toBytes(commitTimestamp.get().getValue());
                    Cell shadowCell = CellUtils.buildShadowCellFromCell(cell, shadowCellValue);
                    saveLastTimestampedCell(lastTimestampedCellsInRow, cell, shadowCell);
                } else {
                    LOG.trace("Discarding cell {}", cell);
                }
            }
        }
        retainLastTimestampedCellsSaved(currentRowWorthValues, lastTimestampedCellsInRow);

        // 4) Sort the list
        Collections.sort(currentRowWorthValues, KeyValue.COMPARATOR);
    }

    // Chomp current row worth values up to the limit
    if (currentRowWorthValues.size() <= limit) {
        result.addAll(currentRowWorthValues);
        currentRowWorthValues.clear();
    } else {
        result.addAll(currentRowWorthValues.subList(0, limit));
        currentRowWorthValues.subList(0, limit).clear();
    }
    LOG.trace("Results to preserve {}", result);

    return hasMoreRows;
}

From source file:org.eclipse.xtext.ide.editor.contentassist.IndentationAwareCompletionPrefixProvider.java

private LinkedList<ILeafNode> collectLeafsWithSameOffset(ILeafNode candidate,
        PeekingIterator<ILeafNode> iterator) {
    LinkedList<ILeafNode> sameOffset = Lists.newLinkedList();
    sameOffset.add(candidate);//from  ww w.  j av a2s .c  om
    int offset = candidate.getTotalOffset();
    while (iterator.hasNext()) {
        ILeafNode peek = iterator.peek();
        if (peek.getTotalOffset() == offset) {
            sameOffset.add(peek);
            iterator.next();
        } else {
            break;
        }
    }
    return sameOffset;
}

From source file:com.techcavern.pircbotz.Channel.java

/**
 * Sets the mode of the channel. If there is a getMode() waiting on this,
 * fire it./*from   w w w  . ja  v a2s . c  om*/
 * @param mode
 */
protected void setMode(String mode, ImmutableList<String> modeParsed) {
    this.mode = mode;
    this.modeStale = false;
    if (modeLatch != null)
        modeLatch.countDown();

    //Parse out mode
    PeekingIterator<String> params = Iterators.peekingIterator(modeParsed.iterator());

    //Process modes letter by letter, grabbing paramaters as needed
    boolean adding = true;
    String modeLetters = params.next();
    for (int i = 0; i < modeLetters.length(); i++) {
        char curModeChar = modeLetters.charAt(i);
        if (curModeChar == '+')
            adding = true;
        else if (curModeChar == '-')
            adding = false;
        else {
            ChannelModeHandler modeHandler = bot.getConfiguration().getChannelModeHandlers().get(curModeChar);
            if (modeHandler != null)
                modeHandler.handleMode(bot, this, null, params, adding, false);
        }
    }
}

From source file:org.eclipse.milo.opcua.binaryschema.AbstractCodec.java

@Override
public void encode(SerializationContext context, StructureT structure, OpcUaBinaryStreamEncoder encoder)
        throws UaSerializationException {

    LinkedHashMap<String, MemberT> members = new LinkedHashMap<>(getMembers(structure));

    PeekingIterator<FieldType> fieldIterator = Iterators.peekingIterator(structuredType.getField().iterator());

    while (fieldIterator.hasNext()) {
        FieldType field = fieldIterator.next();

        if (!fieldIsPresent(field, members)) {
            continue;
        }/*  w  w  w.jav  a2 s.c om*/

        String typeName = field.getTypeName().getLocalPart();
        String typeNamespace = field.getTypeName().getNamespaceURI();

        MemberT member = members.get(field.getName());

        boolean typeNamespaceIsUa = Namespaces.OPC_UA.equals(typeNamespace)
                || Namespaces.OPC_UA_BSD.equals(typeNamespace);

        if (fieldIsScalar(field)) {
            Object scalarValue = memberTypeToOpcUaScalar(member, typeName);

            if (typeNamespaceIsUa && WRITERS.containsKey(typeName)) {
                WRITERS.get(typeName).accept(encoder, scalarValue);
            } else {
                context.encode(typeNamespace, typeName, scalarValue, encoder);
            }
        } else {
            if (field.isIsLengthInBytes()) {
                throw new UaSerializationException(StatusCodes.Bad_EncodingError,
                        "IsLengthInBytes=true not supported");
            }

            int length = fieldLength(field, members);

            if ("Bit".equals(typeName) && typeNamespaceIsUa) {
                Number number = (Number) memberTypeToOpcUaArray(member, typeName);
                BigInteger bi = BigInteger.valueOf(number.longValue());

                for (int i = 0; i < length; i++) {
                    encoder.writeBit(bi.shiftRight(i).and(BigInteger.ONE).intValue());
                }
            } else {
                Object[] valueArray = (Object[]) memberTypeToOpcUaArray(member, typeName);

                if (valueArray != null) {
                    if (typeNamespaceIsUa && WRITERS.containsKey(typeName)) {
                        for (int i = 0; i < length; i++) {
                            Object value = valueArray[i];

                            WRITERS.get(typeName).accept(encoder, value);
                        }
                    } else {
                        for (int i = 0; i < length; i++) {
                            Object value = valueArray[i];

                            context.encode(typeNamespace, typeName, value, encoder);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.digitalpetri.opcua.server.ctt.CttNamespace.java

private UaObjectNode addFoldersToRoot(UaNode root, String path) {
    if (path.startsWith("/"))
        path = path.substring(1, path.length());
    String[] elements = path.split("/");

    LinkedList<UaObjectNode> folderNodes = processPathElements(Lists.newArrayList(elements),
            Lists.newArrayList(), Lists.newLinkedList());

    UaObjectNode firstNode = folderNodes.getFirst();

    if (!nodes.containsKey(firstNode.getNodeId())) {
        nodes.put(firstNode.getNodeId(), firstNode);

        nodes.get(root.getNodeId()).addReference(new Reference(root.getNodeId(), Identifiers.Organizes,
                firstNode.getNodeId().expanded(), firstNode.getNodeClass(), true));

        logger.debug("Added reference: {} -> {}", root.getNodeId(), firstNode.getNodeId());
    }/*w w w  .ja v  a 2 s  .  c o m*/

    PeekingIterator<UaObjectNode> iterator = Iterators.peekingIterator(folderNodes.iterator());

    while (iterator.hasNext()) {
        UaObjectNode node = iterator.next();

        nodes.putIfAbsent(node.getNodeId(), node);

        if (iterator.hasNext()) {
            UaObjectNode next = iterator.peek();

            if (!nodes.containsKey(next.getNodeId())) {
                nodes.put(next.getNodeId(), next);

                nodes.get(node.getNodeId()).addReference(new Reference(node.getNodeId(), Identifiers.Organizes,
                        next.getNodeId().expanded(), next.getNodeClass(), true));

                logger.debug("Added reference: {} -> {}", node.getNodeId(), next.getNodeId());
            }
        }
    }

    return folderNodes.getLast();
}

From source file:org.eclipse.milo.opcua.binaryschema.AbstractCodec.java

@Override
public StructureT decode(SerializationContext context, OpcUaBinaryStreamDecoder decoder)
        throws UaSerializationException {

    LinkedHashMap<String, MemberT> members = new LinkedHashMap<>();

    PeekingIterator<FieldType> fieldIterator = Iterators.peekingIterator(structuredType.getField().iterator());

    while (fieldIterator.hasNext()) {
        FieldType field = fieldIterator.next();
        String fieldName = field.getName();
        String typeName = field.getTypeName().getLocalPart();
        String typeNamespace = field.getTypeName().getNamespaceURI();

        if (!fieldIsPresent(field, members)) {
            continue;
        }/*from   w w  w .j  a v  a  2  s.c o m*/

        boolean typeNamespaceIsUa = Namespaces.OPC_UA.equals(typeNamespace)
                || Namespaces.OPC_UA_BSD.equals(typeNamespace);

        if (fieldIsScalar(field)) {
            if (typeNamespaceIsUa && READERS.containsKey(typeName)) {
                Object value = READERS.get(typeName).apply(decoder);

                members.put(fieldName, opcUaToMemberTypeScalar(fieldName, value, typeName));
            } else {
                Object value = context.decode(typeNamespace, typeName, decoder);

                members.put(fieldName, opcUaToMemberTypeScalar(fieldName, value, typeName));
            }
        } else {
            if (field.isIsLengthInBytes()) {
                throw new UaSerializationException(StatusCodes.Bad_DecodingError,
                        "IsLengthInBytes=true not supported");
            }

            int length = fieldLength(field, members);

            if ("Bit".equals(typeName) && typeNamespaceIsUa) {
                BigInteger bitAccumulation = BigInteger.valueOf(0L);

                for (int i = 0; i < length; i++) {
                    BigInteger bitValue = BigInteger.valueOf(decoder.readBit());

                    bitAccumulation = bitAccumulation.or(bitValue.shiftLeft(i));
                }

                members.put(fieldName, opcUaToMemberTypeArray(fieldName, bitAccumulation.intValue(), typeName));
            } else {
                Object[] values = new Object[length];

                if (typeNamespaceIsUa && READERS.containsKey(typeName)) {
                    for (int i = 0; i < length; i++) {
                        Object value = READERS.get(typeName).apply(decoder);

                        values[i] = value;
                    }
                } else {
                    for (int i = 0; i < length; i++) {
                        Object value = context.decode(typeNamespace, typeName, decoder);

                        values[i] = value;
                    }
                }

                members.put(fieldName, opcUaToMemberTypeArray(fieldName, values, typeName));
            }
        }
    }

    return createStructure(structuredType.getName(), members);
}