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:com.yahoo.yqlplus.engine.rules.NormalizeJoinExpression.java

private OperatorNode<ExpressionOperator> normalizeJoinClause(Set<String> leftSources, Set<String> rightSources,
        OperatorNode<ExpressionOperator> joinExpr) {
    switch (joinExpr.getOperator()) {
    case AND: {// ww w  .j  av  a  2 s  .  c om
        List<OperatorNode<ExpressionOperator>> clauses = joinExpr.getArgument(0);
        List<OperatorNode<ExpressionOperator>> newClauses = Lists.newArrayListWithExpectedSize(clauses.size());
        boolean hasNew = false;
        for (OperatorNode<ExpressionOperator> clause : clauses) {
            OperatorNode<ExpressionOperator> newClause = normalizeJoinClause(leftSources, rightSources, clause);
            if (newClause != clause) {
                hasNew = true;
            }
            newClauses.add(newClause);
        }
        if (hasNew) {
            return OperatorNode.create(joinExpr.getLocation(), joinExpr.getAnnotations(),
                    joinExpr.getOperator(), newClauses);
        }
        return joinExpr;
    }
    case EQ: {
        OperatorNode<ExpressionOperator> leftExpr = joinExpr.getArgument(0);
        OperatorNode<ExpressionOperator> rightExpr = joinExpr.getArgument(1);
        Set<String> leftReferenced = findReferencedSources(leftExpr);
        Set<String> rightReferenced = findReferencedSources(rightExpr);
        boolean ll = !Sets.intersection(leftSources, leftReferenced).isEmpty();
        boolean lr = !Sets.intersection(leftSources, rightReferenced).isEmpty();
        boolean rl = !Sets.intersection(rightSources, leftReferenced).isEmpty();
        boolean rr = !Sets.intersection(rightSources, rightReferenced).isEmpty();
        // ll - left expr references left sources
        // lr - left expr references right sources
        // rl - right expr references left sources
        // rr - right expr references right sources
        // verify neither expr references BOTH sides
        if (ll && lr) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality LEFT side references BOTH sides of JOIN");
        } else if (rl && rr) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality RIGHT side references BOTH sides of JOIN");
        } else if (!(ll || lr)) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality LEFT side references NEITHER side of JOIN");
        } else if (!(rl || rr)) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality RIGHT side references NEITHER side of JOIN");
        }
        // normalize ordering so left side of EQ refers to left side of join
        if (lr) {
            assert rl : "lr without rl - if left side references right sources, then visa versa must be true";
            return OperatorNode.create(joinExpr.getLocation(), joinExpr.getAnnotations(),
                    joinExpr.getOperator(), rightExpr, leftExpr);
        }
        return joinExpr;
    }
    default:
        throw new ProgramCompileException(joinExpr.getLocation(),
                "Only EQ is a supported JOIN expression operator at this time (not %s)",
                joinExpr.getOperator());
    }
}

From source file:ezbake.groups.cli.commands.user.GetUserAuthorizations.java

private static Set<Long> getAuthorizations(EzGroupsGraphImpl graph, BaseVertex.VertexType userType,
        String userId, List<String> appFilterChain) throws GroupQueryException, UserNotFoundException {
    Set<Long> auths = Sets.newHashSet();

    // Only get auths if the user exists
    User user;//from  w  w w .  j av a 2s  . c o  m
    try {
        user = graph.getUser(userType, userId);
        if (!user.isActive()) {
            return auths; // just don't get groups
        }
    } catch (UserNotFoundException | InvalidVertexTypeException e) {
        return auths; // just don't get groups
    }

    // Add the user's own index
    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(graph, userType, userId, false, false);
    logger.debug("Initial user groups: {}", userGroups);

    // These are the groups the apps always include, even if the user doesn't have access
    List<Set<Group>> appsGroups = getAuthorizationsForApps(graph, 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);
    }
    logger.debug("Apps filter: {}", appsFilter);

    if (userType == 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()) {
                groupsUserHasRegardless.add(g.getIndex());
            } else {
                groupsDependingOnApp.add(g.getIndex());
            }
        }

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

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

    logger.debug("User auths before union: {}", auths);
    return Sets.union(auths, groupsAppsAlwaysInclude);
}

From source file:grakn.core.server.kb.concept.ConceptUtils.java

/**
 * perform an answer merge with optional explanation
 * NB:assumes answers are compatible (concept corresponding to join vars if any are the same)
 *
 * @return merged answer//w  w w  .ja  va 2 s.  c  om
 */
public static ConceptMap mergeAnswers(ConceptMap answerA, ConceptMap answerB) {
    if (answerB.isEmpty())
        return answerA;
    if (answerA.isEmpty())
        return answerB;

    Sets.SetView<Variable> varUnion = Sets.union(answerA.vars(), answerB.vars());
    Set<Variable> varIntersection = Sets.intersection(answerA.vars(), answerB.vars());
    Map<Variable, Concept> entryMap = Sets.union(answerA.map().entrySet(), answerB.map().entrySet()).stream()
            .filter(e -> !varIntersection.contains(e.getKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    varIntersection.forEach(var -> {
        Concept concept = answerA.get(var);
        Concept otherConcept = answerB.get(var);
        if (concept.equals(otherConcept))
            entryMap.put(var, concept);
        else {
            if (concept.isSchemaConcept() && otherConcept.isSchemaConcept() && !ConceptUtils
                    .areDisjointTypes(concept.asSchemaConcept(), otherConcept.asSchemaConcept(), false)) {
                entryMap.put(var, Iterables.getOnlyElement(ConceptUtils.topOrMeta(
                        Sets.newHashSet(concept.asSchemaConcept(), otherConcept.asSchemaConcept()))));
            }
        }
    });
    if (!entryMap.keySet().equals(varUnion))
        return new ConceptMap();
    return new ConceptMap(entryMap, answerA.explanation());
}

From source file:pt.ist.fenixedu.integration.ui.FenixEduISTLegacyContextListener.java

private static boolean partOf(Set<ExecutionCourse> degrees, StudentThesisCandidacy studentThesisCandidacy) {
    return Sets.intersection(degrees, studentThesisCandidacy.getThesisProposal().getExecutionDegreeSet())
            .isEmpty();//from   w ww .j a  va 2s. com
}

From source file:org.eclipse.sw360.portal.tags.DisplayReleaseChanges.java

private void renderReleaseIdToRelationship(StringBuilder display, User user) {

    if (ensureSomethingTodoAndNoNull(Release._Fields.RELEASE_ID_TO_RELATIONSHIP)) {

        Set<String> changedReleaseIds = Sets.intersection(additions.getReleaseIdToRelationship().keySet(),
                deletions.getReleaseIdToRelationship().keySet());
        Set<String> releaseIdsInDb = nullToEmptyMap(actual.getReleaseIdToRelationship()).keySet();
        //keep only releases that are still in the database
        changedReleaseIds = Sets.intersection(changedReleaseIds, releaseIdsInDb);

        Set<String> removedReleaseIds = Sets.difference(deletions.getReleaseIdToRelationship().keySet(),
                changedReleaseIds);// www  . j  a  v  a 2 s.co m
        removedReleaseIds = Sets.intersection(removedReleaseIds, releaseIdsInDb);

        Set<String> addedReleaseIds = Sets.difference(additions.getReleaseIdToRelationship().keySet(),
                changedReleaseIds);

        display.append("<h3> Changes in linked releases </h3>");
        LinkedReleaseRenderer renderer = new LinkedReleaseRenderer(display, tableClasses, idPrefix, user);
        renderer.renderReleaseLinkList(display, deletions.getReleaseIdToRelationship(), removedReleaseIds,
                "Removed Release Links");
        renderer.renderReleaseLinkList(display, additions.getReleaseIdToRelationship(), addedReleaseIds,
                "Added Release Links");
        renderer.renderReleaseLinkListCompare(display, actual.getReleaseIdToRelationship(),
                deletions.getReleaseIdToRelationship(), additions.getReleaseIdToRelationship(),
                changedReleaseIds);
    }
}

From source file:org.dishevelled.venn.model.VennModelImpl.java

/**
 * Create and return the map of exclusive set views keyed by bit set.
 *
 * @return the map of exclusive set views keyed by bit set
 *//*from w  w  w. ja v  a2 s.co m*/
private Map<ImmutableBitSet, Set<E>> createExclusives() {
    Map<ImmutableBitSet, Set<E>> map = Maps.newHashMapWithExpectedSize((int) Math.pow(2, this.sets.size()) - 1);

    // construct a set containing 0...n integers
    Set<Integer> input = Sets.newHashSet();
    for (int i = 0, size = size(); i < size; i++) {
        input.add(Integer.valueOf(i));
    }

    // calculate the power set (note n > 30 will overflow int)
    Set<Set<Integer>> powerSet = Sets.powerSet(ImmutableSet.copyOf(input));
    for (Set<Integer> set : powerSet) {
        if (!set.isEmpty()) {
            // intersect all in set
            Iterator<Integer> indices = set.iterator();
            Set<E> view = sets.get(indices.next());
            while (indices.hasNext()) {
                view = Sets.intersection(view, sets.get(indices.next()));
            }

            // subtract all in input not in set
            for (Integer index : input) {
                if (!set.contains(index)) {
                    view = Sets.difference(view, sets.get(index));
                }
            }

            // add to exclusives map
            map.put(toImmutableBitSet(set), view);
        }
    }

    // make an immutable copy?
    return map;
}

From source file:com.siemens.sw360.moderation.db.ModerationRequestGenerator.java

protected void dealWithStringMap(U field) {
    Map<String, String> addedMap = (Map<String, String>) updateDocument.getFieldValue(field);
    if (addedMap == null) {
        addedMap = new HashMap<>();
    }//from   ww w.ja va 2  s .  co m
    Map<String, String> actualMap = (Map<String, String>) actualDocument.getFieldValue(field);
    for (Map.Entry<String, String> entry : actualMap.entrySet()) {
        addedMap.remove(entry);
    }

    Map<String, String> deletedMap = (Map<String, String>) actualDocument.getFieldValue(field);
    if (deletedMap == null) {
        deletedMap = new HashMap<>();
    }
    Map<String, String> updateMap = (Map<String, String>) updateDocument.getFieldValue(field);
    for (Map.Entry<String, String> entry : updateMap.entrySet()) {
        deletedMap.remove(entry);
    }

    //determine changes in common linkedProjects
    Set<String> commonKeys = Sets.intersection(updateMap.keySet(), actualMap.keySet());
    for (String id : commonKeys) {
        String actual = actualMap.get(id);
        String update = updateMap.get(id);
        if (!actual.equals(update)) {
            addedMap.put(id, update);
            deletedMap.put(id, actual);
        }
    }
    if (!addedMap.isEmpty()) {
        documentAdditions.setFieldValue(field, addedMap);
    }
    if (!deletedMap.isEmpty()) {
        documentDeletions.setFieldValue(field, deletedMap);
    }
}

From source file:org.dllearner.utilities.ReasoningUtils.java

/**
 * binary partition a list of sets into true and false, depending on whether they satisfy concept
 * @param concept the OWL concept used for partition
 * @param sets list of sets to partition
 * @return an array of Coverage data, one entry for each input set
 *///from w w w. j av a 2  s.  c  o m
@SafeVarargs
public final Coverage[] getCoverage(OWLClassExpression concept, Set<OWLIndividual>... sets) {
    Coverage[] rv = new Coverage[sets.length];

    if (!reasoner.isUseInstanceChecks()) {
        if (reasoner instanceof SPARQLReasoner && ((SPARQLReasoner) reasoner).isUseValueLists()) {
            for (int i = 0; i < sets.length; ++i) {
                SortedSet<OWLIndividual> trueSet = reasoner.hasType(concept, sets[i]);

                rv[i] = new Coverage();
                rv[i].total = sets[i].size();

                rv[i].trueSet.addAll(trueSet);
                rv[i].falseSet.addAll(Sets.difference(sets[i], trueSet));

                rv[i].trueCount = rv[i].trueSet.size();
                rv[i].falseCount = rv[i].falseSet.size();
            }
        } else {
            SortedSet<OWLIndividual> individuals = reasoner.getIndividuals(concept);
            for (int i = 0; i < sets.length; ++i) {
                rv[i] = new Coverage();
                rv[i].total = sets[i].size();

                rv[i].trueSet.addAll(Sets.intersection(sets[i], individuals));
                rv[i].falseSet.addAll(Sets.difference(sets[i], individuals));

                rv[i].trueCount = rv[i].trueSet.size();
                rv[i].falseCount = rv[i].falseSet.size();
            }
        }
    } else {
        for (int i = 0; i < sets.length; ++i) {
            rv[i] = new Coverage();
            rv[i].total = sets[i].size();

            for (OWLIndividual example : sets[i]) {
                if (getReasoner().hasType(concept, example)) {
                    rv[i].trueSet.add(example);
                } else {
                    rv[i].falseSet.add(example);
                }
                if (interrupted()) {
                    return null;
                }
            }

            rv[i].trueCount = rv[i].trueSet.size();
            rv[i].falseCount = rv[i].falseSet.size();
        }
    }
    return rv;
}

From source file:fr.norad.jaxrs.oauth2.core.service.TokenSpecService.java

private Set<String> checkScopes(Set<String> requestedScopes, Client client, User user)
        throws InvalidScopeOauthException {
    Set<String> allowedScopes = client.getAllowedScopes();
    if (user != null) {
        for (Group group : user.getGroups()) {
            allowedScopes = Sets.union(allowedScopes, group.getAllowedScopes());
        }//from w  w w  .  j  av a2s.  c om
    }
    Sets.SetView<String> intersection = Sets.intersection(allowedScopes, requestedScopes);
    if (intersection.isEmpty()) {
        throw new InvalidScopeOauthException("No scope allowed requested");
    }
    return intersection;
}

From source file:org.apache.aurora.scheduler.state.StateManagerImpl.java

@Override
public void insertPendingTasks(MutableStoreProvider storeProvider, final ITaskConfig task,
        Set<Integer> instanceIds) {

    requireNonNull(storeProvider);/*from  w ww  . jav  a2  s. c  o m*/
    requireNonNull(task);
    checkNotBlank(instanceIds);

    // Done outside the write transaction to minimize the work done inside a transaction.
    Set<IScheduledTask> scheduledTasks = FluentIterable.from(instanceIds)
            .transform(instanceId -> createTask(instanceId, task)).toSet();

    Iterable<IScheduledTask> existingTasks = storeProvider.getTaskStore()
            .fetchTasks(Query.jobScoped(task.getJob()).active());

    Set<Integer> existingInstanceIds = FluentIterable.from(existingTasks).transform(Tasks::getInstanceId)
            .toSet();

    if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) {
        throw new IllegalArgumentException("Instance ID collision detected.");
    }

    storeProvider.getUnsafeTaskStore().saveTasks(scheduledTasks);

    for (IScheduledTask scheduledTask : scheduledTasks) {
        updateTaskAndExternalState(storeProvider.getUnsafeTaskStore(), Tasks.id(scheduledTask),
                Optional.of(scheduledTask), Optional.of(PENDING), Optional.absent());
    }
}