Example usage for com.google.common.collect Sets intersection

List of usage examples for com.google.common.collect Sets intersection

Introduction

In this page you can find the example usage for com.google.common.collect Sets intersection.

Prototype

public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) 

Source Link

Document

Returns an unmodifiable view of the intersection of two sets.

Usage

From source file:org.caleydo.view.domino.api.model.typed.TypedSet.java

public static TypedSet intersection(BitSetSet a, TypedSet b) {
    if (b.wrappee instanceof BitSetSet) {
        return new TypedSet(BitSetSet.and(a, ((BitSetSet) b.wrappee)), b.idType);
    }// ww w .  ja va  2  s  . c o  m
    return new TypedSet(ImmutableSet.copyOf(Sets.intersection(b, a)), b.idType); // as the predicate is: in the
    // second argument
}

From source file:org.kiji.schema.security.KijiPermissions.java

/**
 * Returns an array of all HBase Actions specified by this KijiPermissions object. This is used
 * internally to apply the correct permissions on HBase tables.
 *
 * @return HBase Actions for all of the permitted Actions with corresponding HBase Actions.
 *//*from www .  jav a2  s .  c  o  m*/
protected Permission.Action[] toHBaseActions() {
    final Set<Action> mHBaseActions = Sets.intersection(mActions, HBASE_ACTIONS);
    final Set<Permission.Action> convertedActions = EnumSet.noneOf(Permission.Action.class);
    for (Action kijiAction : mHBaseActions) {
        convertedActions.add(kijiAction.getHBaseAction());
    }
    return convertedActions.toArray(new Permission.Action[convertedActions.size()]);
}

From source file:com.moz.fiji.schema.security.FijiPermissions.java

/**
 * Returns an array of all HBase Actions specified by this FijiPermissions object. This is used
 * internally to apply the correct permissions on HBase tables.
 *
 * @return HBase Actions for all of the permitted Actions with corresponding HBase Actions.
 *//*from w  ww.  j  a v  a2s  . c  om*/
protected Permission.Action[] toHBaseActions() {
    final Set<Action> mHBaseActions = Sets.intersection(mActions, HBASE_ACTIONS);
    final Set<Permission.Action> convertedActions = EnumSet.noneOf(Permission.Action.class);
    for (Action fijiAction : mHBaseActions) {
        convertedActions.add(fijiAction.getHBaseAction());
    }
    return convertedActions.toArray(new Permission.Action[convertedActions.size()]);
}

From source file:com.facebook.buck.android.ResourceFilters.java

/**
 * Takes a list of image files (as paths), and a target density (mdpi, hdpi, xhdpi), and
 * returns a list of files which can be safely left out when building an APK for phones with that
 * screen density. That APK will run on other screens as well but look worse due to scaling.
 * <p>//from w w w. jav  a2s  . c  o m
 * Each combination of non-density qualifiers is processed separately. For example, if we have
 * {@code drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-hdpi-ro}, for a target of {@code
 * mdpi}, we'll be keeping {@code drawable-mdpi, drawable-hdpi-ro}.
 * @param candidates list of paths to image files
 * @param targetDensities densities we want to keep
 * @param canDownscale do we have access to an image scaler
 * @return set of files to remove
 */
@VisibleForTesting
static Set<Path> filterByDensity(Collection<Path> candidates, Set<ResourceFilters.Density> targetDensities,
        boolean canDownscale) {
    ImmutableSet.Builder<Path> removals = ImmutableSet.builder();

    Table<String, Density, Path> imageValues = HashBasedTable.create();

    // Create mappings for drawables. If candidate == "<base>/drawable-<dpi>-<other>/<filename>",
    // then we'll record a mapping of the form ("<base>/<filename>/<other>", "<dpi>") -> candidate.
    // For example:
    //                                    mdpi                               hdpi
    //                       --------------------------------------------------------------------
    // key: res/some.png/    |  res/drawable-mdpi/some.png          res/drawable-hdpi/some.png
    // key: res/some.png/fr  |  res/drawable-fr-hdpi/some.png
    for (Path candidate : candidates) {
        Qualifiers qualifiers = Qualifiers.from(candidate.getParent());

        String filename = candidate.getFileName().toString();
        Density density = qualifiers.density;
        String resDirectory = candidate.getParent().getParent().toString();
        String key = String.format("%s/%s/%s", resDirectory, filename, qualifiers.others);
        imageValues.put(key, density, candidate);
    }

    for (String key : imageValues.rowKeySet()) {
        Map<Density, Path> options = imageValues.row(key);
        Set<Density> available = options.keySet();

        // This is to make sure we preserve the existing structure of drawable/ files.
        Set<Density> targets = targetDensities;
        if (available.contains(Density.NO_QUALIFIER) && !available.contains(Density.MDPI)) {
            targets = Sets.newHashSet(Iterables.transform(targetDensities,
                    input -> (input == Density.MDPI) ? Density.NO_QUALIFIER : input));
        }

        // We intend to keep all available targeted densities.
        Set<Density> toKeep = Sets.newHashSet(Sets.intersection(available, targets));

        // Make sure we have a decent fit for the largest target density.
        Density largestTarget = Density.ORDERING.max(targets);
        if (!available.contains(largestTarget)) {
            Density fallback = null;
            // Downscaling nine-patch drawables would require extra logic, not doing that yet.
            if (canDownscale && !options.values().iterator().next().toString().endsWith(".9.png")) {
                // Highest possible quality, because we'll downscale it.
                fallback = Density.ORDERING.max(available);
            } else {
                // We want to minimize size, so we'll go for the smallest available density that's
                // still larger than the missing one and, missing that, for the largest available.
                for (Density candidate : Density.ORDERING.reverse().sortedCopy(available)) {
                    if (fallback == null || Density.ORDERING.compare(candidate, largestTarget) > 0) {
                        fallback = candidate;
                    }
                }
            }
            toKeep.add(fallback);
        }

        // Mark remaining densities for removal.
        for (Density density : Sets.difference(available, toKeep)) {
            removals.add(options.get(density));
        }
    }

    return removals.build();
}

From source file:com.opengamma.engine.view.calc.CompositeMarketDataSnapshot.java

/**
 * Returns the values from the underlying snapshots if they are available
 * @param requirements the values required, not null
 * @return The values from the underlying snapshots if they are available, values that aren't available will be
 * missing from the results map/*from ww  w .j ava 2 s .c  o m*/
 */
@Override
public Map<ValueRequirement, ComputedValue> query(Set<ValueRequirement> requirements) {
    ArgumentChecker.notNull(requirements, "requirements");
    Map<ValueRequirement, ComputedValue> results = Maps.newHashMapWithExpectedSize(requirements.size());
    List<Set<ValueRequirement>> subscriptions = _subscriptionSupplier.get();
    for (int i = 0; i < _snapshots.size(); i++) {
        MarketDataSnapshot snapshot = _snapshots.get(i);
        Set<ValueRequirement> snapshotSubscriptions = subscriptions.get(i);
        Set<ValueRequirement> snapshotRequirements = Sets.intersection(snapshotSubscriptions, requirements);
        if (!snapshotRequirements.isEmpty()) {
            Map<ValueRequirement, ComputedValue> snapshotValues = snapshot.query(snapshotRequirements);
            results.putAll(snapshotValues);
        }
    }
    return results;
}

From source file:eu.fbk.materializer.PathAnalysis.java

public Level[] buildLevels(Edge[] edges) {
    if (!isConnected(edges))
        throw new IllegalArgumentException("Edges must be connected.");

    final List<List<Edge>> sortedEdges = sortPathDepthFirst(edges[0].cLeft,
            new ArrayList<>(Arrays.asList(edges)));
    final Level[] levels = new Level[sortedEdges.size()];
    int i = 0;//from w w w .j  a va 2  s .  com
    for (List<Edge> sortedEdge : sortedEdges) {
        boolean revert = i > 1 && i < edges.length - 1
                && Sets.intersection(getRight(sortedEdges.get(i - 1)), getLeft(sortedEdges.get(i))).isEmpty();
        levels[i++] = new Level(revert, sortedEdge.toArray(new Edge[sortedEdge.size()]));
    }
    return levels;
}

From source file:org.apache.rya.indexing.accumulo.entity.StarQuery.java

public static Set<String> getCommonVars(final StarQuery query, final BindingSet bs) {

    final Set<String> starQueryVarNames = Sets.newHashSet();

    if (bs == null || bs.size() == 0) {
        return Sets.newHashSet();
    }//  w  w w  .j av  a2 s.c o m

    final Set<String> bindingNames = bs.getBindingNames();
    starQueryVarNames.addAll(query.getUnCommonVars());
    if (!query.commonVarConstant()) {
        starQueryVarNames.add(query.getCommonVarName());
    }

    return Sets.intersection(bindingNames, starQueryVarNames);

}

From source file:org.fenixedu.academic.domain.serviceRequests.documentRequests.DiplomaRequest.java

@Override
final public EventType getEventType() {
    final Set<EventType> eventTypesToUse = Sets.intersection(getPossibleEventTypes(),
            getProgramConclusion().getEventTypes().getTypes());

    if (eventTypesToUse.size() != 1) {
        throw new DomainException("error.program.conclusion.many.event.types");
    }/*  w  w w  .ja va2  s . c o  m*/

    return eventTypesToUse.iterator().next();
}

From source file:com.google.cloud.ExceptionHandler.java

private ExceptionHandler(Builder builder) {
    interceptors = builder.interceptors.build();
    retriableExceptions = builder.retriableExceptions.build();
    nonRetriableExceptions = builder.nonRetriableExceptions.build();
    Preconditions.checkArgument(Sets.intersection(retriableExceptions, nonRetriableExceptions).isEmpty(),
            "Same exception was found in both retryable and non-retryable sets");
    for (Class<? extends Exception> exception : retriableExceptions) {
        addRetryInfo(new RetryInfo(exception, Interceptor.RetryResult.RETRY), retryInfo);
    }/*from  ww w.j a v a  2  s  .c o  m*/
    for (Class<? extends Exception> exception : nonRetriableExceptions) {
        addRetryInfo(new RetryInfo(exception, Interceptor.RetryResult.NO_RETRY), retryInfo);
    }
}

From source file:org.jasig.cas.services.DefaultRegisteredServiceAccessStrategy.java

/**
 * {@inheritDoc}//from w ww.jav  a  2s.  com
 *
 * Verify presence of service required attributes.
 * <ul>
 *     <li>If no required attributes are specified, authz is granted.</li>
 *     <li>If ALL required attributes must be present, and the principal contains all and there is
 *     at least one attribute value that matches the required, authz is granted.</li>
 *     <li>If ALL required attributes don't have to be present, and there is at least
 *     one principal attribute present whose value matches the required, authz is granted.</li>
 *     <li>Otherwise, access is denied</li>
 * </ul>
 * Note that comparison of principal/required attributes is case-sensitive. Exact matches are required
 * for any individual attribute value.
 */
@Override
public boolean doPrincipalAttributesAllowServiceAccess(final Map<String, Object> principalAttributes) {
    if (this.requiredAttributes.isEmpty()) {
        logger.debug("No required attributes are specified");
        return true;
    }
    if (principalAttributes.isEmpty()) {
        logger.debug("No principal attributes are found to satisfy attribute requirements");
        return false;
    }

    if (principalAttributes.size() < this.requiredAttributes.size()) {
        logger.debug(
                "The size of the principal attributes that are [{}] does not match requirements, "
                        + "which means the principal is not carrying enough data to grant authorization",
                principalAttributes);
        return false;
    }

    logger.debug("These required attributes [{}] are examined against [{}] before service can proceed.",
            getRequiredAttributes(), principalAttributes);

    final Sets.SetView<String> difference = Sets.intersection(getRequiredAttributes().keySet(),
            principalAttributes.keySet());
    final Set<String> copy = difference.immutableCopy();

    if (this.requireAllAttributes && copy.size() < this.requiredAttributes.size()) {
        logger.debug("Not all required attributes are available to the principal");
        return false;
    }

    for (final String key : copy) {
        final Set<?> requiredValues = this.requiredAttributes.get(key);
        Set<?> availableValues;

        final Object objVal = principalAttributes.get(key);
        if (objVal instanceof Collection) {
            final Collection valCol = (Collection) objVal;
            availableValues = Sets.newHashSet(valCol.toArray());
        } else {
            availableValues = Collections.singleton(objVal);
        }

        final Sets.SetView<?> differenceInValues = Sets.intersection(availableValues, requiredValues);
        if (differenceInValues.size() > 0) {
            logger.info("Principal is authorized to access the service");
            return true;
        }
    }
    logger.info("Principal is denied access as the required attributes for the registered service are missing");
    return false;
}