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.apache.rya.accumulo.pcj.iterators.BindingSetHashJoinIterator.java

/**
 * This method verifies that all common variables have a common value and
 * then joins the BindingSets together. In the case that the PCJ contains a
 * LeftJoin, if the leftBs and rightBs have a common variable with distinct
 * values and that common variable is unassured (only appears in LeftJoin),
 * this method uses the value corresponding to leftBs.
 *
 * @param leftBs// www.jav  a2  s  . co  m
 *            - BindingSet passed into PCJ
 * @param rightBs
 *            - PCJ BindingSet
 * @return - joined BindingSet
 */
private BindingSet joinBindingSets(BindingSet leftBs, BindingSet rightBs) {

    Set<String> commonVars = Sets.intersection(leftBs.getBindingNames(), rightBs.getBindingNames());
    // compare values associated with common variables to make sure
    // BindingSets can be joined. Possible for leftBs and rightBs
    // to have a common unAssuredVariable in event PCJ contains LeftJoin.
    // if values corresponding to common unAssuredVariable do not agree
    // add value corresponding to leftBs
    for (String s : commonVars) {
        if (!leftBs.getValue(s).equals(rightBs.getValue(s)) && !unAssuredVariables.contains(s)) {
            return EMPTY_BINDINGSET;
        }
    }
    QueryBindingSet bs = new QueryBindingSet(removeConstants(leftBs));

    rightBs = removeConstants(rightBs);
    // only add Bindings corresponding to variables that have no value
    // assigned. This takes into account case where leftBs and rightBs
    // share a common, unAssuredVariable. In this case, use value
    // corresponding
    // to leftBs, which is effectively performing a LeftJoin.
    for (String s : rightBs.getBindingNames()) {
        if (bs.getValue(s) == null) {
            bs.addBinding(s, rightBs.getValue(s));
        }
    }

    return bs;
}

From source file:org.dllearner.refinementoperators.Utility.java

/**
 * Given a set of applicable object properties, this method returns
 * the most general ones, i.e. those where more general ones do not
 * exist in the set of applicable properties. Due to the definition
 * of "applicable", the returned set is just the intersection of the most
 * general object properties and the applicable properties. (A non-applicable
 * property cannot have applicable subproperties, because subproperties
 * can only restrict, but not broaden their domain.)
 * /*from w w w. j  ava 2 s.c o  m*/
 * @param applicableObjectProperties The set of applicable properties.
 * @return The most general applicable properties.
 */
public Set<OWLObjectProperty> computeMgr(Set<OWLObjectProperty> applicableObjectProperties) {
    return new HashSet<>(Sets.intersection(reasoner.getMostGeneralProperties(), applicableObjectProperties));
}

From source file:org.apache.sentry.api.generic.thrift.SentryGenericPolicyProcessor.java

private boolean inAdminGroups(Set<String> requestorGroups) {
    return !Sets.intersection(adminGroups, requestorGroups).isEmpty();
}

From source file:mvm.rya.indexing.accumulo.entity.StarQuery.java

public static StarQuery getConstrainedStarQuery(StarQuery query, BindingSet bs) {

    if (bs.size() == 0) {
        return query;
    }/*from   w ww  . j ava  2 s.co  m*/

    Set<String> bindingNames = bs.getBindingNames();
    Set<String> unCommonVarNames = query.getUnCommonVars();
    Set<String> intersectVar = Sets.intersection(bindingNames, unCommonVarNames);

    if (!query.commonVarConstant()) {

        Value v = bs.getValue(query.getCommonVarName());

        if (v != null) {
            query.commonVar.setValue(v);
        }
    }

    for (String s : intersectVar) {
        try {
            query.nodeColumnCond[query.varPos.get(s)] = query
                    .setValue(query.nodeColumnCond[query.varPos.get(s)], bs.getValue(s));
        } catch (RyaTypeResolverException e) {
            e.printStackTrace();
        }
    }

    return query;
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRacePointsData.java

protected Map<Race, Integer> calculateFleetSizes(FleetMethod fleetMethod) {
    Map<Race, Integer> fleetSizes = new HashMap<Race, Integer>();
    switch (fleetMethod) {
    case RACE://from  ww w . ja  va 2s.  co  m
        for (Race race : scores.getRaces()) {
            fleetSizes.put(race, Sets.intersection(scores.getFleet(), race.getAttendees().keySet()).size());
        }
        break;

    case EVENT: {
        Map<Event, Integer> eventFleetSizes = new HashMap<Event, Integer>();
        for (Race race : scores.getRaces()) {
            Event event = race.getEvent();

            if (!eventFleetSizes.containsKey(event)) {
                Set<Pilot> pilots = new HashSet<Pilot>(scores.getSeries().getPilots().size() * 2);

                pilots.addAll(event.getAttendees());

                for (Race race2 : event.getRaces()) {
                    pilots.addAll(race2.getAttendees().keySet());
                }

                eventFleetSizes.put(event, Sets.intersection(scores.getFleet(), pilots).size());
            }

            fleetSizes.put(race, eventFleetSizes.get(event));
        }

        break;
    }

    case SERIES: {
        Set<Pilot> pilots = new HashSet<Pilot>(scores.getSeries().getPilots().size() * 2);
        for (Event event : scores.getSeries().getEvents()) {
            pilots.addAll(event.getAttendees());

            for (Race race : event.getRaces()) {
                pilots.addAll(race.getAttendees().keySet());
            }
        }

        int fleetSize = Sets.intersection(scores.getFleet(), pilots).size();
        for (Race race : scores.getRaces()) {
            fleetSizes.put(race, fleetSize);
        }

        break;
    }

    case RACES_SCORED: {
        Set<Pilot> pilots = new HashSet<Pilot>(scores.getPilots().size() * 2);
        for (Race race : scores.getRaces()) {
            pilots.addAll(race.getAttendees().keySet());
        }

        int fleetSize = Sets.intersection(scores.getFleet(), pilots).size();
        for (Race race : scores.getRaces()) {
            fleetSizes.put(race, fleetSize);
        }

        break;
    }

    case EVENTS_SCORED: {
        Set<Pilot> pilots = new HashSet<Pilot>(scores.getPilots().size() * 2);
        for (Event event : scores.getEvents()) {
            pilots.addAll(event.getAttendees());

            for (Race race : event.getRaces()) {
                pilots.addAll(race.getAttendees().keySet());
            }
        }

        int fleetSize = Sets.intersection(scores.getFleet(), pilots).size();
        for (Race race : scores.getRaces()) {
            fleetSizes.put(race, fleetSize);
        }

        break;
    }

    case PILOTS:
        for (Race race : scores.getRaces()) {
            fleetSizes.put(race, scores.getFleet().size());
        }
        break;
    }
    return fleetSizes;
}

From source file:ezbake.groups.graph.query.AuthorizationQuery.java

/**
 * Will get a user's authorizations, filtering by the groups that apps in the filter chain have access to
 *
 * @param type type of user to look for//from w  ww .ja v  a  2s .  c om
 * @param id user id
 * @param appFilterChain
 * @return the user's set of group authorizations
 */
public Set<Long> getAuthorizationSet(BaseVertex.VertexType type, String id, List<String> appFilterChain)
        throws GroupQueryException {
    Set<Long> auths = Sets.newHashSet();

    // Only get auths if the user exists
    User user;
    try {
        user = graph.getUser(type, id);
        if (!user.isActive()) {
            logger.debug("User was inactive, returning empty set");
            return auths; // just don't get groups
        }
    } catch (InvalidVertexTypeException e) {
        logger.debug("Invalid request, returning empty set");
        return auths; // just don't get groups
    } catch (UserNotFoundException e) {
        throw new GroupQueryException("No user found: " + type + ":" + id, GroupQueryError.USER_NOT_FOUND);
    }

    // Add the user's own index
    logger.debug("Adding user's id to the auths: {}", user.getIndex());
    auths.add(user.getIndex());

    // This can sometimes be null
    if (appFilterChain == null) {
        appFilterChain = Collections.emptyList();
    }

    // These are the groups the user has on their own
    Set<Group> userGroups = getUserGroups(type, id, false);
    for (Group g : userGroups) {
        logger.debug("Group -> {} {}", g.getGroupName(), g.getIndex());
    }
    logger.debug("getAuthorizations User: {} has groups: {}", user, userGroups);

    // These are the groups the apps always include, even if the user doesn't have access
    Collection<Set<Group>> appsGroups = getUserGroups(
            userListToMap(BaseVertex.VertexType.APP_USER, appFilterChain), false);
    Set<Long> appsFilter = Sets.newHashSet(); // This is the intersection of all app auths
    Set<Long> groupsAppsAlwaysInclude = Sets.newTreeSet(); // This is all the groups the apps include anyways
    for (Set<Group> appGroup : appsGroups) {
        Set<Long> indices = Sets.newTreeSet();
        for (Group group : appGroup) {
            indices.add(group.getIndex());
            if (group.isRequireOnlyApp()) {
                groupsAppsAlwaysInclude.add(group.getIndex());
            }
        }
        appsFilter.retainAll(indices);
    }

    if (type == BaseVertex.VertexType.USER) {
        // Split groups into 2 sets - those that users always have (even if app doesn't) and those that users only have if app has too
        Set<Long> groupsUserHasRegardless = Sets.newHashSet(auths);
        Set<Long> groupsDependingOnApp = Sets.newHashSet();
        for (Group g : userGroups) {
            if (g.isRequireOnlyUser()) {
                logger.debug("User should have group: {} regardless", g);
                groupsUserHasRegardless.add(g.getIndex());
            } else {
                logger.debug("Will check app access to group: {}", g);
                groupsDependingOnApp.add(g.getIndex());
            }
        }

        // Filter the groups that depend on the app
        if (!groupsDependingOnApp.isEmpty()) {
            logger.debug("Filtering groups depending on app: {} -> {}", groupsDependingOnApp, appsFilter);
            groupsDependingOnApp = Sets.intersection(groupsDependingOnApp, appsFilter);
            logger.debug("Filter result: {}", groupsDependingOnApp);
        }

        // Now union the sets to get the users final list
        auths = Sets.union(groupsUserHasRegardless, groupsDependingOnApp);
        logger.debug("Auths after taking intersection: {}", auths);
    } else if (type == BaseVertex.VertexType.APP_USER) {
        // What to do here?
        Set<Long> appAuths = Sets.newHashSet(auths);
        for (Group g : userGroups) {
            appAuths.add(g.getIndex());
        }
        auths = appAuths;
    }

    graph.commitTransaction();
    return Sets.union(auths, groupsAppsAlwaysInclude);
}

From source file:co.mitro.analysis.AuditLogProcessor.java

public static Collection<DBProcessedAudit> getActionsForTransactionId(Manager manager, String transactionId)
        throws SQLException {
    Set<DBAudit.ACTION> actions = Sets.newHashSet();
    List<DBAudit> matchingAuditLogs = manager.auditDao.queryForEq(DBAudit.TRANSACTION_ID_FIELD_NAME,
            new SelectArg(transactionId));
    String operationName = null;/*from  w  w w. j  a  v  a2 s . c o  m*/

    List<DBProcessedAudit> rval = Lists.newArrayList();
    List<DBProcessedAudit> invites = Lists.newArrayList();

    // these need to be maps and not sets because equals() and hashCode() aren't
    // properly implemented in these db objects.
    Map<Integer, DBGroup> affectedGroups = Maps.newHashMap();
    Map<Integer, DBServerVisibleSecret> affectedSecrets = Maps.newHashMap();
    Map<Integer, DBAudit> actionTargets = Maps.newHashMap();

    // First look through the audit logs that match the txn id, and figure
    // out if we've invited any users. If so, we make special events for them.
    for (DBAudit audit : matchingAuditLogs) {
        if (audit.getUser() == null && !DBAudit.TRANSACTION_ACTIONS.contains(audit.getAction())) {
            continue;
        }
        if (audit.getTargetGroup() != null) {
            affectedGroups.put(audit.getTargetGroup().getId(), audit.getTargetGroup());
        }
        if (audit.getTargetSVS() != null) {
            affectedSecrets.put(audit.getTargetSVS().getId(), audit.getTargetSVS());
        }

        actions.add(audit.getAction());
        operationName = (operationName == null) ? audit.getOperationName() : operationName;
        if (ACTION.INVITE_NEW_USER == audit.getAction()) {
            invites.add(new DBProcessedAudit(ActionType.INVITE_USER, audit));
            invites.add(new DBProcessedAudit(ActionType.INVITED_BY_USER, audit));
            // we don't care about the new user's private group
            audit.setTargetGroup(null);
            if (null != audit.getTargetUser()) {
                actionTargets.put(audit.getId(), audit);
            }
        }
    }

    // has this transaction been cancelled or rolled back? If so, don't add any events.
    if (!Sets.intersection(actions, DBAudit.UNCOMMITTED_TRANSACTIONS).isEmpty()
            || !actions.contains(DBAudit.ACTION.TRANSACTION_COMMIT)) {
        return Collections.emptyList();
    }

    ActionType actionType = null;
    if (!Strings.isNullOrEmpty(operationName)) {
        // operation name is present in the log. This is pretty easy.
        actionType = OP_NAME_TO_ACTION_TYPE.get(operationName);
        if (actionType != null && actionType != ActionType.UNKNOWN && actionType != ActionType.NOOP) {
            if (actionTargets.isEmpty()) {
                // if we don't have any action targets, it doesn't matter which audit object we use to create
                // the processed audit.
                addFromMatchingAudits(actionType, matchingAuditLogs, rval);
            } else {
                // here, we have information about action targets. We must add a processed audit record for each.
                for (DBAudit audit : actionTargets.values())
                    rval.add(new DBProcessedAudit(actionType, audit));
            }
        }
    } else {
        // no operation name, thus we must infer what happened in this transaction.
        if (actions.contains(DBAudit.ACTION.CREATE_IDENTITY)) {
            actionType = ActionType.SIGNUP;
        } else if (actions.contains(DBAudit.ACTION.GET_SECRET_WITH_CRITICAL) && actions.size() == 2) {
            // there are a bunch of different txns that could have GET_SECRET_WITH_CRITICAL
            // the ones that have only that and commit txn are for logins. 
            actionType = ActionType.GET_SECRET_CRITICAL_DATA_FOR_LOGIN;
        } else if (actions.contains(DBAudit.ACTION.GET_PRIVATE_KEY)) {
            actionType = ActionType.MITRO_LOGIN;
        }
        addFromMatchingAudits(actionType, matchingAuditLogs, rval);
    }

    // some kinds of transactions affect at most one group.
    if (TRACK_GROUPS.contains(actionType)) {
        if (affectedGroups.size() > 1) {
            logger.warn("transaction {} has more than one affected group. Ignoring groups for now...",
                    transactionId);
        } else if (!affectedGroups.isEmpty()) {
            final DBGroup g = affectedGroups.values().iterator().next();
            for (DBProcessedAudit a : rval) {
                a.setAffectedGroup(g);
            }
        }
    }

    // some kinds of transactions affect at most one secret.
    if (TRACK_SECRETS.contains(actionType)) {
        if (affectedSecrets.size() > 1) {
            logger.warn("transaction {} has more than one affected secret. Ignoring secrets for now...",
                    transactionId);
        } else if (!affectedSecrets.isEmpty()) {
            final DBServerVisibleSecret s = affectedSecrets.values().iterator().next();
            for (DBProcessedAudit a : rval) {
                a.setAffectedSecret(s);
            }
        }
    }

    rval.addAll(invites);
    return rval;
}

From source file:org.sosy_lab.cpachecker.util.predicates.interpolation.strategy.ITPStrategy.java

/**
 * This method checks the validity of the interpolants according to
 * the current interpolation strategy.//w  w  w. j  av  a2  s.c  om
 * The default interpolation strategy is sequential interpolation,
 * i.e. we assume:  \forall i \in [1..n-1] : itp_{i-1} & f_i => itp_i
 * This method can be overridden if the strategy computes interpolants
 * with a different strategy.
 *
 * @param solver is for checking satisfiability
 * @param formulasWithStatesAndGroupdIds is a list of (F,E,T) where
 *          the path formula F starting at an abstract state E corresponds
 *          with the ITP-group T. We assume the sorting of the list matches
 *          the order of abstract states along the counterexample.
 * @param interpolants computed with {@link getInterpolants} and will be checked.
 */
public void checkInterpolants(final Solver solver,
        final List<Triple<BooleanFormula, AbstractState, T>> formulasWithStatesAndGroupdIds,
        final List<BooleanFormula> interpolants) throws InterruptedException, SolverException {

    final List<BooleanFormula> formulas = Lists.transform(formulasWithStatesAndGroupdIds,
            Triple.<BooleanFormula>getProjectionToFirst());

    final int n = interpolants.size();
    assert n == (formulas.size() - 1);

    // The following three properties need to be checked:
    // (A)                          true      & f_0 => itp_0
    // (B) \forall i \in [1..n-1] : itp_{i-1} & f_i => itp_i
    // (C)                          itp_{n-1} & f_n => false

    // Check (A)
    if (!solver.implies(formulas.get(0), interpolants.get(0))) {
        throw new SolverException("First interpolant is not implied by first formula");
    }

    // Check (B).
    for (int i = 1; i <= (n - 1); i++) {
        BooleanFormula conjunct = bfmgr.and(interpolants.get(i - 1), formulas.get(i));
        if (!solver.implies(conjunct, interpolants.get(i))) {
            throw new SolverException(
                    "Interpolant " + interpolants.get(i) + " is not implied by previous part of the path");
        }
    }

    // Check (C).
    BooleanFormula conjunct = bfmgr.and(interpolants.get(n - 1), formulas.get(n));
    if (!solver.implies(conjunct, bfmgr.makeBoolean(false))) {
        throw new SolverException("Last interpolant fails to prove infeasibility of the path");
    }

    // Furthermore, check if the interpolants contains only the allowed variables
    final List<Set<String>> variablesInFormulas = Lists.newArrayListWithExpectedSize(formulas.size());
    for (BooleanFormula f : formulas) {
        variablesInFormulas.add(fmgr.extractVariableNames(f));
    }

    for (int i = 0; i < interpolants.size(); i++) {

        Set<String> variablesInA = new HashSet<>();
        for (int j = 0; j <= i; j++) {
            // formula i is in group A
            variablesInA.addAll(variablesInFormulas.get(j));
        }

        Set<String> variablesInB = new HashSet<>();
        for (int j = i + 1; j < formulas.size(); j++) {
            // formula i is in group A
            variablesInB.addAll(variablesInFormulas.get(j));
        }

        Set<String> allowedVariables = Sets.intersection(variablesInA, variablesInB).immutableCopy();
        Set<String> variablesInInterpolant = fmgr.extractVariableNames(interpolants.get(i));

        variablesInInterpolant.removeAll(allowedVariables);

        if (!variablesInInterpolant.isEmpty()) {
            throw new SolverException("Interpolant " + interpolants.get(i) + " contains forbidden variable(s) "
                    + variablesInInterpolant);
        }
    }
}

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

/**
 * Derive current node's preferred properties based on parent's preferences
 *
 * @param parentProperties Parent's preferences (translated)
 * @param partitioningColumns partitioning columns of current node
 * @param hashingColumns hashing columns of current node
 * @param localProperties local properties of current node
 * @return PreferredProperties for current node
 *///from  w  w  w.j a  va2 s. com
public static PreferredProperties derivePreferences(PreferredProperties parentProperties,
        Set<Symbol> partitioningColumns, Optional<List<Symbol>> hashingColumns,
        List<LocalProperty<Symbol>> localProperties) {
    if (hashingColumns.isPresent()) {
        checkState(partitioningColumns.equals(ImmutableSet.copyOf(hashingColumns.get())),
                "hashingColumns and partitioningColumns must be the same");
    }

    List<LocalProperty<Symbol>> local = ImmutableList.<LocalProperty<Symbol>>builder().addAll(localProperties)
            .addAll(parentProperties.getLocalProperties()).build();

    // Check we need to be hash partitioned
    if (hashingColumns.isPresent()) {
        return hashPartitionedWithLocal(hashingColumns.get(), local);
    }

    if (parentProperties.getGlobalProperties().isPresent()) {
        Global global = parentProperties.getGlobalProperties().get();
        if (global.getPartitioningProperties().isPresent()) {
            Partitioning partitioning = global.getPartitioningProperties().get();

            // If parent's hash partitioning satisfies our partitioning, use parent's hash partitioning
            if (partitioning.getHashingOrder().isPresent()
                    && partitioningColumns.equals(ImmutableSet.copyOf(partitioning.getHashingOrder().get()))) {
                List<Symbol> hashingSymbols = partitioning.getHashingOrder().get();
                return hashPartitionedWithLocal(hashingSymbols, local);
            }

            // if the child plan is partitioned by the common columns between our requirements and our parent's, it can satisfy both in one shot
            Set<Symbol> parentPartitioningColumns = partitioning.getPartitioningColumns();
            Set<Symbol> common = Sets.intersection(partitioningColumns, parentPartitioningColumns);

            // If we find common partitioning columns, use them, else use child's partitioning columns
            if (!common.isEmpty()) {
                return partitionedWithLocal(common, local);
            }
            return partitionedWithLocal(partitioningColumns, local);
        }
    }
    return partitionedWithLocal(partitioningColumns, local);
}

From source file:com.google.template.soy.parsepasses.SafetyInfo.java

/**
 * Merges the given SafetyInfo objects into a new SafetyInfo object. A data path is only safe in
 * the merged SafetyInfo if it is safe in all the input SafetyInfos.
 *///from w w w.j a va2  s  .  com
public static SafetyInfo merge(Collection<SafetyInfo> safetyInfos) {

    // Special cases.
    if (safetyInfos.size() == 0) {
        return EMPTY_INSTANCE;
    }
    if (safetyInfos.size() == 1) {
        return clone(Iterators.getOnlyElement(safetyInfos.iterator()));
    }

    SafetyInfo mergedInfo = new SafetyInfo();

    // Determine the isSafe value on the mergedInfo.
    boolean mergedIsSafe = true;
    for (SafetyInfo safetyInfo : safetyInfos) {
        if (!safetyInfo.isSafe) {
            mergedIsSafe = false;
            break;
        }
    }
    mergedInfo.isSafe = mergedIsSafe;

    // Determine the merged keys at the current level.
    boolean isStarMergedKey = true;
    Set<String> nonstarMergedKeys = null;
    for (SafetyInfo safetyInfo : safetyInfos) {
        if (safetyInfo.starSubinfo != null) {
            continue; // doesn't subtract from merged keys
        }
        if (isStarMergedKey) {
            isStarMergedKey = false;
            nonstarMergedKeys = Sets.newHashSet(safetyInfo.nonstarSubinfos.keySet());
        } else {
            nonstarMergedKeys = Sets.intersection(nonstarMergedKeys, safetyInfo.nonstarSubinfos.keySet());
        }
    }

    // For each merged key, merge subinfos and put the new merged subinfo.
    if (isStarMergedKey) {
        List<SafetyInfo> subinfosToMerge = Lists.newArrayList();
        for (SafetyInfo safetyInfo : safetyInfos) {
            subinfosToMerge.add(safetyInfo.starSubinfo);
        }
        mergedInfo.starSubinfo = merge(subinfosToMerge);
    } else {
        for (String mergedKey : nonstarMergedKeys) {
            List<SafetyInfo> subinfosToMerge = Lists.newArrayList();
            for (SafetyInfo safetyInfo : safetyInfos) {
                // Important: Must use getSubinfo() and not nonstarSubinfos.get() to retrieve subinfo
                // because some safetyInfos may have '*' key at this level while others have non-'*' key.
                subinfosToMerge.add(safetyInfo.getSubinfo(mergedKey));
            }
            mergedInfo.putSubinfo(mergedKey, merge(subinfosToMerge));
        }
    }

    return mergedInfo;
}