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

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

Introduction

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

Prototype

public static <T> Iterator<T> limit(final Iterator<T> iterator, final int limitSize) 

Source Link

Document

Creates an iterator returning the first limitSize elements of the given iterator.

Usage

From source file:org.locationtech.geogig.porcelain.LogOp.java

/**
 * Executes the log operation./* w w w. j  a  v  a2  s .  c o  m*/
 * 
 * @return the list of commits that satisfy the query criteria, most recent first.
 * @see org.locationtech.geogig.repository.AbstractGeoGigOp#call()
 */
@Override
protected Iterator<RevCommit> _call() {

    ObjectId newestCommitId;
    ObjectId oldestCommitId;
    {
        if (this.until == null) {
            newestCommitId = command(RevParse.class).setRefSpec(Ref.HEAD).call().get();
        } else {
            if (!repository().commitExists(this.until)) {
                throw new IllegalArgumentException(
                        "Provided 'until' commit id does not exist: " + until.toString());
            }
            newestCommitId = this.until;
        }
        if (this.since == null) {
            oldestCommitId = ObjectId.NULL;
        } else {
            if (!repository().commitExists(this.since)) {
                throw new IllegalArgumentException(
                        "Provided 'since' commit id does not exist: " + since.toString());
            }
            oldestCommitId = this.since;
        }
    }

    Iterator<RevCommit> history;
    if (firstParent) {
        history = new LinearHistoryIterator(newestCommitId, repository());
    } else {
        if (commits.isEmpty()) {
            commits.add(newestCommitId);
        }
        if (topo) {
            history = new TopologicalHistoryIterator(commits, repository(), graphDatabase());
        } else {
            history = new ChronologicalHistoryIterator(commits, repository());
        }
    }
    LogFilter filter = new LogFilter(oldestCommitId, timeRange, paths, author, commiter);
    Iterator<RevCommit> filteredCommits = Iterators.filter(history, filter);
    if (skip != null) {
        Iterators.advance(filteredCommits, skip.intValue());
    }
    if (limit != null) {
        filteredCommits = Iterators.limit(filteredCommits, limit.intValue());
    }
    return filteredCommits;
}

From source file:com.github.jonross.seq4j.Seq.java

/**
 * Wraps {@link Iterators#limit(Iterator, int)}; limits the number of items
 * that are available from this iterator.
 * //from w  ww  .j a  v  a 2s .  co  m
 * @param count The number of elements after which <code>hasNext</code> will return false.
 * @return A new <code>Seq</code> for which the limit applies.
 */

public Seq<T> take(int count) {
    return seq(Iterators.limit(this, count));
}

From source file:org.geotools.data.geogit.GeoGitSimpleFeatureCollection.java

/**
 * @see org.geotools.feature.FeatureCollection#iterator()
 *//*  ww w  .j a  v a 2 s.  c o m*/
@Override
public Iterator<SimpleFeature> iterator() {
    final FeatureRefIterator refs = new FeatureRefIterator(typeTree, filter);
    Iterator<SimpleFeature> features = new GeoGitFeatureIterator(refs, type, filter, odb);
    if (maxFeatures != null) {
        features = Iterators.limit(features, maxFeatures.intValue());
    }
    return features;
}

From source file:org.sakaiproject.nakamura.site.SiteServiceImpl.java

/**
 * Sets a list at the correct starting point, limits the result and does sorting (if
 * required)./*ww w .  ja v a 2  s  .  co m*/
 * 
 * @param memberList
 *          The list that needs to be manipulated.
 * @param start
 *          The starting point
 * @param nitems
 *          The number of items that should be in the collection.
 * @param sort
 *          The requested sorting, can be null.
 * @return
 */
protected AbstractCollection<AuthorizableKey> returnCollection(final List<AuthorizableKey> memberList,
        final int start, final int nitems, Sort[] sort) {
    Iterator<AuthorizableKey> listIterator = null;
    // Check if we need to sort the list.
    if (sort != null && sort.length > 0) {
        Comparator<AuthorizableKey> comparitor = buildCompoundComparitor(sort);
        Collections.sort(memberList, comparitor);
        listIterator = memberList.listIterator(start);
    }

    // Start at the requested point in the list.
    listIterator = memberList.listIterator(start);

    // -1 means that we should fetch them all.
    if (nitems > 0) {
        listIterator = Iterators.limit(listIterator, nitems);
    }

    final Iterator<AuthorizableKey> iterator = listIterator;
    return new AbstractCollection<AuthorizableKey>() {

        @Override
        public Iterator<AuthorizableKey> iterator() {
            return iterator;
        }

        @Override
        public int size() {
            return memberList.size();
        }
    };
}

From source file:org.geoserver.jdbcconfig.internal.ConfigDatabase.java

public <T extends Info> CloseableIterator<T> query(final Class<T> of, final Filter filter,
        @Nullable Integer offset, @Nullable Integer limit, @Nullable SortBy... sortOrder) {

    checkNotNull(of);/* w  ww  . ja va2 s .  c o  m*/
    checkNotNull(filter);
    checkArgument(offset == null || offset.intValue() >= 0);
    checkArgument(limit == null || limit.intValue() >= 0);

    QueryBuilder<T> sqlBuilder = QueryBuilder.forIds(of, dbMappings).filter(filter).offset(offset).limit(limit)
            .sortOrder(sortOrder);

    final StringBuilder sql = sqlBuilder.build();
    final Map<String, Object> namedParameters = sqlBuilder.getNamedParameters();
    final Filter unsupportedFilter = sqlBuilder.getUnsupportedFilter();
    final boolean fullySupported = Filter.INCLUDE.equals(unsupportedFilter);

    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.finer("Original filter: " + filter);
        LOGGER.finer("Supported filter: " + sqlBuilder.getSupportedFilter());
        LOGGER.finer("Unsupported filter: " + sqlBuilder.getUnsupportedFilter());
    }
    logStatement(sql, namedParameters);

    Stopwatch sw = new Stopwatch().start();
    List<String> ids = template.queryForList(sql.toString(), namedParameters, String.class);
    sw.stop();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(Joiner.on("").join("query returned ", ids.size(), " records in ", sw.toString()));
    }

    List<T> lazyTransformed = Lists.transform(ids, new Function<String, T>() {
        @Override
        public T apply(String id) {
            return getById(id, of);
        }
    });

    CloseableIterator<T> result;

    if (fullySupported) {
        Iterator<T> iterator = lazyTransformed.iterator();
        result = new CloseableIteratorAdapter<T>(iterator);
    } else {
        Iterator<T> iterator = lazyTransformed.iterator();
        if (offset != null) {
            Iterators.skip(iterator, offset.intValue());
        }
        if (limit != null) {
            iterator = Iterators.limit(iterator, limit.intValue());
        }
        result = CloseableIteratorAdapter.filter(iterator, filter);
    }

    return result;
}

From source file:com.thinkbiganalytics.metadata.core.feed.InMemoryFeedProvider.java

@Override
public List<Feed> getFeeds(FeedCriteria criteria) {
    Criteria critImpl = (Criteria) criteria;
    Iterator<Feed> filtered = Iterators.filter(this.feeds.values().iterator(), critImpl);
    Iterator<Feed> limited = Iterators.limit(filtered, critImpl.getLimit());

    return ImmutableList.copyOf(limited);
}

From source file:org.locationtech.geogig.geotools.data.GeogigFeatureReader.java

private Iterator<SimpleFeature> applyFeaturesOffsetLimit(Iterator<SimpleFeature> features) {
    if (offset != null) {
        Iterators.advance(features, offset.intValue());
    }//  w  ww  .  java 2 s  .c  o m
    if (maxFeatures != null) {
        features = Iterators.limit(features, maxFeatures.intValue());
    }
    return features;
}

From source file:com.palantir.atlasdb.keyvalue.remoting.RemotingKeyValueService.java

private static <T> RangeIterator<T> transformIterator(String tableName, RangeRequest range, long timestamp,
        ClosableIterator<RowResult<T>> closableIterator,
        Function<Pair<Boolean, ImmutableList<RowResult<T>>>, RangeIterator<T>> resultSupplier) {
    try {/*  ww w . j  a v  a2s  . c  o  m*/
        int pageSize = range.getBatchHint() != null ? range.getBatchHint() : 100;
        if (pageSize == 1) {
            pageSize = 2;
        }
        ImmutableList<RowResult<T>> page = ImmutableList.copyOf(Iterators.limit(closableIterator, pageSize));
        if (page.size() < pageSize) {
            return resultSupplier.apply(Pair.create(false, page));
        } else {
            return resultSupplier.apply(Pair.create(true, page.subList(0, pageSize - 1)));
        }
    } finally {
        closableIterator.close();
    }
}

From source file:org.locationtech.geogig.geotools.data.GeogigFeatureReader.java

private Iterator<NodeRef> applyRefsOffsetLimit(Iterator<NodeRef> featureRefs) {
    if (offset != null) {
        Iterators.advance(featureRefs, offset.intValue());
    }/*from w ww .  j a v  a 2s . c  o  m*/
    if (maxFeatures != null) {
        featureRefs = Iterators.limit(featureRefs, maxFeatures.intValue());
    }
    return featureRefs;
}

From source file:com.google.cloud.genomics.localrepo.QueryEngine.java

private SearchReadsResponse searchReads(Map<File, PeekingIterator<SAMRecordWithSkip>> iterators, final int end,
        Predicate<String> readsetFilter) {
    List<Read> reads = new ArrayList<>();
    for (Iterator<SAMRecordWithSkip> iterator = Iterators
            .limit(Iterators.mergeSorted(iterators.values(), Comparator.naturalOrder()), pageSize); iterator
                    .hasNext();) {/* w  ww  .ja  va2  s.c  o m*/
        SAMRecordWithSkip next = iterator.next();
        String readsetId = getReadsetId(next.file, next.record);
        if (readsetFilter.test(readsetId)) {
            reads.add(read(readsetId, next.record));
        }
    }
    Map<File, PeekingIterator<SAMRecordWithSkip>> nonEmptyIterators = Maps.filterValues(iterators,
            iterator -> iterator.hasNext());
    return SearchReadsResponse.create(reads,
            nonEmptyIterators.isEmpty() ? null
                    : QueryDescriptor.create(new HashMap<>(Maps.transformValues(nonEmptyIterators,
                            new Function<PeekingIterator<SAMRecordWithSkip>, QueryDescriptor.Start>() {
                                @Override
                                public QueryDescriptor.Start apply(
                                        PeekingIterator<SAMRecordWithSkip> iterator) {
                                    SAMRecordWithSkip peek = iterator.peek();
                                    SAMRecord record = peek.record;
                                    return QueryDescriptor.Start.create(record.getReferenceName(),
                                            record.getAlignmentStart(), peek.skip);
                                }
                            })), end).toString());
}