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.continuuity.loom.layout.NodeLayoutGenerator.java

private static boolean satisfiesMustCoexist(Set<String> serviceSet, LayoutConstraint layoutConstraint,
        Set<String> clusterServices) {
    // if the service set contains at least one service in a must coexist constraint, but not all clusterServices in the
    // constraint, then it is invalid.  Ignore clusterServices that are not on the cluster.
    for (Set<String> mustCoexist : layoutConstraint.getServicesThatMustCoexist()) {
        Set<String> trueMustCoexist = Sets.intersection(mustCoexist, clusterServices);
        if (containsOne(serviceSet, trueMustCoexist) && !serviceSet.containsAll(trueMustCoexist)) {
            return false;
        }//from   www .  ja va 2  s  . c o  m
    }
    return true;
}

From source file:gobblin.metastore.DatabaseJobHistoryStore.java

private static VersionedDatabaseJobHistoryStore findVersionedDatabaseJobHistoryStore(
        MigrationVersion requiredVersion)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    Class<?> foundClazz = null;
    Class<?> defaultClazz = null;
    MigrationVersion defaultVersion = MigrationVersion.EMPTY;
    // Scan all packages
    Reflections reflections = new Reflections("gobblin.metastore.database",
            effectiveClassPathUrls(DatabaseJobHistoryStore.class.getClassLoader()));
    for (Class<?> clazz : Sets.intersection(reflections.getTypesAnnotatedWith(SupportedDatabaseVersion.class),
            reflections.getSubTypesOf(VersionedDatabaseJobHistoryStore.class))) {
        SupportedDatabaseVersion annotation = clazz.getAnnotation(SupportedDatabaseVersion.class);
        String version = annotation.version();
        MigrationVersion actualVersion = MigrationVersion
                .fromVersion(Strings.isNullOrEmpty(version) ? null : version);
        if (annotation.isDefault() && actualVersion.compareTo(defaultVersion) > 0) {
            defaultClazz = clazz;/*from   w w  w  .  j a  v a2 s  .  co m*/
            defaultVersion = actualVersion;
        }
        if (actualVersion.compareTo(requiredVersion) == 0) {
            foundClazz = clazz;
        }
    }
    if (foundClazz == null) {
        foundClazz = defaultClazz;
    }
    if (foundClazz == null) {
        throw new ClassNotFoundException(
                String.format("Could not find an instance of %s which supports database " + "version %s.",
                        VersionedDatabaseJobHistoryStore.class.getSimpleName(), requiredVersion.toString()));
    }
    return (VersionedDatabaseJobHistoryStore) foundClazz.newInstance();
}

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

public static GetOrganizationStateResponse doOperation(MitroRequestContext context, int orgId)
        throws MitroServletException, SQLException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    GetOrganizationStateResponse out = new GetOrganizationStateResponse();

    @SuppressWarnings("deprecation")
    AuthenticatedDB userDb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor);
    DBGroup org = userDb.getOrganizationAsMember(orgId);
    assert (null != org);

    Set<String> users = Sets.newHashSet();
    Set<Integer> groupIds = ListMySecretsAndGroupKeys.getGroupsUsersAndOrgsFromRawStatement(context, null,
            org.getId(), out.groups, out.organizations, null, users);

    // prevent users who are memebers of org groups but not members of the org from being returned as members.
    Set<String> orgMembers = DBIdentity.getUserNamesFromIds(context.manager,
            MutateOrganization.getMemberIdsAndPrivateGroupIdsForOrg(context.manager, org).keySet());
    out.members = Lists.newArrayList(Sets.intersection(orgMembers, users));

    Set<Integer> orgAdmins = Sets.newHashSet();
    org.putDirectUsersIntoSet(orgAdmins, DBAcl.adminAccess());
    out.admins = Lists.newArrayList(DBIdentity.getUserNamesFromIds(context.manager, orgAdmins));

    // all users get a list of THEIR secrets
    if (userDb.isOrganizationAdmin(orgId)) {
        // if user is admin: get list of secrets
        // TODO: audit log is super slow; this should move to its own API call?
        final IncludeAuditLogInfo GET_AUDIT = IncludeAuditLogInfo.NO_AUDIT_LOG_INFO;
        groupIds.add(org.getId());/*from w  w  w  .ja  v  a2s .com*/
        ListMySecretsAndGroupKeys.getSecretInfo(context, AdminAccess.FORCE_ACCESS_VIA_TOPLEVEL_GROUPS,
                out.orgSecretsToPath, groupIds, null, GET_AUDIT);

        // any org secrets with no users, no hidden groups and only the org group are orphaned.
        out.orphanedSecretsToPath = Maps.newHashMap();
        for (Iterator<Entry<Integer, SecretToPath>> iter = out.orgSecretsToPath.entrySet().iterator(); iter
                .hasNext();) {
            Entry<Integer, SecretToPath> entry = iter.next();
            SecretToPath stp = entry.getValue();
            if (stp.users.isEmpty() && stp.hiddenGroups.isEmpty() && stp.groups.size() == 1) {
                // this is an orphaned secret
                assert (stp.groups.get(0) == org.getId());
                out.orphanedSecretsToPath.put(entry.getKey(), entry.getValue());
                // remove orphaned secrets from regular org secrets
                iter.remove();
            }
        }
    } else {
        // these variables are not filled; set to null so the caller doesn't rely on them
        out.orgSecretsToPath = null;
        out.orphanedSecretsToPath = null;
        out.organizations = null;

        // Remove private data from groups: membership; encrypted keys
        for (GroupInfo group : out.groups.values()) {
            group.users = null;
            group.encryptedPrivateKey = null;
        }
    }

    logger.info("{} elapsed: {} ms:", context.requestor, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    return out;
}

From source file:pl.edu.icm.cermine.metadata.extraction.enhancers.DescriptionEnhancer.java

@Override
protected boolean enhanceMetadata(BxDocument document, DocumentMetadata metadata) {
    List<BxLine> lines = new ArrayList<BxLine>();
    for (BxPage page : filterPages(document)) {
        for (BxZone zone : filterZones(page)) {
            for (BxLine line : zone) {
                lines.add(line);/*  ww w. ja  v  a 2  s  .co  m*/
            }
        }
    }

    StringBuilder sb = new StringBuilder();
    BxLine prev = null;
    for (BxLine line : lines) {
        String normalized = line.toText().toLowerCase().trim();
        if (normalized.startsWith("abstract") || normalized.startsWith("a b s t r a c t")
                || normalized.startsWith("article info")) {
            sb = new StringBuilder();
        }
        if (normalized.startsWith("keywords") || normalized.startsWith("key words")
                || normalized.equals("introduction") || normalized.startsWith("this work is licensed")
                || (normalized.length() < 20
                        && (normalized.startsWith("introduction") || normalized.endsWith("introduction")))) {
            break;
        }
        if (prev != null && !prev.getParent().equals(line.getParent()) && lines.indexOf(line) > 5
                && prev.toText().endsWith(".") && (Math.abs(prev.getX() - line.getX()) > 5
                        || Sets.intersection(prev.getFontNames(), line.getFontNames()).isEmpty())) {
            break;
        }
        sb.append("\n");
        sb.append(line.toText().trim());
        prev = line;
    }

    String text = sb.toString().trim();
    if (!text.isEmpty()) {
        Matcher matcher = PREFIX.matcher(text);
        if (matcher.find()) {
            text = text.substring(matcher.end()).trim();
        }
        metadata.setAbstrakt(text);
        return true;
    }
    return false;
}

From source file:com.google.gerrit.server.schema.Schema_105.java

private Set<String> listChangesIndexes(JdbcSchema schema) throws SQLException {
    // List of all changes indexes ever created or dropped, found with the
    // following command:
    //   find g* -name \*.sql | xargs git log -i -p -S' index changes_' | grep -io ' index changes_\w*' | cut -d' ' -f3 | tr A-Z a-z | sort -u
    // Used rather than listIndexes as we're not sure whether it might include
    // primary key indexes.
    Set<String> allChanges = ImmutableSet.of("changes_allclosed", "changes_allopen", "changes_bybranchclosed",
            "changes_byownerclosed", "changes_byowneropen", "changes_byproject", "changes_byprojectopen",
            "changes_key", "changes_submitted");
    return Sets.intersection(schema.getDialect().listIndexes(schema.getConnection(), TABLE), allChanges);
}

From source file:org.sonatype.nexus.security.user.AbstractUserManager.java

protected boolean matchesCriteria(final String userId, final String userSource,
        final Collection<String> usersRoles, final UserSearchCriteria criteria) {
    if (!Strings2.isBlank(criteria.getUserId())
            && !userId.toLowerCase().startsWith(criteria.getUserId().toLowerCase())) {
        return false;
    }/*from ww w .  j  av  a 2s .c  o  m*/

    if (criteria.getSource() != null && !criteria.getSource().equals(userSource)) {
        return false;
    }

    if (criteria.getOneOfRoleIds() != null && !criteria.getOneOfRoleIds().isEmpty()) {
        Set<String> userRoles = new HashSet<>();
        if (usersRoles != null) {
            userRoles.addAll(usersRoles);
        }

        // check the intersection of the roles
        if (Sets.intersection(criteria.getOneOfRoleIds(), userRoles).isEmpty()) {
            return false;
        }
    }

    return true;
}

From source file:compile.type.visit.SubstMap.java

/**
 * Check for agreement with another map. If maps m1 and m2 agree, there is no
 * LHS v for which m1.contains(v) && m2.contains(v) && m1.get(v) != m2.get(v).
 * An error is raised for each LHS on which maps disagree.
 */// w  w  w.  ja v a 2  s  .c  o  m
public static boolean checkAgreement(final Loc loc, final SubstMap left, final SubstMap right) {
    boolean agrees = true;

    for (final Type type : Sets.intersection(left.keySet(), right.keySet())) {
        final Type leftType = left.get(type);
        final Type rightType = right.get(type);

        if (!leftType.equals(rightType)) {
            // TODO always internal? if not, change message
            Session.error(loc, "internal error: substitution maps disagree: {0} vs. {1}", leftType.dump(),
                    rightType.dump());
            agrees = false;
        }
    }

    return agrees;
}

From source file:org.dllearner.algorithms.schema.SimpleSchemaGenerator.java

@Override
public Set<OWLAxiom> generateSchema() {
    Set<OWLAxiom> generatedAxiomsTotal = new HashSet<>();

    // get the entities
    SortedSet<OWLEntity> entities = getEntities();

    // we repeat the whole process
    for (int i = 0; i < nrOfIterations; i++) {
        LOGGER.trace("Iteration " + (i + 1) + " ...");
        Set<OWLAxiom> generatedAxioms = new HashSet<>();

        // iterate over the entities
        for (OWLEntity entity : entities) {
            // get the applicable axiom types
            SetView<AxiomType<? extends OWLAxiom>> applicableAxiomTypes = Sets
                    .intersection(AxiomAlgorithms.getAxiomTypes(entity.getEntityType()), axiomTypes);

            // iterate over the axiom types
            for (AxiomType<? extends OWLAxiom> axiomType : applicableAxiomTypes) {
                // apply the appropriate learning algorithm
                try {
                    Set<OWLAxiom> axioms = applyLearningAlgorithm(entity, axiomType);
                    generatedAxioms.addAll(axioms);
                } catch (Exception e) {
                    LOGGER.error("Exception occured for axiom type " + axiomType.getName() + " and entity "
                            + entity + ".", e);
                    //TODO handle exception despite logging
                }//from   w w w .  jav  a 2s.  co m
            }
        }

        // add the generated axioms to the knowledge base
        addToKnowledgebase(generatedAxioms);

        // new axioms
        SetView<OWLAxiom> newAxioms = Sets.difference(generatedAxioms, generatedAxiomsTotal);

        LOGGER.trace(newAxioms.isEmpty() ? "Got no new axioms." : ("Got " + newAxioms.size() + " new axioms:"));
        if (newAxioms.isEmpty()) { // terminate if iteration lead to no new axioms
            if ((i + 1) < nrOfIterations)
                LOGGER.trace("Early termination. Ignoring further iterations.");
            break;
        }
        LOGGER.trace(newAxioms.toString());

        // add to total set
        generatedAxiomsTotal.addAll(generatedAxioms);
    }
    return generatedAxiomsTotal;
}

From source file:org.apache.rya.indexing.external.matching.FlattenedOptional.java

public FlattenedOptional(LeftJoin node) {
    rightArgs = getJoinArgs(node.getRightArg(), new HashSet<TupleExpr>());
    boundVars = setWithOutConstants(Sets.intersection(node.getLeftArg().getAssuredBindingNames(),
            node.getRightArg().getBindingNames()));
    unboundVars = setWithOutConstants(Sets.difference(node.getRightArg().getBindingNames(), boundVars));
    condition = node.getCondition();// w  w w. j a v  a 2s  .  c  o  m
    rightArg = node.getRightArg();
    getVarCounts(node);
    assuredBindingNames = new HashSet<>(leftArgVarCounts.keySet());
    bindingNames = new HashSet<>(Sets.union(assuredBindingNames, unboundVars));
}

From source file:com.visural.stereotyped.ui.Privilege.java

public static IPrivilege currentUserHasReadAccess(final UUID id) {
    return new IPrivilege() {

        public boolean isGrantedToClient(IClient arg0) {
            StereotypeUIMetaData meta = ServiceProvider.getServiceInstance(StereotypeService.class)
                    .readUIMeta(id);// www.  ja v  a2 s  . c o  m
            User u = (User) arg0;
            return ADMINISTRATOR.isGrantedToClient(arg0) || meta.getOwner().equals(u.getId())
                    || meta.getViewUsers().contains(u.getId()) || meta.getEditUsers().contains(u.getId())
                    || !Sets.intersection(meta.getEditGroups(), u.getGroups()).isEmpty()
                    || !Sets.intersection(meta.getViewGroups(), u.getGroups()).isEmpty();
        }

    };
}