Example usage for com.google.common.collect ImmutableSet containsAll

List of usage examples for com.google.common.collect ImmutableSet containsAll

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet containsAll.

Prototype

boolean containsAll(Collection<?> c);

Source Link

Document

Returns true if this set contains all of the elements of the specified collection.

Usage

From source file:com.facebook.buck.cxx.CxxHeaders.java

/**
 * @return the arguments to add to the preprocessor command line to include the given header packs
 *     in preprocessor search path./*from  ww w .  j ava 2 s .  c  om*/
 */
public static Iterable<String> getArgs(Iterable<CxxHeaders> cxxHeaderses, SourcePathResolver resolver,
        Optional<PathShortener> pathMinimizer, Preprocessor preprocessor) {
    ImmutableList.Builder<String> args = ImmutableList.builder();

    // Collect the header maps and roots into buckets organized by include type, so that we can:
    // 1) Apply the header maps first (so that they work properly).
    // 2) De-duplicate redundant include paths.
    Multimap<CxxPreprocessables.IncludeType, String> headerMaps = LinkedHashMultimap.create();
    Multimap<CxxPreprocessables.IncludeType, String> roots = LinkedHashMultimap.create();
    for (CxxHeaders cxxHeaders : cxxHeaderses) {
        Optional<SourcePath> headerMap = cxxHeaders.getHeaderMap();
        if (headerMap.isPresent()) {
            headerMaps.put(cxxHeaders.getIncludeType(),
                    resolveSourcePathAndShorten(resolver, headerMap.get(), pathMinimizer).toString());
        }
        roots.put(cxxHeaders.getIncludeType(),
                resolveSourcePathAndShorten(resolver, cxxHeaders.getIncludeRoot(), pathMinimizer).toString());
    }

    // Define the include type ordering.  We always add local ("-I") include paths first so that
    // headers match there before system ("-isystem") ones.
    ImmutableSet<CxxPreprocessables.IncludeType> includeTypes = ImmutableSet
            .of(CxxPreprocessables.IncludeType.LOCAL, CxxPreprocessables.IncludeType.SYSTEM);

    // Apply the header maps first, so that headers that matching there avoid falling back to
    // stat'ing files in the normal include roots.
    Preconditions.checkState(includeTypes.containsAll(headerMaps.keySet()));
    for (CxxPreprocessables.IncludeType includeType : includeTypes) {
        args.addAll(includeType.includeArgs(preprocessor, headerMaps.get(includeType)));
    }

    // Apply the regular includes last.
    Preconditions.checkState(includeTypes.containsAll(roots.keySet()));
    for (CxxPreprocessables.IncludeType includeType : includeTypes) {
        args.addAll(includeType.includeArgs(preprocessor, roots.get(includeType)));
    }

    return args.build();
}

From source file:com.facebook.buck.core.rules.configsetting.ConfigSettingSelectable.java

private <T> boolean refines(ImmutableSet<T> values, ImmutableSet<T> otherValues) {
    return (values.size() > otherValues.size() && values.containsAll(otherValues));
}

From source file:com.jeffreybosboom.lyne.Puzzle.java

private Puzzle set(Node a, Node b, Set<Node.Kind> possibilities) {
    //private because rules actually want to call restrict instead
    Pair<Node, Node> p = Pair.sorted(a, b);
    ImmutableSet<Node.Kind> currentPossibilities = possibilities(a, b);
    if (possibilities.isEmpty() || !currentPossibilities.containsAll(possibilities))
        throw new ContradictionException();
    if (currentPossibilities.equals(possibilities))
        return this;

    return withEdgeSet(p, ImmutableSet.copyOf(possibilities));
}

From source file:com.facebook.presto.sql.planner.optimizations.StreamPreferredProperties.java

public StreamPreferredProperties constrainTo(Iterable<Symbol> symbols) {
    if (!partitioningColumns.isPresent()) {
        return this;
    }/*from  w ww. ja va 2s.  c om*/

    ImmutableSet<Symbol> availableSymbols = ImmutableSet.copyOf(symbols);
    if (exactColumnOrder) {
        if (availableSymbols.containsAll(partitioningColumns.get())) {
            return this;
        }
        return any();
    }

    Set<Symbol> common = Sets.intersection(availableSymbols, ImmutableSet.copyOf(partitioningColumns.get()));
    if (common.isEmpty()) {
        return any();
    }
    return new StreamPreferredProperties(distribution, Optional.of(common), false);
}

From source file:io.prestosql.sql.planner.optimizations.StreamPreferredProperties.java

public StreamPreferredProperties constrainTo(Iterable<Symbol> symbols) {
    if (!partitioningColumns.isPresent()) {
        return this;
    }//from   w w  w  .  jav  a 2 s . c  om

    ImmutableSet<Symbol> availableSymbols = ImmutableSet.copyOf(symbols);
    if (exactColumnOrder) {
        if (availableSymbols.containsAll(partitioningColumns.get())) {
            return this;
        }
        return any();
    }

    List<Symbol> common = partitioningColumns.get().stream().filter(availableSymbols::contains)
            .collect(toImmutableList());
    if (common.isEmpty()) {
        return any();
    }
    return new StreamPreferredProperties(distribution, Optional.of(common), false);
}

From source file:com.facebook.buck.versions.VersionedTargetGraph.java

@Nullable
@Override//from  w  w w .  j  a  v a 2s  .  co m
protected TargetNode<?, ?> getInternal(BuildTarget target) {

    // If this node is in the graph under the given name, return it.
    TargetNode<?, ?> node = targetsToNodes.get(target);
    if (node != null) {
        return node;
    }

    ImmutableList<ImmutableSet<Flavor>> flavorList = flavorMap.get(target.getUnflavoredBuildTarget());
    if (flavorList == null) {
        return null;
    }

    // Otherwise, see if this node exists in the graph with a "less" flavored name.  We initially
    // select all targets which contain a subset of the original flavors, which should be sorted by
    // from largest flavor set to smallest.  We then use the first match, and verify the subsequent
    // matches are subsets.
    ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList)
            .filter(target.getFlavors()::containsAll).toImmutableList();
    if (!matches.isEmpty()) {
        ImmutableSet<Flavor> firstMatch = matches.get(0);
        for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) {
            Preconditions.checkState(firstMatch.size() > subsequentMatch.size());
            Preconditions.checkState(firstMatch.containsAll(subsequentMatch),
                    "Found multiple disjoint flavor matches for %s: %s and %s",
                    target.getUnflavoredBuildTarget(), firstMatch, subsequentMatch);
        }
        return Preconditions.checkNotNull(targetsToNodes.get(target.withFlavors(firstMatch)))
                .withFlavors(target.getFlavors());
    }

    // Otherwise, return `null` to indicate this node isn't in the target graph.
    return null;
}

From source file:com.facebook.presto.tests.AbstractTestDistributedQueries.java

@Test
public void testShowSchemasFromOther() throws Exception {
    MaterializedResult result = computeActual("SHOW SCHEMAS FROM tpch");
    ImmutableSet<String> schemaNames = ImmutableSet
            .copyOf(transform(result.getMaterializedRows(), onlyColumnGetter()));
    assertTrue(schemaNames.containsAll(ImmutableSet.of(INFORMATION_SCHEMA, "tiny", "sf1")));
}

From source file:com.facebook.buck.versions.AbstractFlavorSearchTargetNodeFinder.java

public Optional<TargetNode<?>> get(BuildTarget target) {

    // If this node is in the graph under the given name, return it.
    TargetNode<?> node = getBuildTargetIndex().get(target);
    if (node != null) {
        return Optional.of(node);
    }/* w ww . j a  va2  s.c o m*/

    ImmutableSet<ImmutableSet<Flavor>> flavorList = getBaseTargetFlavorMap()
            .get(target.getUnflavoredBuildTarget());
    if (flavorList == null) {
        return Optional.empty();
    }

    // Otherwise, see if this node exists in the graph with a "less" flavored name.  We initially
    // select all targets which contain a subset of the original flavors, which should be sorted by
    // from largest flavor set to smallest.  We then use the first match, and verify the subsequent
    // matches are subsets.
    ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList)
            .filter(target.getFlavors()::containsAll).toImmutableList();
    if (!matches.isEmpty()) {
        ImmutableSet<Flavor> firstMatch = matches.get(0);
        for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) {
            Preconditions
                    .checkState(firstMatch.size() > subsequentMatch.size(),
                            "Expected to find larger flavor lists earlier in the flavor map "
                                    + "index (sizeof(%s) <= sizeof(%s))",
                            firstMatch.size(), subsequentMatch.size());
            Preconditions.checkState(firstMatch.containsAll(subsequentMatch),
                    "Found multiple disjoint flavor matches for %s: %s and %s (from %s)", target, firstMatch,
                    subsequentMatch, matches);
        }
        return Optional.of(Preconditions.checkNotNull(getBaseTargetIndex().get(target.withFlavors(firstMatch)),
                "%s missing in index", target.withFlavors(firstMatch)));
    }

    // Otherwise, return `null` to indicate this node isn't in the target graph.
    return Optional.empty();
}

From source file:org.glowroot.central.repo.GaugeValueDaoImpl.java

public void store(String agentId, List<String> agentRollupIdsForMeta, List<GaugeValue> gaugeValues)
        throws Exception {
    if (gaugeValues.isEmpty()) {
        return;//ww  w.j a  v a 2  s. c  om
    }
    int ttl = getTTLs().get(0);
    long maxCaptureTime = 0;
    List<Future<?>> futures = new ArrayList<>();
    for (GaugeValue gaugeValue : gaugeValues) {
        BoundStatement boundStatement = insertValuePS.get(0).bind();
        String gaugeName = gaugeValue.getGaugeName();
        long captureTime = gaugeValue.getCaptureTime();
        maxCaptureTime = Math.max(captureTime, maxCaptureTime);
        int adjustedTTL = Common.getAdjustedTTL(ttl, captureTime, clock);
        int i = 0;
        boundStatement.setString(i++, agentId);
        boundStatement.setString(i++, gaugeName);
        boundStatement.setTimestamp(i++, new Date(captureTime));
        boundStatement.setDouble(i++, gaugeValue.getValue());
        boundStatement.setLong(i++, gaugeValue.getWeight());
        boundStatement.setInt(i++, adjustedTTL);
        futures.add(session.writeAsync(boundStatement));
        for (String agentRollupIdForMeta : agentRollupIdsForMeta) {
            futures.addAll(gaugeNameDao.insert(agentRollupIdForMeta, captureTime, gaugeName));
        }
    }

    // wait for success before inserting "needs rollup" records
    MoreFutures.waitForAll(futures);
    futures.clear();

    // insert into gauge_needs_rollup_1
    Map<NeedsRollupKey, ImmutableSet<String>> updatesForNeedsRollupCache1 = new HashMap<>();
    SetMultimap<Long, String> rollupCaptureTimes = getRollupCaptureTimes(gaugeValues);
    for (Map.Entry<Long, Set<String>> entry : Multimaps.asMap(rollupCaptureTimes).entrySet()) {
        Long captureTime = entry.getKey();
        Set<String> gaugeNames = entry.getValue();
        NeedsRollupKey needsRollupKey = ImmutableNeedsRollupKey.of(agentId, captureTime);
        ImmutableSet<String> needsRollupGaugeNames = needsRollupCache1.get(needsRollupKey);
        if (needsRollupGaugeNames == null) {
            // first insert for this key
            updatesForNeedsRollupCache1.put(needsRollupKey, ImmutableSet.copyOf(gaugeNames));
        } else if (needsRollupGaugeNames.containsAll(gaugeNames)) {
            // capture current time after getting data from cache to prevent race condition with
            // reading the data in Common.getNeedsRollupList()
            if (!Common.isOldEnoughToRollup(captureTime, clock.currentTimeMillis(),
                    configRepository.getRollupConfigs().get(0).intervalMillis())) {
                // completely covered by prior inserts that haven't been rolled up yet so no
                // need to re-insert same data
                continue;
            }
        } else {
            // merge will maybe help prevent a few subsequent inserts
            Set<String> combined = new HashSet<>(needsRollupGaugeNames);
            combined.addAll(gaugeNames);
            updatesForNeedsRollupCache1.put(needsRollupKey, ImmutableSet.copyOf(gaugeNames));
        }
        BoundStatement boundStatement = insertNeedsRollup.get(0).bind();
        int adjustedTTL = Common.getAdjustedTTL(ttl, captureTime, clock);
        int needsRollupAdjustedTTL = Common.getNeedsRollupAdjustedTTL(adjustedTTL,
                configRepository.getRollupConfigs());
        int i = 0;
        boundStatement.setString(i++, agentId);
        boundStatement.setTimestamp(i++, new Date(captureTime));
        boundStatement.setUUID(i++, UUIDs.timeBased());
        boundStatement.setSet(i++, gaugeNames);
        boundStatement.setInt(i++, needsRollupAdjustedTTL);
        futures.add(session.writeAsync(boundStatement));
    }
    MoreFutures.waitForAll(futures);

    // update the cache now that the above inserts were successful
    needsRollupCache1.putAll(updatesForNeedsRollupCache1);
}

From source file:google.registry.request.auth.OAuthAuthenticationMechanism.java

@Override
public AuthResult authenticate(HttpServletRequest request) {

    // Make sure that there is an Authorization header in Bearer form. OAuthService also accepts
    // tokens in the request body and URL string, but we should not use those, since they are more
    // likely to be logged than the Authorization header. Checking to make sure there's a token also
    // avoids unnecessary RPCs, since OAuthService itself does not check whether the header is
    // present. In theory, there could be more than one Authorization header, but we only check the
    // first one, because there's not a legitimate use case for having more than one, and
    // OAuthService itself only looks at the first one anyway.
    String header = request.getHeader(AUTHORIZATION);
    if ((header == null) || !header.startsWith(BEARER_PREFIX)) {
        return AuthResult.create(NONE);
    }//  w ww  . ja v  a  2  s.  c o m
    // Assume that, if a bearer token is found, it's what OAuthService will use to attempt
    // authentication. This is not technically guaranteed by the contract of OAuthService; see
    // OAuthTokenInfo for more information.
    String rawAccessToken = header.substring(BEARER_PREFIX.length());

    // Get the OAuth information. The various oauthService method calls use a single cached
    // authentication result, we can call them one by one. Unfortunately, the calls have a
    // single-scope form, and a varargs scope list form, but no way to call them with a collection
    // of scopes, so it will not be easy to configure multiple scopes.
    User currentUser;
    boolean isUserAdmin;
    String clientId;
    ImmutableSet<String> authorizedScopes;
    try {
        currentUser = oauthService.getCurrentUser(availableOauthScopes.toArray(new String[0]));
        isUserAdmin = oauthService.isUserAdmin(availableOauthScopes.toArray(new String[0]));
        clientId = oauthService.getClientId(availableOauthScopes.toArray(new String[0]));
        authorizedScopes = ImmutableSet
                .copyOf(oauthService.getAuthorizedScopes(availableOauthScopes.toArray(new String[0])));
    } catch (OAuthRequestException | OAuthServiceFailureException e) {
        return AuthResult.create(NONE);
    }
    if ((currentUser == null) || (clientId == null) || (authorizedScopes == null)) {
        return AuthResult.create(NONE);
    }

    // Make sure that the client ID matches, to avoid a confused deputy attack; see:
    // http://stackoverflow.com/a/17439317/1179226
    if (!allowedOauthClientIds.contains(clientId)) {
        return AuthResult.create(NONE);
    }

    // Make sure that all required scopes are present.
    if (!authorizedScopes.containsAll(requiredOauthScopes)) {
        return AuthResult.create(NONE);
    }

    // Create the {@link AuthResult}, including the OAuth token info.
    return AuthResult.create(USER, UserAuthInfo.create(currentUser, isUserAdmin,
            OAuthTokenInfo.create(ImmutableSet.copyOf(authorizedScopes), clientId, rawAccessToken)));
}