Example usage for com.google.common.collect Iterators advance

List of usage examples for com.google.common.collect Iterators advance

Introduction

In this page you can find the example usage for com.google.common.collect Iterators advance.

Prototype

public static int advance(Iterator<?> iterator, int numberToAdvance) 

Source Link

Document

Calls next() on iterator , either numberToAdvance times or until hasNext() returns false , whichever comes first.

Usage

From source file:com.yandex.yoctodb.v1.immutable.V1Database.java

@Override
public int executeAndUnlimitedCount(@NotNull final Query query, @NotNull final DocumentProcessor processor) {
    final BitSet docs = query.filteredUnlimited(this, bitSetPool);
    if (docs == null) {
        return 0;
    }/*from   ww w.  j a  v a 2 s .  co  m*/

    assert !docs.isEmpty();

    final int result = docs.cardinality();
    final Iterator<? extends ScoredDocument<?>> unlimited;
    if (result == getDocumentCount()) {
        unlimited = query.sortedUnlimited(new ReadOnlyOneBitSet(getDocumentCount()), this, bitSetPool);
    } else {
        unlimited = query.sortedUnlimited(docs, this, bitSetPool);
    }

    if (query.getSkip() != 0) {
        Iterators.advance(unlimited, query.getSkip());
    }

    final Iterator<? extends ScoredDocument<?>> limited;
    if (query.getLimit() == Integer.MAX_VALUE) {
        limited = unlimited;
    } else {
        limited = Iterators.limit(unlimited, query.getLimit());
    }

    while (limited.hasNext()) {
        if (!processor.process(limited.next().getDocument(), this)) {
            return result;
        }
    }

    return result;
}

From source file:org.apache.drill.exec.store.hbase.config.HBasePersistentStore.java

@Override
public Iterator<Entry<String, V>> getRange(int skip, int take) {
    final Iterator<Entry<String, V>> iter = new Iter(take);
    Iterators.advance(iter, skip);
    return Iterators.limit(iter, take);
}

From source file:co.cask.cdap.api.dataset.lib.CounterTimeseriesTable.java

/**
 * Reads entries for a given time range and returns an <code>Iterator<Counter></code>.
 * Provides the same functionality as {@link #read(byte[], long, long, byte[][]) read(byte[], long, long, byte[]...)}
 * but accepts additional parameters for pagination purposes.
 *
 * @param counter name of the counter to read
 * @param startTime defines start of the time range to read, inclusive
 * @param endTime defines end of the time range to read, inclusive
 * @param offset the number of initial entries to ignore and not add to the results
 * @param limit upper limit on number of results returned. If limit is exceeded, the first <code>limit</code> results
 *              are returned./*from   w  ww.  ja v  a2  s. co  m*/
 * @param tags a set of tags which entries returned must contain. Tags for entries are defined at write-time and an
 *             entry is only returned if it contains all of these tags.
 * @return an iterator over entries that satisfy provided conditions
 */
public Iterator<Counter> read(byte[] counter, long startTime, long endTime, int offset, int limit,
        byte[]... tags) {
    Iterator<Counter> iterator = read(counter, startTime, endTime, tags);
    iterator = Iterators.limit(iterator, limit + offset);
    Iterators.advance(iterator, offset);
    return iterator;
}

From source file:de.kussm.chain.ChainLayouter.java

private void restoreInsertionPoint() throws NotEnoughSpaceException {
    if (insertionPoint == null) {
        throw new NotEnoughSpaceException();
    }//from w w  w  .  j ava2  s  . co  m
    this.currentPosition = insertionPoint.currentPosition;
    this.placedReceivers = insertionPoint.placedReceivers;
    this.placedTransmitters = insertionPoint.placedTransmitters;
    this.cntDirections = insertionPoint.cntDirections;
    this.itDirections = dirs.iterator();
    Iterators.advance(this.itDirections, cntDirections);
    this.prevDirection = insertionPoint.prevDirection;
    this.nextDirection = insertionPoint.nextDirection;
    this.placedChainLinks = insertionPoint.placedChainLinks;
    this.chainLinkIndex = insertionPoint.chainLinkIndex;
    this.currentChainLink = insertionPoint.currentChainLink;
}

From source file:com.ethlo.geodata.RtreeRepository.java

public Iterator<Long> findNear(Coordinates point, double maxDistanceInKilometers, Pageable pageable) {
    final Iterator<Entry<RTreePayload, Geometry>> e = tree
            .nearest(Geometries.point(point.getLng(), point.getLat()), maxDistanceInKilometers,
                    pageable.getOffset() + pageable.getPageSize())
            .toBlocking().getIterator();
    final Iterator<Long> iter = new AbstractIterator<Long>() {
        @Override/*from   w w w. j a  va2  s .co m*/
        protected Long computeNext() {
            if (e.hasNext()) {
                return e.next().value().getId();
            }
            return endOfData();
        }
    };
    Iterators.advance(iter, pageable.getOffset());
    return iter;
}

From source file:org.fcrepo.kernel.api.utils.iterators.RdfStream.java

/**
 * As {@link Iterators#advance(Iterator, int)} while maintaining context.
 *
 * @param skipNum the skip number//from w ww .j  a  v a  2 s  . c o  m
 * @return RDFStream
 */
public RdfStream skip(final Integer skipNum) {
    Iterators.advance(this, skipNum);
    return this;
}

From source file:com.mattc.launcher.util.Console.java

/**
 * Takes a Throwable and prints out the Stack Trace. This is <br />
 * basically equivalent to Throwable.printStackTrace().
 * //from w w w . j a v  a2 s.  c o m
 * @param e
 */
public static void exception(Throwable e) {
    final Splitter splitter = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings();
    final Iterator<String> trace = splitter.split(Throwables.getStackTraceAsString(e)).iterator();

    error("===============EXCEPTION===============");
    error("");
    error(String.format("MESSAGE (T:%s): %s", e.getClass().getSimpleName(), e.getLocalizedMessage()));
    error(" " + trace.next());
    Iterators.advance(trace, 1);

    while (trace.hasNext()) {
        error(" \t" + trace.next());
    }

    logger.error("");
    logger.error("===============EXCEPTION===============");
}

From source file:com.yandex.yoctodb.v1.immutable.V1CompositeDatabase.java

@Override
public int executeAndUnlimitedCount(@NotNull final Query query, @NotNull final DocumentProcessor processor) {
    int result = 0;
    final Iterator<ScoredDocument<?>> iterator;

    // Doing merging iff there is sorting
    if (query.hasSorting()) {
        final List<Iterator<? extends ScoredDocument<?>>> results = new ArrayList<>(databases.size());
        for (IndexedDatabase db : databases) {
            final BitSet docs = query.filteredUnlimited(db, bitSetPool);
            if (docs != null) {
                assert !docs.isEmpty();

                final int dbSize = db.getDocumentCount();
                final int count = docs.cardinality();
                final BitSet filter;
                if (count == dbSize) {
                    filter = new ReadOnlyOneBitSet(dbSize);
                } else {
                    filter = docs;/*from w  w w . j av  a  2s  . c  om*/
                }
                results.add(query.sortedUnlimited(filter, db, bitSetPool));
                result += count;
            }
        }

        if (results.isEmpty()) {
            return 0;
        }

        iterator = Iterators.mergeSorted(results, SCORED_DOCUMENT_COMPARATOR);
    } else {
        final List<QueryContext> results = new ArrayList<>(databases.size());
        for (IndexedDatabase db : databases) {
            final BitSet docs = query.filteredUnlimited(db, bitSetPool);
            if (docs != null) {
                assert !docs.isEmpty();

                final int dbSize = db.getDocumentCount();
                final int count = docs.cardinality();
                final BitSet filter;
                if (count == dbSize) {
                    filter = new ReadOnlyOneBitSet(dbSize);
                } else {
                    filter = docs;
                }
                results.add(new QueryContext(filter, db, bitSetPool));
                result += count;
            }
        }

        if (results.isEmpty()) {
            return 0;
        }

        iterator = Iterators.concat(new SortResultIterator(query, results.iterator()));
    }

    // Skipping values
    if (query.getSkip() != 0) {
        Iterators.advance(iterator, query.getSkip());
    }

    // Limited
    final Iterator<ScoredDocument<?>> limitedIterator;
    if (query.getLimit() == Integer.MAX_VALUE) {
        limitedIterator = iterator;
    } else {
        limitedIterator = Iterators.limit(iterator, query.getLimit());
    }

    while (limitedIterator.hasNext()) {
        final ScoredDocument<?> document = limitedIterator.next();
        if (!processor.process(document.getDocument(), document.getDatabase())) {
            return result;
        }
    }

    return result;
}

From source file:co.cask.cdap.api.dataset.lib.TimeseriesTable.java

/**
 * Reads entries for a given time range and returns an <code>Iterator<Entry></code>.
 * Provides the same functionality as {@link #read(byte[], long, long, byte[][]) read(byte[], long, long, byte[]...)} 
 * but accepts additional parameters for pagination purposes.
 * NOTE: A limit is placed on the max number of time intervals to be scanned during a read, as defined by
 * {@link #MAX_ROWS_TO_SCAN_PER_READ}.//from  ww  w.j  ava 2  s .c  o m
 *
 * @param key key of the entries to read
 * @param startTime defines start of the time range to read, inclusive
 * @param endTime defines end of the time range to read, inclusive
 * @param offset the number of initial entries to ignore and not add to the results
 * @param limit upper limit on number of results returned. If limit is exceeded, the first <code>limit</code> results
 *              are returned
 * @param tags a set of tags which entries returned must contain. Tags for entries are defined at write-time and an
 *             entry is only returned if it contains all of these tags.
 *
 * @return an iterator over entries that satisfy provided conditions
 * @throws IllegalArgumentException when provided condition is incorrect
 */
public final Iterator<Entry> read(byte[] key, long startTime, long endTime, int offset, int limit,
        byte[]... tags) {
    Iterator<Entry> iterator = read(key, startTime, endTime, tags);
    iterator = Iterators.limit(iterator, limit + offset);
    Iterators.advance(iterator, offset);
    return iterator;
}

From source file:org.locationtech.geogig.web.api.commands.Log.java

/**
 * Runs the command and builds the appropriate response
 * /*  w  w  w. j a v a 2s.com*/
 * @param context - the context to use for this command
 * 
 * @throws IllegalArgumentException
 */
@Override
public void run(final CommandContext context) {
    final Context geogig = this.getCommandLocator(context);

    LogOp op = geogig.command(LogOp.class).setFirstParentOnly(firstParentOnly);

    if (skip != null) {
        op.setSkip(skip.intValue());
    }
    if (limit != null) {
        op.setLimit(limit.intValue());
    }

    if (this.sinceTime != null || this.untilTime != null) {
        Date since = new Date(0);
        Date until = new Date();
        if (this.sinceTime != null) {
            since = new Date(geogig.command(ParseTimestamp.class).setString(this.sinceTime).call());
        }
        if (this.untilTime != null) {
            until = new Date(geogig.command(ParseTimestamp.class).setString(this.untilTime).call());
        }
        op.setTimeRange(new Range<Date>(Date.class, since, until));
    }

    if (this.since != null) {
        Optional<ObjectId> since;
        since = geogig.command(RevParse.class).setRefSpec(this.since).call();
        Preconditions.checkArgument(since.isPresent(), "Object not found '%s'", this.since);
        op.setSince(since.get());
    }
    if (this.until != null) {
        Optional<ObjectId> until;
        until = geogig.command(RevParse.class).setRefSpec(this.until).call();
        Preconditions.checkArgument(until.isPresent(), "Object not found '%s'", this.until);
        op.setUntil(until.get());
    }
    if (paths != null && !paths.isEmpty()) {
        for (String path : paths) {
            op.addPath(path);
        }
    }

    final Iterator<RevCommit> log = op.call();

    Iterators.advance(log, page * elementsPerPage);

    if (countChanges) {
        final String pathFilter;
        if (paths != null && !paths.isEmpty()) {
            pathFilter = paths.get(0);
        } else {
            pathFilter = null;
        }
        Function<RevCommit, CommitWithChangeCounts> changeCountFunctor = new Function<RevCommit, CommitWithChangeCounts>() {

            @Override
            public CommitWithChangeCounts apply(RevCommit input) {
                ObjectId parent = ObjectId.NULL;
                if (input.getParentIds().size() > 0) {
                    parent = input.getParentIds().get(0);
                }
                int added = 0;
                int modified = 0;
                int removed = 0;

                // If it's a shallow clone, the commit may not exist
                if (parent.equals(ObjectId.NULL) || geogig.objectDatabase().exists(parent)) {
                    final Iterator<DiffEntry> diff = geogig.command(DiffOp.class).setOldVersion(parent)
                            .setNewVersion(input.getId()).setFilter(pathFilter).call();

                    while (diff.hasNext()) {
                        DiffEntry entry = diff.next();
                        if (entry.changeType() == DiffEntry.ChangeType.ADDED) {
                            added++;
                        } else if (entry.changeType() == DiffEntry.ChangeType.MODIFIED) {
                            modified++;
                        } else {
                            removed++;
                        }
                    }
                }

                return new CommitWithChangeCounts(input, added, modified, removed);
            }
        };

        final Iterator<CommitWithChangeCounts> summarizedLog = Iterators.transform(log, changeCountFunctor);
        context.setResponseContent(new CommandResponse() {
            @Override
            public void write(ResponseWriter out) throws Exception {
                out.start();
                out.writeCommitsWithChangeCounts(summarizedLog, elementsPerPage);
                out.finish();
            }
        });
    } else if (summary) {
        if (paths != null && paths.size() > 0) {
            context.setResponseContent(new StreamResponse() {

                @Override
                public void write(Writer out) throws Exception {
                    writeCSV(context.getGeoGIG(), out, log);
                }
            });
        } else {
            throw new CommandSpecException("You must specify a feature type path when getting a summary.");
        }
    } else {
        final boolean rangeLog = returnRange;
        context.setResponseContent(new CommandResponse() {
            @Override
            public void write(ResponseWriter out) throws Exception {
                out.start();
                out.writeCommits(log, elementsPerPage, rangeLog);
                out.finish();
            }
        });
    }

}