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

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

Introduction

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

Prototype

public static <T> Iterable<T> limit(final Iterable<T> iterable, final int limitSize) 

Source Link

Document

Creates an iterable with the first limitSize elements of the given iterable.

Usage

From source file:com.github.benmanes.caffeine.cache.LocalCacheFactoryGenerator.java

private void addLocalCacheSpec(String className, boolean isFinal, Set<Feature> features) {
    TypeName superClass;//  w ww. j  a va  2s.co m
    Set<Feature> parentFeatures;
    Set<Feature> generateFeatures;
    if (features.size() == 2) {
        parentFeatures = ImmutableSet.of();
        generateFeatures = features;
        superClass = BOUNDED_LOCAL_CACHE;
    } else {
        parentFeatures = ImmutableSet.copyOf(Iterables.limit(features, features.size() - 1));
        generateFeatures = ImmutableSet.of(Iterables.getLast(features));
        superClass = ParameterizedTypeName
                .get(ClassName.bestGuess(encode(Feature.makeClassName(parentFeatures))), kTypeVar, vTypeVar);
    }

    LocalCacheContext context = new LocalCacheContext(superClass, className, isFinal, parentFeatures,
            generateFeatures);
    for (LocalCacheRule rule : rules) {
        rule.accept(context);
    }
    factory.addType(context.cache.build());
}

From source file:uk.gov.gchq.gaffer.store.schema.ViewValidator.java

protected boolean validateGroupBy(final boolean isStoreOrdered, final String group,
        final ViewElementDefinition viewElDef, final SchemaElementDefinition schemaElDef) {
    final Set<String> viewGroupBy = viewElDef.getGroupBy();

    boolean isValid = true;
    if (null != viewGroupBy && !viewGroupBy.isEmpty()) {
        final Set<String> schemaGroupBy = schemaElDef.getGroupBy();
        if (null != schemaGroupBy && schemaGroupBy.containsAll(viewGroupBy)) {
            if (isStoreOrdered) {
                final LinkedHashSet<String> schemaGroupBySubset = Sets
                        .newLinkedHashSet(Iterables.limit(schemaGroupBy, viewGroupBy.size()));
                if (!viewGroupBy.equals(schemaGroupBySubset)) {
                    LOGGER.error("Group by properties for group " + group
                            + " are not in the same order as the group by properties in the schema. View groupBy:"
                            + viewGroupBy + ". Schema groupBy:" + schemaGroupBy);
                    isValid = false;//from   w w  w.  j  a  v a2 s.  c o  m
                }
            }
        } else {
            LOGGER.error("Group by properties for group " + group
                    + " in the view are not all included in the group by field in the schema. View groupBy:"
                    + viewGroupBy + ". Schema groupBy:" + schemaGroupBy);
            isValid = false;
        }
    }

    return isValid;
}

From source file:org.glowroot.local.ui.ClasspathCache.java

private ImmutableList<String> combineClassNamesWithLimit(Set<String> fullMatchingClassNames,
        Set<String> matchingClassNames, int limit) {
    if (fullMatchingClassNames.size() < limit) {
        int space = limit - fullMatchingClassNames.size();
        int numToAdd = Math.min(space, matchingClassNames.size());
        fullMatchingClassNames.addAll(ImmutableList.copyOf(Iterables.limit(matchingClassNames, numToAdd)));
    }//www.j a  va2s  . c o  m
    return ImmutableList.copyOf(fullMatchingClassNames);
}

From source file:org.apache.mahout.math.neighborhood.ProjectionSearch.java

/**
 * Returns the closest vector to the query.
 * When only one the nearest vector is needed, use this method, NOT search(query, limit) because
 * it's faster (less overhead)./*  w  ww . j a  v a  2s  .c o  m*/
 *
 * @param query the vector to search for
 * @param differentThanQuery if true, returns the closest vector different than the query (this
 *                           only matters if the query is among the searched vectors), otherwise,
 *                           returns the closest vector to the query (even the same vector).
 * @return the weighted vector closest to the query
 */
@Override
public WeightedThing<Vector> searchFirst(Vector query, boolean differentThanQuery) {
    double bestDistance = Double.POSITIVE_INFINITY;
    Vector bestVector = null;

    Iterator<? extends Vector> projections = basisMatrix.iterator();
    for (TreeMultiset<WeightedThing<Vector>> v : scalarProjections) {
        Vector basisVector = projections.next();
        WeightedThing<Vector> projectedQuery = new WeightedThing<Vector>(query, query.dot(basisVector));
        for (WeightedThing<Vector> candidate : Iterables.concat(
                Iterables.limit(v.tailMultiset(projectedQuery, BoundType.CLOSED), searchSize), Iterables.limit(
                        v.headMultiset(projectedQuery, BoundType.OPEN).descendingMultiset(), searchSize))) {
            double distance = distanceMeasure.distance(query, candidate.getValue());
            if (distance < bestDistance && (!differentThanQuery || !candidate.getValue().equals(query))) {
                bestDistance = distance;
                bestVector = candidate.getValue();
            }
        }
    }

    return new WeightedThing<Vector>(bestVector, bestDistance);
}

From source file:org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier.java

/**
 * Return an instance identifier trimmed at the first occurrence of a
 * specific component type./*from   ww  w.j  a v  a 2s.  c  o m*/
 *
 * For example let's say an instance identifier was built like so,
 * <pre>
 *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
 * </pre>
 *
 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
 *
 * <pre>
 *      identifier.firstIdentifierOf(Nodes.class)
 * </pre>
 *
 * @param type component type
 * @return trimmed instance identifier, or null if the component type
 *         is not present.
 */
public final <I extends TreeNode> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
    int i = 1;
    for (final TreeArgument a : pathArguments) {
        if (type.equals(a.getType())) {
            @SuppressWarnings("unchecked")
            final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(
                    Iterables.limit(pathArguments, i));
            return ret;
        }

        ++i;
    }

    return null;
}

From source file:org.opendaylight.yangtools.yang.binding.InstanceIdentifier.java

/**
 * Return an instance identifier trimmed at the first occurrence of a
 * specific component type.// ww  w  . jav a 2  s  .com
 *
 * For example let's say an instance identifier was built like so,
 * <pre>
 *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
 * </pre>
 *
 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
 *
 * <pre>
 *      identifier.firstIdentifierOf(Nodes.class)
 * </pre>
 *
 * @param type component type
 * @return trimmed instance identifier, or null if the component type
 *         is not present.
 */
public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
    int i = 1;
    for (final PathArgument a : pathArguments) {
        if (type.equals(a.getType())) {
            @SuppressWarnings("unchecked")
            final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(
                    Iterables.limit(pathArguments, i));
            return ret;
        }

        ++i;
    }

    return null;
}

From source file:com.slimgears.slimprefs.apt.ClassBindingGenerator.java

@Override
protected void build(TypeSpec.Builder builder, TypeElement type, TypeElement... interfaces) {
    builder.addField(FieldSpec//from   w  w  w .  j  a v a2  s  .  c o  m
            .builder(ParameterizedTypeName.get(ClassName.get(ClassBinding.class), targetTypeName), "INSTANCE")
            .addModifiers(Modifier.STATIC, Modifier.PUBLIC, Modifier.FINAL)
            .initializer("new $T()", getTypeName()).build());
    builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build());
    MethodSpec.Builder bindMethodBuilder = MethodSpec.methodBuilder("bind").returns(PreferenceBinding.class)
            .addParameter(PreferenceProvider.class, "provider")
            .addParameter(targetTypeName, "target", Modifier.FINAL).addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC).addCode("return $T.create(\n", CompositePreferenceBinding.class);

    for (BindingDescriptor binding : Iterables.limit(bindings, bindings.size() - 1)) {
        bindMethodBuilder.addCode(binding.build()).addCode(",\n");
    }

    for (BindingDescriptor binding : Iterables.skip(bindings, bindings.size() - 1)) {
        bindMethodBuilder.addCode(binding.build());
    }

    bindMethodBuilder.addCode(");\n");
    builder.addMethod(bindMethodBuilder.build());
}

From source file:com.github.jsdossier.JsDoc.java

private void parse() {
    if (parsed) {
        return;//from   w ww .  j a v  a2s  .  c o m
    }
    parsed = true;

    String original = Strings.nullToEmpty(info.getOriginalCommentString());
    if (original.isEmpty()) {
        return;
    }
    if (info.getStaticSourceFile() != null && info.getOriginalCommentPosition() > 0) {
        int offset = info.getOriginalCommentPosition();
        int column = info.getStaticSourceFile().getColumnOfOffset(offset);
        if (column > 0) {
            original = Strings.repeat(" ", column) + original;
        }
    }
    original = original.substring(0, original.length() - 2); // subtract closing */

    Iterable<String> lines = Splitter.on(EOL_PATTERN).split(original);
    int firstAnnotation = findFirstAnnotationLine(lines);
    int annotationOffset = 0;
    if (firstAnnotation != -1 && !info.getMarkers().isEmpty()) {
        blockComment = processBlockCommentLines(Iterables.limit(lines, firstAnnotation));

        JSDocInfo.StringPosition firstAnnotationPosition = info.getMarkers().iterator().next().getAnnotation();

        annotationOffset = firstAnnotationPosition.getStartLine() - firstAnnotation;
    } else {
        blockComment = processBlockCommentLines(lines);
    }

    // If we failed to extract a block comment, yet the original JSDoc has one, we've
    // probably encountered a case where the compiler merged multiple JSDoc comments
    // into one. Try to recover by parsing the compiler's provided block comment.
    if (isNullOrEmpty(blockComment) && !isNullOrEmpty(info.getBlockDescription())) {
        blockComment = processBlockCommentLines(Splitter.on('\n').split(info.getBlockDescription()));
    }

    for (JSDocInfo.Marker marker : info.getMarkers()) {
        Optional<Annotation> annotation = Annotation.forMarker(marker);
        if (!annotation.isPresent()) {
            continue; // Unrecognized/unsupported annotation.
        }

        JSDocInfo.StringPosition description = marker.getDescription();
        if (description == null) {
            continue;
        }

        int startLine = description.getStartLine() - annotationOffset;
        Iterable<String> descriptionLines = Iterables.skip(lines, startLine);

        int numLines = Math.max(description.getEndLine() - description.getStartLine(), 1);
        descriptionLines = Iterables.limit(descriptionLines, numLines);

        switch (annotation.get()) {
        case DEFINE:
            defineComment = processDescriptionLines(descriptionLines, description);
            break;
        case DEPRECATED:
            deprecationReason = processDescriptionLines(descriptionLines, description);
            break;
        case FILEOVERVIEW:
            fileoverview = processDescriptionLines(descriptionLines, description);
            break;
        case PARAM:
            String name = marker.getNameNode().getItem().getString();
            parameters.put(name, new Parameter(name, getJsTypeExpression(marker),
                    processDescriptionLines(descriptionLines, description)));
            break;
        case RETURN:
            returnDescription = processDescriptionLines(descriptionLines, description);
            break;
        case SEE:
            seeClauses.add(processDescriptionLines(descriptionLines, description));
            break;
        case THROWS:
            throwsClauses.add(new ThrowsClause(getJsTypeExpression(marker),
                    processDescriptionLines(descriptionLines, description)));
            break;
        }
    }

    if (isNullOrEmpty(blockComment)) {
        if (!isNullOrEmpty(fileoverview)) {
            blockComment = fileoverview;
        } else if (!isNullOrEmpty(defineComment)) {
            blockComment = defineComment;
        }
    }
}

From source file:io.prestosql.tests.QueryAssertions.java

public static void assertEqualsIgnoreOrder(Iterable<?> actual, Iterable<?> expected, String message) {
    assertNotNull(actual, "actual is null");
    assertNotNull(expected, "expected is null");

    ImmutableMultiset<?> actualSet = ImmutableMultiset.copyOf(actual);
    ImmutableMultiset<?> expectedSet = ImmutableMultiset.copyOf(expected);
    if (!actualSet.equals(expectedSet)) {
        Multiset<?> unexpectedRows = Multisets.difference(actualSet, expectedSet);
        Multiset<?> missingRows = Multisets.difference(expectedSet, actualSet);
        int limit = 100;
        fail(format(/*w ww .j  ava 2  s .  c o m*/
                "%snot equal\n" + "Actual rows (up to %s of %s extra rows shown, %s rows in total):\n    %s\n"
                        + "Expected rows (up to %s of %s missing rows shown, %s rows in total):\n    %s\n",
                message == null ? "" : (message + "\n"), limit, unexpectedRows.size(), actualSet.size(),
                Joiner.on("\n    ").join(Iterables.limit(unexpectedRows, limit)), limit, missingRows.size(),
                expectedSet.size(), Joiner.on("\n    ").join(Iterables.limit(missingRows, limit))));
    }
}

From source file:org.jclouds.blobstore.LocalAsyncBlobStore.java

/**
 * default maxResults is 1000//from w w w  .  j a  va2s .c  o  m
 */
@Override
public ListenableFuture<PageSet<? extends StorageMetadata>> list(final String container,
        ListContainerOptions options) {

    // Check if the container exists
    if (!storageStrategy.containerExists(container))
        return immediateFailedFuture(cnfe(container));

    // Loading blobs from container
    Iterable<String> blobBelongingToContainer = null;
    try {
        blobBelongingToContainer = storageStrategy.getBlobKeysInsideContainer(container);
    } catch (IOException e) {
        logger.error(e, "An error occurred loading blobs contained into container %s", container);
        Throwables.propagate(e);
    }

    SortedSet<StorageMetadata> contents = newTreeSet(
            transform(blobBelongingToContainer, new Function<String, StorageMetadata>() {
                public StorageMetadata apply(String key) {
                    Blob oldBlob = loadBlob(container, key);
                    checkState(oldBlob != null,
                            "blob " + key + " is not present although it was in the list of " + container);
                    checkState(oldBlob.getMetadata() != null,
                            "blob " + container + "/" + key + " has no metadata");
                    MutableBlobMetadata md = BlobStoreUtils.copy(oldBlob.getMetadata());
                    String directoryName = ifDirectoryReturnName.execute(md);
                    if (directoryName != null) {
                        md.setName(directoryName);
                        md.setType(StorageType.RELATIVE_PATH);
                    }
                    return md;
                }
            }));

    String marker = null;
    if (options != null) {
        if (options.getMarker() != null) {
            final String finalMarker = options.getMarker();
            StorageMetadata lastMarkerMetadata = find(contents, new Predicate<StorageMetadata>() {
                public boolean apply(StorageMetadata metadata) {
                    return metadata.getName().compareTo(finalMarker) > 0;
                }
            });
            contents = contents.tailSet(lastMarkerMetadata);
        }

        final String prefix = options.getDir();
        if (prefix != null) {
            contents = newTreeSet(filter(contents, new Predicate<StorageMetadata>() {
                public boolean apply(StorageMetadata o) {
                    return o != null && o.getName().startsWith(prefix) && !o.getName().equals(prefix);
                }
            }));
        }

        int maxResults = options.getMaxResults() != null ? options.getMaxResults() : 1000;
        if (!contents.isEmpty()) {
            StorageMetadata lastElement = contents.last();
            contents = newTreeSet(Iterables.limit(contents, maxResults));
            if (!contents.contains(lastElement)) {
                // Partial listing
                marker = contents.last().getName();
            }
        }

        if (!options.isRecursive()) {
            String delimiter = storageStrategy.getSeparator();
            SortedSet<String> commonPrefixes = newTreeSet(
                    transform(contents, new CommonPrefixes(prefix, delimiter)));
            commonPrefixes.remove(CommonPrefixes.NO_PREFIX);

            contents = newTreeSet(filter(contents, new DelimiterFilter(prefix, delimiter)));

            for (String o : commonPrefixes) {
                MutableStorageMetadata md = new MutableStorageMetadataImpl();
                md.setType(StorageType.RELATIVE_PATH);
                md.setName(o);
                contents.add(md);
            }
        }

        // trim metadata, if the response isn't supposed to be detailed.
        if (!options.isDetailed()) {
            for (StorageMetadata md : contents) {
                md.getUserMetadata().clear();
            }
        }
    }

    return Futures.<PageSet<? extends StorageMetadata>>immediateFuture(
            new PageSetImpl<StorageMetadata>(contents, marker));

}