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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the difference of two sets.

Usage

From source file:com.groupon.mesos.zookeeper.ZookeeperMasterDetector.java

@Subscribe
public void processMasterUpdate(final MasterUpdateMessage message) {
    final Set<String> currentNodes = message.getNodes();
    final Set<String> nodesToRemove = ImmutableSet.copyOf(Sets.difference(nodeCache.keySet(), currentNodes));
    final Set<String> nodesToAdd = ImmutableSet.copyOf(Sets.difference(currentNodes, nodeCache.keySet()));

    for (final String node : nodesToAdd) {
        final String path = zookeeperPath + "/" + node;
        final MasterInfo masterInfo = client.readData(path);
        nodeCache.put(node, masterInfo);
    }/*from w w w  . j ava 2 s  .  c  om*/

    for (final String node : nodesToRemove) {
        nodeCache.remove(node);
    }

    LOG.debug("Processed event, active nodes are %s", nodeCache.entrySet());

    final MasterInfo masterInfo = getMaster();

    if (masterInfo == null) {
        LOG.debug("No current master exists!");
    } else {
        LOG.debug("Current master is %s", UPID.create(masterInfo.getPid()).asString());
    }

    final List<DetectMessage> detectMessages = new ArrayList<>(futures.size());
    futures.drainTo(detectMessages);

    for (final DetectMessage detectMessage : detectMessages) {
        processDetect(detectMessage);
    }
}

From source file:grakn.core.graql.reasoner.cache.SemanticDifference.java

/**
 * @param answer to project/*from w  ww  . jav a  2s . c o m*/
 * @param partialSub partial child substitution that needs to be incorporated
 * @param vars       child vars
 * @param unifier    parent-child unifier
 * @return projected answer (empty if semantic difference not satisfied)
 */
@CheckReturnValue
public ConceptMap applyToAnswer(ConceptMap answer, ConceptMap partialSub, Set<Variable> vars, Unifier unifier) {
    ConceptMap unified = unifier.apply(answer);
    if (unified.isEmpty())
        return unified;
    Set<Variable> varsToRetain = Sets.difference(unified.vars(), partialSub.vars());
    return !this.satisfiedBy(unified) ? new ConceptMap()
            : ConceptUtils.mergeAnswers(unified.project(varsToRetain), partialSub).project(vars);
}

From source file:com.google.javascript.jscomp.RandomNameGenerator.java

@Override
public void reset(Set<String> reservedNames, String prefix, @Nullable char[] reservedFirstCharacters,
        @Nullable char[] reservedNonFirstCharacters) {
    this.reservedNames = ImmutableSet.copyOf(reservedNames);
    this.prefix = prefix;
    nameCount = 0;//from  ww  w. ja va 2  s .c o m

    // Build the character arrays to use
    firstChars = Sets.difference(FIRST_CHAR, asSet(reservedFirstCharacters)).immutableCopy();
    nonFirstChars = Sets.difference(NONFIRST_CHAR, asSet(reservedNonFirstCharacters)).immutableCopy();

    checkPrefix(prefix);
    shuffleAlphabets();
}

From source file:co.mitro.core.servlets.MutateOrganization.java

@Override
protected MitroRPC processCommand(MitroRequestContext context)
        throws IOException, SQLException, MitroServletException {
    try {/*from   w  w w.  java  2  s  .  c om*/
        RPC.MutateOrganizationRequest in = gson.fromJson(context.jsonRequest,
                RPC.MutateOrganizationRequest.class);

        in.promotedMemberEncryptedKeys = MitroServlet.createMapIfNull(in.promotedMemberEncryptedKeys);
        in.newMemberGroupKeys = MitroServlet.createMapIfNull(in.newMemberGroupKeys);
        in.adminsToDemote = MitroServlet.uniquifyCollection(in.adminsToDemote);
        in.membersToRemove = MitroServlet.uniquifyCollection(in.membersToRemove);

        @SuppressWarnings("deprecation")
        AuthenticatedDB userDb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor);
        DBGroup org = userDb.getOrganizationAsAdmin(in.orgId);

        Set<String> adminsToDemote = Sets.newHashSet(in.adminsToDemote);
        Collection<DBAcl> aclsToRemove = new HashSet<>();
        Set<Integer> existingAdmins = new HashSet<>();
        for (DBAcl acl : org.getAcls()) {
            DBIdentity u = acl.loadMemberIdentity(context.manager.identityDao);
            assert (u != null); // toplevel groups should not have group members.
            if (adminsToDemote.contains(u.getName())) {
                aclsToRemove.add(acl);
                adminsToDemote.remove(u.getName());
            } else {
                existingAdmins.add(u.getId());
            }
        }
        // check for an attempt to promote members who are already admins.
        Set<Integer> duplicateAdmins = Sets.intersection(existingAdmins,
                DBIdentity.getUserIdsFromNames(context.manager, in.promotedMemberEncryptedKeys.keySet()));
        if (!duplicateAdmins.isEmpty()) {
            throw new MitroServletException(
                    "Operation would create duplicate admins: " + COMMA_JOINER.join(duplicateAdmins));
        }

        if (!adminsToDemote.isEmpty()) {
            throw new MitroServletException("The following users are not admins and could not be deleted:"
                    + COMMA_JOINER.join(adminsToDemote));
        }
        if (existingAdmins.isEmpty() && in.promotedMemberEncryptedKeys.isEmpty()) {
            throw new UserVisibleException("You cannot remove all admins from an organization");
        }

        // delete ACLs for the admin user on the group. This maybe should be using common code?
        context.manager.aclDao.delete(aclsToRemove);
        Map<Integer, Integer> currentMemberIdsToGroupIds = getMemberIdsAndPrivateGroupIdsForOrg(context.manager,
                org);

        // Promoted members (new admins) must be members after all changes
        Set<String> currentMembers = DBIdentity.getUserNamesFromIds(context.manager,
                currentMemberIdsToGroupIds.keySet());
        Set<String> membersAfterChanges = Sets.difference(
                Sets.union(currentMembers, in.newMemberGroupKeys.keySet()), new HashSet<>(in.membersToRemove));
        Set<String> nonMemberAdmins = Sets.difference(in.promotedMemberEncryptedKeys.keySet(),
                membersAfterChanges);
        if (!nonMemberAdmins.isEmpty()) {
            throw new MitroServletException(
                    "Cannot add admins without them being members: " + COMMA_JOINER.join(nonMemberAdmins));
        }

        // check for duplicate users
        Set<Integer> duplicateMembers = Sets.intersection(currentMemberIdsToGroupIds.keySet(),
                DBIdentity.getUserIdsFromNames(context.manager, in.newMemberGroupKeys.keySet()));
        if (!duplicateMembers.isEmpty()) {
            throw new MitroServletException(
                    "Operation would create duplicate members: " + COMMA_JOINER.join(duplicateMembers));
        }

        // delete all the private groups. This might orphan secrets, which is the intended result.
        Set<Integer> memberIdsToRemove = DBIdentity.getUserIdsFromNames(context.manager, in.membersToRemove);
        if (memberIdsToRemove.size() != in.membersToRemove.size()) {
            throw new MitroServletException("Invalid members to remove.");
        }

        Set<Integer> illegalRemovals = Sets.intersection(existingAdmins, memberIdsToRemove);
        if (!illegalRemovals.isEmpty()) {
            throw new MitroServletException(
                    "Cannot remove members who are admins:" + COMMA_JOINER.join(illegalRemovals));
        }
        Set<Integer> nonOrgUsers = Sets.difference(memberIdsToRemove, currentMemberIdsToGroupIds.keySet());
        if (!nonOrgUsers.isEmpty()) {
            throw new MitroServletException("The following users are not members and cannot be removed:"
                    + COMMA_JOINER.join(nonOrgUsers));
        }
        Set<Integer> deleteGroupIds = Sets.newHashSet(
                Maps.filterKeys(currentMemberIdsToGroupIds, Predicates.in(memberIdsToRemove)).values());
        if (!deleteGroupIds.isEmpty()) {
            context.manager.groupDao.deleteIds(deleteGroupIds);
            DeleteBuilder<DBAcl, Integer> deleter = context.manager.aclDao.deleteBuilder();
            deleter.where().in(DBAcl.GROUP_ID_FIELD_NAME, deleteGroupIds);
            deleter.delete();

            DeleteBuilder<DBGroupSecret, Integer> gsDeleter = context.manager.groupSecretDao.deleteBuilder();
            gsDeleter.where().in(DBGroupSecret.GROUP_ID_NAME, deleteGroupIds);
            gsDeleter.delete();
        }

        // Remove the user from all org-owned group to which he belongs.
        // Note: if the user has access to an org-owned secret via a non-org-owned group, 
        // he will retain access. 
        Set<Integer> allOrgGroupIds = Sets.newHashSet();
        for (DBGroup g : org.getAllOrgGroups(context.manager)) {
            allOrgGroupIds.add(g.getId());
        }
        if (!memberIdsToRemove.isEmpty()) {
            if (!allOrgGroupIds.isEmpty()) {
                // Remove users from organization-owned groups (named or otherwise)
                DeleteBuilder<DBAcl, Integer> deleter = context.manager.aclDao.deleteBuilder();
                deleter.where().in(DBAcl.MEMBER_IDENTITY_FIELD_NAME, memberIdsToRemove).and()
                        .in(DBAcl.GROUP_ID_FIELD_NAME, allOrgGroupIds);
                deleter.delete();
            }

            // Remove users from any org-owned secrets (e.g. via non-org private or named groups)
            HashMap<Integer, SecretToPath> orgSecretsToPath = new HashMap<>();
            ListMySecretsAndGroupKeys.getSecretInfo(context, AdminAccess.FORCE_ACCESS_VIA_TOPLEVEL_GROUPS,
                    orgSecretsToPath, ImmutableSet.of(org.getId()), null,
                    IncludeAuditLogInfo.NO_AUDIT_LOG_INFO);
            if (orgSecretsToPath.size() > 0) {
                // Delete any group secret giving these users access to org secrets
                // strange side effect: personal teams may be mysteriously removed from org secrets
                // TODO: Potential bug: removing the last personal team will "orphan" the secret
                String groupSecretDelete = String.format(
                        "DELETE FROM group_secret WHERE id IN ("
                                + "SELECT group_secret.id FROM group_secret, acl WHERE "
                                + "  group_secret.\"serverVisibleSecret_id\" IN (%s) AND "
                                + "  group_secret.group_id = acl.group_id AND acl.member_identity IN (%s))",
                        COMMA_JOINER.join(orgSecretsToPath.keySet()), COMMA_JOINER.join(memberIdsToRemove));
                context.manager.groupSecretDao.executeRaw(groupSecretDelete);
            }
        }

        List<DBAcl> organizationAcls = CreateOrganization.makeAdminAclsForOrganization(userDb, org,
                in.promotedMemberEncryptedKeys);

        // TODO: move to authdb?
        for (DBAcl acl : organizationAcls) {
            context.manager.aclDao.create(acl);
        }

        // create private groups for each new member
        CreateOrganization.addMembersToOrganization(userDb, org, in.newMemberGroupKeys, context.manager);

        context.manager.addAuditLog(DBAudit.ACTION.MUTATE_ORGANIZATION, null, null, org, null, "");

        MutateOrganizationResponse out = new RPC.MutateOrganizationResponse();
        // TODO: validate the group?
        return out;

    } catch (CyclicGroupError e) {
        throw new MitroServletException(e);
    }
}

From source file:com.google.devtools.build.lib.packages.EnvironmentGroup.java

/**
 * Checks that all environments declared by this group are in the same package as the group (so
 * we can perform an environment --> environment_group lookup and know the package is available)
 * and checks that all defaults are legitimate members of the group.
 *
 * <p>Does <b>not</b> check that the referenced environments exist (see
 * {@link #processMemberEnvironments}).//  w ww  .j  a v  a 2s  . co m
 *
 * @return a list of validation errors that occurred
 */
List<Event> validateMembership() {
    List<Event> events = new ArrayList<>();

    // All environments should belong to the same package as this group.
    for (Label environment : Iterables.filter(environments, new DifferentPackage(containingPackage))) {
        events.add(Event.error(location, environment + " is not in the same package as group " + label));
    }

    // The defaults must be a subset of the member environments.
    for (Label unknownDefault : Sets.difference(defaults, environments)) {
        events.add(Event.error(location,
                "default " + unknownDefault + " is not a " + "declared environment for group " + getLabel()));
    }

    return events;
}

From source file:com.b2international.snowowl.snomed.datastore.RefSetMemberRedundancyAnalyzer.java

/**
 * Returns with a {@link ReferencedComponentIdSet a set of redundant and non-redundant member IDs} based on the specified SNOMED CT 
 * reference set and the terminology independent component identifier.
 * <br><br><b>Note: </b>this method does nothing but returns with the specified <b>componentIds</b> wrapped to a {@link ReferencedComponentIdSet} instance
 * since redundancy based on the referenced components is not available for SNOMED CT {@link SnomedRefSetType#SIMPLE_MAP simple map} type and 
 * SNOMED CT {@link SnomedRefSetType#COMPLEX_MAP complex map} type reference sets. This method throws IllegalStateException if the specified SNOMED CT
 * reference set is a {@link SnomedRefSetType#QUERY query type} reference set.
 * @param refSet the reference where the member redundancy analysis should be performed.
 * @param monitor the progress monitor for the process. Can be {@code null}. If {@code null} a new {@link NullProgressMonitor} will be instantiated.
 * @param componentIds the terminology independent component identifiers.
 * @return the {@link ReferencedComponentIdSet} wrapping the redundant and non-redundant reference set member IDs.
 *///from  ww w  .  j a  va2s  .  com
public static ReferencedComponentIdSet analyzeMemberRedundancy(@Nonnull final SnomedRegularRefSet refSet,
        @Nullable IProgressMonitor monitor, final Iterable<String> componentIds) {
    checkNotNull(refSet, "SNOMED CT reference set argument cannot be null.");
    checkNotNull(refSet.getIdentifierId(), "The identifier SNOMED CT concept ID cannot be null.");
    checkState(!StringUtils.isEmpty(refSet.getIdentifierId()),
            "The identifier SNOMED CT concept ID cannot be empty.");
    checkState(!QUERY.equals(refSet.getType()), "SNOMED CT query type reference set is not supported.");

    if (null == monitor)
        monitor = new NullProgressMonitor();

    monitor.beginTask("Analyzing reference set member redundancy...", IProgressMonitor.UNKNOWN);

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    //no member redundancy check is required for either SNOMED CT simple map type or SNOMED CT complex map type reference sets.
    if (SnomedRefSetUtil.isMapping(refSet.getType())) {
        return ReferencedComponentIdSet.createWithoutRedundantMembers(componentIds);
    }

    //get all persisted members and extract the unique component identifiers of the referenced components 
    final Set<String> persistedIds = ImmutableSet.copyOf(getPersistedReferencedComponentIds(refSet));

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    //need to update persisted IDs with the changes made on the underlying transaction.
    final CDOView view = refSet.cdoView();

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    //we need to delete the detached IDs from persisted IDs
    persistedIds.removeAll(Sets
            .newHashSet(Collections2.transform(getDetachedMembers(view), MEMBER_TO_REFERENCED_COMPONENT_ID)));

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    //wee need to add the new IDs to the persisted IDs
    persistedIds.addAll(
            Sets.newHashSet(Collections2.transform(getNewMembers(view), MEMBER_TO_REFERENCED_COMPONENT_ID)));

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    //after we have the most up-to-date referenced component IDs we should create the return value based on the specified component IDs argument
    final Set<String> allComponentIds = Sets.newHashSet(componentIds);
    final Set<String> nonRedundantMembers = Sets.difference(allComponentIds, persistedIds);

    if (monitor.isCanceled()) {
        monitor.setCanceled(true);
        return ReferencedComponentIdSet.NULL_IMPL;
    }

    final Set<String> redundantMembers = Sets.newHashSet(componentIds);
    redundantMembers.removeAll(nonRedundantMembers);

    return new ReferencedComponentIdSet(redundantMembers, nonRedundantMembers);
}

From source file:org.jboss.pnc.rest.provider.ProductVersionProvider.java

public ProductVersion updateBuildConfigurationSets(Integer id,
        List<BuildConfigurationSetRest> buildConfigurationSetsToAdd) throws RestValidationException {
    if (buildConfigurationSetsToAdd == null) {
        throw new InvalidEntityException("No BuildConfigurationSets supplied");
    }// ww  w  . ja  v a  2s. c o m

    ProductVersion productVersion = repository.queryById(id);
    List<BuildConfigurationSet> buildConfigurationSets = buildConfigurationSetRepository
            .withProductVersionId(productVersion.getId());

    if (logger.isTraceEnabled()) {
        logger.trace("Retrieved ProductVersion: {}; Retrieved BuildConfigurationSets: {}", productVersion,
                buildConfigurationSets.stream().map(bcs -> bcs.getId().toString())
                        .collect(Collectors.joining()));
    }

    Set<BuildConfigurationSet> addedBCSets = new HashSet<>();

    for (BuildConfigurationSetRest configurationSetToAdd : buildConfigurationSetsToAdd) {
        BuildConfigurationSet buildConfigurationSet = buildConfigurationSetRepository
                .queryById(configurationSetToAdd.getId());
        logger.trace("Validating buildConfigurationSet: {}", buildConfigurationSet);

        if (buildConfigurationSet == null) {
            throw new InvalidEntityException("Invalid BuildConfigurationSet");
        }

        if (buildConfigurationSet.getProductVersion() != null
                && !buildConfigurationSet.getProductVersion().getId().equals(productVersion.getId())) {
            throw new ConflictedEntryException(
                    format("BuildConfigurationSet: '%s' is already associated with a different Product Version",
                            buildConfigurationSet.getName()),
                    BuildConfigurationSet.class, buildConfigurationSet.getId());
        }

        addedBCSets.add(buildConfigurationSet);
    }

    Set<BuildConfigurationSet> removedBCSets = Sets.difference(new HashSet<>(buildConfigurationSets),
            addedBCSets);

    productVersion.setBuildConfigurationSets(addedBCSets);
    validateBeforeUpdating(id, new ProductVersionRest(productVersion));
    if (logger.isTraceEnabled()) {
        logger.trace("About to remove BCSets from productVersion: {}",
                removedBCSets.stream().map(set -> set.getId().toString()).collect(Collectors.joining()));
    }
    removedBCSets.forEach(removed -> {
        removed.setProductVersion(null);
        buildConfigurationSetRepository.save(removed);
    });
    if (logger.isTraceEnabled()) {
        logger.trace("About to add BCSets to productVersion: {}",
                addedBCSets.stream().map(set -> set.getId().toString()).collect(Collectors.joining()));
    }
    addedBCSets.forEach(added -> {
        added.setProductVersion(productVersion);
        productVersion.getBuildConfigurationSets().add(added);
        buildConfigurationSetRepository.save(added);
    });
    if (logger.isTraceEnabled()) {
        logger.trace("About to save ProductVersion: {}; Contains BuildConfigurationSets: {}", productVersion,
                productVersion.getBuildConfigurationSets().stream().map(bcs -> bcs.getId().toString())
                        .collect(Collectors.joining()));
    }
    return repository.save(productVersion);
}

From source file:org.apache.cassandra.contrib.circuit.CircuitFrame.java

/**
 * For each node, retrieve that nodes list and compare it to ours. If the
 * list of remote nodes doesn't match (it's long or short), then the node is
 * flagged accordingly and an error message is written to the status display.
 *//*  w w  w  .ja  v  a 2s . c o m*/
private void verifyRing() {
    new Thread("VERIFY-RING") {
        public void run() {
            verifyLock.lock();
            ringPanel.setVerifying(true);
            try {
                writeStatusOutput("Beginning ring verification...");
                for (Node node : ringModel.getNodes()) {
                    // Skip the node we already queried at startup
                    if (node.isSeed())
                        continue;

                    writeStatusOutput("Verifying %s (ring) against reference node", node);
                    node.setSelected(true);

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            ringPanel.repaint();
                        }
                    });

                    // uncomment this to simulate a slow running verification process
                    //                        try {Thread.currentThread().sleep(2000L); } catch (Exception ex) { }

                    Set<Node> othersSet, nodesSet;
                    try {
                        othersSet = new HashSet<Node>(ringModel.getRemoteNodes(node.getHost()));
                    } catch (IOException e) {
                        e.printStackTrace();
                        writeStatusOutput("Error retrieving node list from %s", node.getHost());
                        continue;
                    }

                    nodesSet = new HashSet<Node>(ringModel.getNodes());

                    for (Node upShort : Sets.difference(nodesSet, othersSet)) {
                        node.setStatus(NodeStatus.SHORT);
                        writeStatusOutput("%s: missing node %s", node, upShort);
                    }

                    for (Node upLong : Sets.difference(othersSet, nodesSet)) {
                        node.setStatus(NodeStatus.LONG);
                        writeStatusOutput("%s: contains node %s missing from reference list", node, upLong);
                    }

                    node.setSelected(false);
                }

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        ringPanel.repaint();
                    }
                });
                writeStatusOutput("Ring verification complete.");
            } finally {
                verifyLock.unlock();
                ringPanel.setVerifying(false);
            }
        }
    }.start();
}

From source file:com.squareup.wire.schema.IdentifierSet.java

public Set<String> unusedExcludes() {
    return Sets.difference(excludes, usedExcludes);
}