List of usage examples for com.google.common.collect PeekingIterator hasNext
boolean hasNext();
From source file:org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyFlatBatchImpl.java
static Map<Range<Integer>, Batch> mapBatchesToRanges(final List<Batch> inputBatchBag, final int failureIndexLimit) { final Map<Range<Integer>, Batch> batchMap = new LinkedHashMap<>(); final PeekingIterator<Batch> batchPeekingIterator = Iterators.peekingIterator(inputBatchBag.iterator()); while (batchPeekingIterator.hasNext()) { final Batch batch = batchPeekingIterator.next(); final int nextBatchOrder = batchPeekingIterator.hasNext() ? batchPeekingIterator.peek().getBatchOrder() : failureIndexLimit;/* w w w . j av a 2 s . c o m*/ batchMap.put(Range.closed(batch.getBatchOrder(), nextBatchOrder - 1), batch); } return batchMap; }
From source file:com.github.rinde.rinsim.geom.Graphs.java
/** * Create a path of connections on the specified {@link Graph} using the * specified {@link Point}s. If the points <code>A, B, C</code> are specified, * the two connections: <code>A -> B</code> and <code>B -> C</code> will * be added to the graph.//from ww w .j a v a 2 s. com * @param graph The graph to which the connections will be added. * @param path Points that will be treated as a path. * @param <E> The type of connection data. */ public static <E extends ConnectionData> void addPath(Graph<E> graph, Iterable<Point> path) { final PeekingIterator<Point> it = Iterators.peekingIterator(path.iterator()); while (it.hasNext()) { final Point n = it.next(); if (it.hasNext()) { graph.addConnection(n, it.peek()); } } }
From source file:r.base.Calls.java
private static boolean hasNextUnTagged(PeekingIterator<PairList.Node> it) { return it.hasNext() && !it.peek().hasTag(); }
From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java
/** * The Collection provided to this function has to be sorted and strictly increasing. *//* w ww .j av a2 s.c o m*/ public static <T> Iterator<RowResult<T>> createRowView(final Collection<Map.Entry<Cell, T>> sortedIterator) { final PeekingIterator<Entry<Cell, T>> it = Iterators.peekingIterator(sortedIterator.iterator()); Iterator<Map.Entry<byte[], SortedMap<byte[], T>>> resultIt = new AbstractIterator<Map.Entry<byte[], SortedMap<byte[], T>>>() { byte[] row = null; SortedMap<byte[], T> map = null; @Override protected Entry<byte[], SortedMap<byte[], T>> computeNext() { if (!it.hasNext()) { return endOfData(); } row = it.peek().getKey().getRowName(); ImmutableSortedMap.Builder<byte[], T> mapBuilder = ImmutableSortedMap .orderedBy(UnsignedBytes.lexicographicalComparator()); while (it.hasNext()) { Entry<Cell, T> peek = it.peek(); if (!Arrays.equals(peek.getKey().getRowName(), row)) { break; } mapBuilder.put(peek.getKey().getColumnName(), peek.getValue()); it.next(); } map = mapBuilder.build(); return Maps.immutableEntry(row, map); } }; return RowResults.viewOfEntries(resultIt); }
From source file:net.tridentsdk.reflect.Injector.java
/** * Creates a new object which has injectable fields, using the injectable constructor * * @param clazz the class to instantiate * @param args the parameters, not including the injectable classes, in order of declaration * @param <T> the type to return/*from w w w . ja va 2 s . c o m*/ * @return the new object */ public static <T> T newObject(Class<T> clazz, Object... args) { for (Map.Entry<Constructor, Class<?>[]> entry : findConstructors(clazz).entrySet()) { List<Object> arguments = Lists.newArrayList(); Constructor constructor = entry.getKey(); Class<?>[] constructorParameters = entry.getValue(); PeekingIterator<Object> iterator = Iterators.peekingIterator(Iterators.forArray(args)); if (!checkArray(args, constructorParameters)) continue; for (Class<?> c : constructorParameters) { Producer<?> producer = injectors.get(c); Inject inject = (Inject) constructor.getAnnotation(Inject.class); if (iterator.hasNext()) { if (iterator.peek().getClass() == c) { arguments.add(iterator.next()); continue; } } if (producer == null) { if (iterator.hasNext()) { if (iterator.peek().getClass() == c) { arguments.add(iterator.next()); continue; } } TridentLogger.error(new IllegalArgumentException("Constructor " + clazz.getName() + "(" + Arrays.toString(constructorParameters).replaceAll("class ", "").replaceAll("\\[", "") .replaceAll("\\]", "") + ") " + "does not provide or registered parameter " + c.getName())); return null; } else { if (inject.meta() == Class.class) { arguments.add(producer.produce()); } else { arguments.add(producer.produce(inject.meta())); } } } try { T t = (T) constructor.newInstance(arguments.toArray()); for (Field field : findFields(clazz)) { setField(t, field); } return t; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { TridentLogger.error(e); return null; } } try { T t = clazz.newInstance(); for (Field field : findFields(clazz)) { setField(t, field); } return t; } catch (InstantiationException | IllegalAccessException e) { TridentLogger.error(e); return null; } }
From source file:org.apache.cassandra.db.rows.Rows.java
/** * Given the result ({@code merged}) of merging multiple {@code inputs}, signals the difference between * each input and {@code merged} to {@code diffListener}. * <p>/*www . j a v a 2s .c o m*/ * Note that this method doesn't only emit cells etc where there's a difference. The listener is informed * of every corresponding entity between the merged and input rows, including those that are equal. * * @param diffListener the listener to which to signal the differences between the inputs and the merged result. * @param merged the result of merging {@code inputs}. * @param inputs the inputs whose merge yielded {@code merged}. */ public static void diff(RowDiffListener diffListener, Row merged, Row... inputs) { Clustering clustering = merged.clustering(); LivenessInfo mergedInfo = merged.primaryKeyLivenessInfo().isEmpty() ? null : merged.primaryKeyLivenessInfo(); Row.Deletion mergedDeletion = merged.deletion().isLive() ? null : merged.deletion(); for (int i = 0; i < inputs.length; i++) { Row input = inputs[i]; LivenessInfo inputInfo = input == null || input.primaryKeyLivenessInfo().isEmpty() ? null : input.primaryKeyLivenessInfo(); Row.Deletion inputDeletion = input == null || input.deletion().isLive() ? null : input.deletion(); if (mergedInfo != null || inputInfo != null) diffListener.onPrimaryKeyLivenessInfo(i, clustering, mergedInfo, inputInfo); if (mergedDeletion != null || inputDeletion != null) diffListener.onDeletion(i, clustering, mergedDeletion, inputDeletion); } List<Iterator<ColumnData>> inputIterators = new ArrayList<>(1 + inputs.length); inputIterators.add(merged.iterator()); for (Row row : inputs) inputIterators.add(row == null ? Collections.emptyIterator() : row.iterator()); Iterator<?> iter = MergeIterator.get(inputIterators, ColumnData.comparator, new MergeIterator.Reducer<ColumnData, Object>() { ColumnData mergedData; ColumnData[] inputDatas = new ColumnData[inputs.length]; public void reduce(int idx, ColumnData current) { if (idx == 0) mergedData = current; else inputDatas[idx - 1] = current; } protected Object getReduced() { for (int i = 0; i != inputDatas.length; i++) { ColumnData input = inputDatas[i]; if (mergedData != null || input != null) { ColumnDefinition column = (mergedData != null ? mergedData : input).column; if (column.isSimple()) { diffListener.onCell(i, clustering, (Cell) mergedData, (Cell) input); } else { ComplexColumnData mergedData = (ComplexColumnData) this.mergedData; ComplexColumnData inputData = (ComplexColumnData) input; if (mergedData == null) { // Everything in inputData has been shadowed if (!inputData.complexDeletion().isLive()) diffListener.onComplexDeletion(i, clustering, column, null, inputData.complexDeletion()); for (Cell inputCell : inputData) diffListener.onCell(i, clustering, null, inputCell); } else if (inputData == null) { // Everything in inputData is new if (!mergedData.complexDeletion().isLive()) diffListener.onComplexDeletion(i, clustering, column, mergedData.complexDeletion(), null); for (Cell mergedCell : mergedData) diffListener.onCell(i, clustering, mergedCell, null); } else { if (!mergedData.complexDeletion().isLive() || !inputData.complexDeletion().isLive()) diffListener.onComplexDeletion(i, clustering, column, mergedData.complexDeletion(), inputData.complexDeletion()); PeekingIterator<Cell> mergedCells = Iterators .peekingIterator(mergedData.iterator()); PeekingIterator<Cell> inputCells = Iterators .peekingIterator(inputData.iterator()); while (mergedCells.hasNext() && inputCells.hasNext()) { int cmp = column.cellPathComparator().compare(mergedCells.peek().path(), inputCells.peek().path()); if (cmp == 0) diffListener.onCell(i, clustering, mergedCells.next(), inputCells.next()); else if (cmp < 0) diffListener.onCell(i, clustering, mergedCells.next(), null); else // cmp > 0 diffListener.onCell(i, clustering, null, inputCells.next()); } while (mergedCells.hasNext()) diffListener.onCell(i, clustering, mergedCells.next(), null); while (inputCells.hasNext()) diffListener.onCell(i, clustering, null, inputCells.next()); } } } } return null; } protected void onKeyChange() { mergedData = null; Arrays.fill(inputDatas, null); } }); while (iter.hasNext()) iter.next(); }
From source file:com.google.googlejavaformat.java.javadoc.JavadocLexer.java
private static void deindentPreCodeBlock(ImmutableList.Builder<Token> output, PeekingIterator<Token> tokens) { Deque<Token> saved = new ArrayDeque<>(); output.add(new Token(LITERAL, tokens.next().getValue().trim())); while (tokens.hasNext() && tokens.peek().getType() != PRE_CLOSE_TAG) { Token token = tokens.next();//from ww w. jav a2 s . com saved.addLast(token); } while (!saved.isEmpty() && saved.peekFirst().getType() == FORCED_NEWLINE) { saved.removeFirst(); } while (!saved.isEmpty() && saved.peekLast().getType() == FORCED_NEWLINE) { saved.removeLast(); } if (saved.isEmpty()) { return; } // move the trailing `}` to its own line Token last = saved.peekLast(); boolean trailingBrace = false; if (last.getType() == LITERAL && last.getValue().endsWith("}")) { saved.removeLast(); if (last.length() > 1) { saved.addLast(new Token(LITERAL, last.getValue().substring(0, last.getValue().length() - 1))); saved.addLast(new Token(FORCED_NEWLINE, null)); } trailingBrace = true; } int trim = -1; for (Token token : saved) { if (token.getType() == LITERAL) { int idx = CharMatcher.isNot(' ').indexIn(token.getValue()); if (idx != -1 && (trim == -1 || idx < trim)) { trim = idx; } } } output.add(new Token(FORCED_NEWLINE, "\n")); for (Token token : saved) { if (token.getType() == LITERAL) { output.add(new Token(LITERAL, trim > 0 && token.length() > trim ? token.getValue().substring(trim) : token.getValue())); } else { output.add(token); } } if (trailingBrace) { output.add(new Token(LITERAL, "}")); } else { output.add(new Token(FORCED_NEWLINE, "\n")); } }
From source file:com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService.java
private static Iterator<Entry<Key, byte[]>> takeCell(final PeekingIterator<Entry<Key, byte[]>> iter, final Key key) { return new AbstractIterator<Entry<Key, byte[]>>() { @Override/*from www .j a v a 2 s.c o m*/ protected Entry<Key, byte[]> computeNext() { if (!iter.hasNext()) { return endOfData(); } Entry<Key, byte[]> next = iter.peek(); Key nextKey = next.getKey(); if (nextKey.matchesCell(key)) { return iter.next(); } return endOfData(); } }; }
From source file:org.kiji.schema.impl.cassandra.CassandraKijiPartition.java
/** * Convert a set of (start-token, host) pairs into a set of (token-range, host) pairs. * * Package private for testing.//from w w w . java 2s . c om * * @param startTokens The set of start tokens with hosts. * @return The token corresponding token ranges. */ static Map<Range<Long>, InetAddress> getTokenRanges(final SortedMap<Long, InetAddress> startTokens) { ImmutableMap.Builder<Range<Long>, InetAddress> tokenRangesBldr = ImmutableMap.builder(); final PeekingIterator<Entry<Long, InetAddress>> startTokensItr = Iterators .peekingIterator(startTokens.entrySet().iterator()); // Add a range for [-, firstStartToken) owned by the final key (the wrap-around range). // For more information on Casandra VNode token ranges: // http://www.datastax.com/dev/blog/virtual-nodes-in-cassandra-1-2 tokenRangesBldr.put(Range.lessThan(startTokens.firstKey()), startTokens.get(startTokens.lastKey())); while (startTokensItr.hasNext()) { Entry<Long, InetAddress> startToken = startTokensItr.next(); if (!startTokensItr.hasNext()) { // The final start token // Add a range for [lastStartToken, ) tokenRangesBldr.put(Range.atLeast(startToken.getKey()), startToken.getValue()); } else { // Add a range for [thisStartToken, nextStartToken) tokenRangesBldr.put(Range.closedOpen(startToken.getKey(), startTokensItr.peek().getKey()), startToken.getValue()); } } final Map<Range<Long>, InetAddress> tokenRanges = tokenRangesBldr.build(); // Check that the returned ranges are coherent; most importantly that all possible tokens fall // within the returned range set. if (startTokens.size() + 1 != tokenRanges.size()) { throw new InternalKijiError( String.format("Unexpected number of token ranges. start-tokens: %s, token-ranges: %s.", startTokens.size(), tokenRanges.size())); } final RangeSet<Long> ranges = TreeRangeSet.create(); for (Range<Long> tokenRange : tokenRanges.keySet()) { ranges.add(tokenRange); } if (!ranges.encloses(Range.closed(Long.MIN_VALUE, Long.MAX_VALUE))) { throw new InternalKijiError("Token range does not include all possible tokens."); } return tokenRanges; }
From source file:com.google.gerrit.server.mail.receive.HtmlParser.java
/** * Parses comments from html email.//w w w .ja v a2 s .c om * * @param email MailMessage as received from the email service. * @param comments A specific set of comments as sent out in the original notification email. * Comments are expected to be in the same order as they were sent out to in the email * @param changeUrl Canonical change URL that points to the change on this Gerrit instance. * Example: https://go-review.googlesource.com/#/c/91570 * @return List of MailComments parsed from the html part of the email. */ public static List<MailComment> parse(MailMessage email, Collection<Comment> comments, String changeUrl) { // TODO(hiesel) Add support for Gmail Mobile // TODO(hiesel) Add tests for other popular email clients // This parser goes though all html elements in the email and checks for // matching patterns. It keeps track of the last file and comments it // encountered to know in which context a parsed comment belongs. // It uses the href attributes of <a> tags to identify comments sent out by // Gerrit as these are generally more reliable then the text captions. List<MailComment> parsedComments = new ArrayList<>(); Document d = Jsoup.parse(email.htmlContent()); PeekingIterator<Comment> iter = Iterators.peekingIterator(comments.iterator()); String lastEncounteredFileName = null; Comment lastEncounteredComment = null; for (Element e : d.body().getAllElements()) { String elementName = e.tagName(); boolean isInBlockQuote = e.parents().stream().filter(p -> p.tagName().equals("blockquote")).findAny() .isPresent(); if (elementName.equals("a")) { String href = e.attr("href"); // Check if there is still a next comment that could be contained in // this <a> tag if (!iter.hasNext()) { continue; } Comment perspectiveComment = iter.peek(); if (href.equals(ParserUtil.filePath(changeUrl, perspectiveComment))) { if (lastEncounteredFileName == null || !lastEncounteredFileName.equals(perspectiveComment.key.filename)) { // Not a file-level comment, but users could have typed a comment // right after this file annotation to create a new file-level // comment. If this file has a file-level comment, we have already // set lastEncounteredComment to that file-level comment when we // encountered the file link and should not reset it now. lastEncounteredFileName = perspectiveComment.key.filename; lastEncounteredComment = null; } else if (perspectiveComment.lineNbr == 0) { // This was originally a file-level comment lastEncounteredComment = perspectiveComment; iter.next(); } } else if (ParserUtil.isCommentUrl(href, changeUrl, perspectiveComment)) { // This is a regular inline comment lastEncounteredComment = perspectiveComment; iter.next(); } } else if (!isInBlockQuote && elementName.equals("div") && !e.className().startsWith("gmail")) { // This is a comment typed by the user // Replace non-breaking spaces and trim string String content = e.ownText().replace('\u00a0', ' ').trim(); if (!Strings.isNullOrEmpty(content)) { if (lastEncounteredComment == null && lastEncounteredFileName == null) { // Remove quotation line, email signature and // "Sent from my xyz device" content = ParserUtil.trimQuotation(content); // TODO(hiesel) Add more sanitizer if (!Strings.isNullOrEmpty(content)) { parsedComments.add( new MailComment(content, null, null, MailComment.CommentType.CHANGE_MESSAGE)); } } else if (lastEncounteredComment == null) { parsedComments.add(new MailComment(content, lastEncounteredFileName, null, MailComment.CommentType.FILE_COMMENT)); } else { parsedComments.add(new MailComment(content, null, lastEncounteredComment, MailComment.CommentType.INLINE_COMMENT)); } } } } return parsedComments; }