Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:org.openmrs.cohort.CohortSearchHistory.java

public Cohort getPatientSetCombineWithAnd(EvaluationContext context) {
    Set<Integer> current = null;
    for (int i = 0; i < searchHistory.size(); ++i) {
        Cohort ps = getPatientSet(i, context);
        if (current == null)
            current = new HashSet<Integer>(ps.getMemberIds());
        else/*from w  ww. j  av a 2 s.  co m*/
            current.retainAll(ps.getMemberIds());
    }
    if (current == null)
        return Context.getPatientSetService().getAllPatients();
    else {
        return new Cohort("Cohort anded together", "", current);
    }
}

From source file:com.datatorrent.contrib.dimensions.DimensionsQueryExecutor.java

private void applyRolling(List<Map<String, EventKey>> keysEventKeys, List<Map<String, GPOMutable>> keys,
        List<Map<String, GPOMutable>> results, List<Map<String, GPOMutable>> rolledKeys,
        List<Map<String, GPOMutable>> rolledResults, DimensionalConfigurationSchema configurationSchema,
        DataQueryDimensional query) {/*from w ww . jav a2 s . c o m*/
    for (int offset = 0; offset < keys.size() - (query.getSlidingAggregateSize() - 1); offset++) {
        int index = offset + (query.getSlidingAggregateSize() - 1);
        Map<String, EventKey> bucketKeysEventKeys = keysEventKeys.get(index);
        Map<String, GPOMutable> bucketKeys = keys.get(index);

        Set<String> aggregators = Sets.newHashSet(bucketKeys.keySet());
        for (int rollingIndex = 0; rollingIndex < query.getSlidingAggregateSize(); rollingIndex++) {
            //Get aggregators for rolling bucket
            Map<String, GPOMutable> key = keys.get(offset + rollingIndex);
            aggregators.retainAll(key.keySet());
        }

        Set<String> unNeededAggregators = Sets.newHashSet(bucketKeys.keySet());
        unNeededAggregators.removeAll(aggregators);

        for (String unNeededAggregator : unNeededAggregators) {
            bucketKeys.remove(unNeededAggregator);
        }

        Map<String, GPOMutable> result = Maps.newHashMap();

        if (!aggregators.isEmpty()) {
            for (int rollingIndex = 0; rollingIndex < query.getSlidingAggregateSize(); rollingIndex++) {
                Map<String, GPOMutable> currentResult = results.get(offset + rollingIndex);
                for (String aggregator : aggregators) {
                    IncrementalAggregator incrementalAggregator = configurationSchema.getAggregatorRegistry()
                            .getNameToIncrementalAggregator().get(aggregator);
                    GPOMutable aggregate = result.get(aggregator);
                    GPOMutable currentAggregate = currentResult.get(aggregator);
                    EventKey currentEventKey = bucketKeysEventKeys.get(aggregator);

                    if (aggregate == null) {
                        result.put(aggregator, currentAggregate);
                    } else {
                        incrementalAggregator.aggregate(new Aggregate(currentEventKey, aggregate),
                                new Aggregate(currentEventKey, currentAggregate));
                    }
                }
            }
        }

        rolledKeys.add(bucketKeys);
        rolledResults.add(result);
    }
}

From source file:org.entrystore.repository.impl.PrincipalManagerImpl.java

protected boolean hasAccess(User currentUser, Entry entry, AccessProperty prop) {
    Set<URI> principals = entry.getAllowedPrincipalsFor(prop);
    if (!principals.isEmpty()) {

        //Check if guest is in principals.
        if (principals.contains(getGuestUser().getURI())) {
            return true;
        }/*from  w  ww . j a v a2 s  .  com*/

        //Check if the special "user" group is in principals and user is not guest.
        if (currentUser != getGuestUser() && principals.contains(getUserGroup().getURI())) {
            return true;
        }

        //Check if user is in principals.
        if (principals.contains(currentUser.getURI())) {
            return true;
        }

        //Check if any of the groups the user belongs to is in principals
        Set<URI> groups = getGroupUris(currentUser.getURI());
        groups.retainAll(principals);
        if (!groups.isEmpty()) {
            return true;
        }
    }

    if (prop != AccessProperty.Administer) {
        principals = entry.getAllowedPrincipalsFor(AccessProperty.Administer);
        if (!principals.isEmpty()) {

            //Check if user is in principals.
            if (principals.contains(currentUser.getURI())) {
                return true;
            }

            //Check if any of the groups the user belongs to is in principals
            Set<URI> groups = getGroupUris(currentUser.getURI());
            groups.retainAll(principals);
            if (!groups.isEmpty()) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.ist.p2pbay.manager.SearchManager.java

public String[] getMatchingItems(String[] keywords, Character operation) {
    Set<String> resultSet = new HashSet<String>();
    if (keywords != null && keywords.length > 0) {
        for (int i = 0; i < keywords.length; i++) {
            Set result1;
            Set result2;//w  ww. ja va2 s  .  co  m

            if (i == 0) {
                result1 = new HashSet(Arrays.asList(getMatchingItems(keywords[i])));
                result2 = new HashSet(Arrays.asList(getMatchingItems(keywords[i + 1])));
                i++;
            } else {
                result1 = resultSet;
                result2 = new HashSet(Arrays.asList(getMatchingItems(keywords[i])));
            }
            switch (operation) {
            case Constants.AND_OPERATION:
                result1.retainAll(result2);
                resultSet = result1;
                break;

            case Constants.OR_OPERATION:
                result1.addAll(result2);
                resultSet = result1;
                break;
            }

        }
    }
    return (String[]) resultSet.toArray(new String[resultSet.size()]);
}

From source file:org.openlmis.fulfillment.service.request.RequestParametersTest.java

@Test
public void shouldSplit() {
    RequestParameters params = RequestParameters.init().set(KEY,
            range(0, 10).mapToObj(String::valueOf).collect(toList()));

    Pair<RequestParameters, RequestParameters> split = params.split();

    assertThat(split.getLeft(), is(notNullValue()));
    assertThat(split.getRight(), is(notNullValue()));

    Set<Object> values0 = new HashSet<>();
    Set<Object> values1 = new HashSet<>();

    split.getLeft().forEach(entry -> {
        assertThat(entry.getKey(), is(KEY));
        values0.addAll(entry.getValue());
    });/*w  ww.j a  va  2s  . c om*/

    split.getRight().forEach(entry -> {
        assertThat(entry.getKey(), is(KEY));
        values1.addAll(entry.getValue());
    });

    assertThat(values0, hasSize(5));
    assertThat(values1, hasSize(5));

    // the values0 will contain only values that are in the values1.
    values0.retainAll(values1);

    assertThat(values0, hasSize(0));
}

From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.errormining.SpellingErrorFilter.java

private boolean isRelated(Entity e1, Entity e2) throws LexicalSemanticResourceException {
    Set<String> lexemes2 = e2.getLexemes();

    String lexeme = e1.getFirstLexeme();
    PoS pos = e1.getPos();//from   w w  w  .  j a va 2  s. c om
    String sense = e1.getSense(lexeme);

    for (LexicalRelation relation : LexicalRelation.values()) {
        Set<String> relatedLexemes = lsr.getRelatedLexemes(lexeme, pos, sense, relation);
        relatedLexemes.retainAll(lexemes2);

        if (relatedLexemes.size() > 0) {
            return true;
        }
    }

    for (SemanticRelation relation : SemanticRelation.values()) {
        Set<Entity> relatedEntities = lsr.getRelatedEntities(e1, relation);

        if (relatedEntities.contains(e2)) {
            return true;
        }
    }

    return false;
}

From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.nodeService.NodeServiceImpl.java

public void updateProperties(NodeRef nodeRef, Collection<QName> changes) {
    String type_name = nodeService.getType(nodeRef).getLocalName();
    List<String> sqlQueries = new ArrayList<String>();

    List<QName> parentNames = nodeHelper.getParentAndSelfQNames(nodeRef);
    Map<QName, Serializable> nodeProperties = nodeService.getProperties(nodeRef);

    for (QName type_qname : parentNames) {
        type_name = type_qname.getLocalName();

        String simplified_type_name = databaseDictionary.resolveClassAsTableName(type_name);
        Serializable dbid = getDbId(nodeRef);

        TypeDefinition currentTypeDefinition = dictionaryService.getType(type_qname);
        Map<QName, PropertyDefinition> currentTypeProperties = new HashMap<QName, PropertyDefinition>();
        currentTypeProperties.putAll(currentTypeDefinition.getProperties());
        for (AspectDefinition ad : currentTypeDefinition.getDefaultAspects()) {
            currentTypeProperties.putAll(ad.getProperties());
        }//from   w  w  w .j  av a2  s  . c  o m

        Set<QName> iterablePropertiesKeySet = new HashSet<QName>(changes);
        Set<QName> currentTypePropertiesKeySet = currentTypeProperties.keySet();
        iterablePropertiesKeySet.retainAll(currentTypePropertiesKeySet);
        // Remove intrinsic properties
        iterablePropertiesKeySet.remove(ContentModel.PROP_NODE_DBID);
        iterablePropertiesKeySet.remove(ContentModel.PROP_NODE_UUID);

        for (QName key : iterablePropertiesKeySet) {
            Serializable property = nodeProperties.get(key);
            PropertyDefinition propertyDefinition = dictionaryService.getProperty(key);
            String value = getSQLFormatFromSerializable(property, propertyDefinition);

            String originalName = key.getLocalName();
            String resolvedColumnName = databaseDictionary.resolveAttributeAsColumnName(originalName,
                    type_name);

            String sql_query = String.format("UPDATE %1$s SET %2$s = %3$s WHERE id = %4$s",
                    simplified_type_name, (resolvedColumnName != null ? resolvedColumnName : originalName),
                    value, dbid);
            sqlQueries.add(sql_query);
        }
    }

    executeSQLQuery(sqlQueries);

    invokeOnUpdateProperties(nodeRef, changes);
}

From source file:ubic.BAMSandAllen.MatrixPairs.ConnectivityAndAllenDataPair.java

/**
 * Converts connectivity region name to an Allen name
 *///from w  w w.  ja  v a2  s .c o  m
public Set<String> convertANametoB(String BAMSregion) {
    // the region has been modified to create a virtual region (the virtual mapping is 1-1)
    if (virtualRegions.contains(BAMSregion)) {
        Set<String> result = new HashSet<String>();
        result.add(BAMSregion);
        return result;
    }

    Set<String> result = allenCatalog.getAllenMappedRegions(BAMSregion);

    if (result != null) {
        result.retainAll(allenCatalog.getLeafs());
        // if it is in ABAMS space for both matrices, then we can't filter using this
        if (!isInSameSpace)
            result.retainAll(matrixB.getColNames());
    }
    return result;
}

From source file:com.clican.pluto.dataprocess.dpl.parser.object.filter.AndFilter.java

public void filter(ProcessorContext context) throws DplParseException {
    ProcessorContext context1 = context.getCloneContext();
    ProcessorContext context2;//from  ww w  .ja  v a 2  s. c o  m
    filter1.filter(context1);
    dumpTrace(filter1.getExpr(), context1);
    // AndFiltercontextcontext1?clone
    context2 = context1.getCloneContext();
    filter2.filter(context2);
    dumpTrace(filter2.getExpr(), context2);

    DplResultSet dplResultSet1 = context1.getAttribute(CompareFilter.DPL_RESULT_SET);
    DplResultSet dplResultSet2 = context2.getAttribute(CompareFilter.DPL_RESULT_SET);
    if (dplResultSet1 != null && dplResultSet2 != null) {
        // dplResultSet1dplResultSet2?filter2dplResultSet1
        if (dplResultSet1 == dplResultSet2) {
            DplResultSet dplResultSet = new DplResultSet();
            dplResultSet.setResultNames(dplResultSet1.getResultNames());
            dplResultSet.setResultSet(dplResultSet1.getResultSet());
            context.setAttribute(CompareFilter.DPL_RESULT_SET, dplResultSet);
        } else {
            // ?list??
            Set<String> names = new HashSet<String>();
            // ?list??
            Set<String> shareNames = new HashSet<String>();

            for (String name : dplResultSet1.getResultNames()) {
                names.add(name);
            }
            for (String name : dplResultSet2.getResultNames()) {
                if (names.contains(name)) {
                    shareNames.add(name);
                } else {
                    names.add(name);
                }
            }
            Set<Map<String, Object>> filterSet = new HashSet<Map<String, Object>>();
            List<Map<String, Object>> filterList = new ArrayList<Map<String, Object>>();
            DplResultSet dplResultSet = new DplResultSet();
            dplResultSet.setResultNames(names);
            // ?case??FilterParserTestCase#testParseFilter5
            // select list1.id as id from list1,list2,list3,list4,list5
            // where (list1.id=list2.id and list2.id=list3.id) and
            // (list4.id=list5.id and list3.id=list4.id)
            if (shareNames.size() != 0) {
                // ?list??listnamevalueCombinedKeym1m2
                // order1order2??????????
                Map<Set<CombinedKey>, List<Map<String, Object>>> m1 = new HashMap<Set<CombinedKey>, List<Map<String, Object>>>();
                Map<Set<CombinedKey>, List<Map<String, Object>>> m2 = new HashMap<Set<CombinedKey>, List<Map<String, Object>>>();
                Map<Map<String, Object>, Integer> order1 = new HashMap<Map<String, Object>, Integer>();
                Map<Map<String, Object>, Integer> order2 = new HashMap<Map<String, Object>, Integer>();
                final Map<Map<String, Object>, Integer[]> order = new HashMap<Map<String, Object>, Integer[]>();
                // ?m1order1
                for (int i = 0; i < dplResultSet1.getResultSet().size(); i++) {
                    Map<String, Object> rs1 = dplResultSet1.getResultSet().get(i);
                    order1.put(rs1, i);
                    Set<CombinedKey> combinedKeySet = new HashSet<CombinedKey>();
                    for (String name : shareNames) {
                        Object obj = rs1.get(name);
                        CombinedKey key = new CombinedKey();
                        key.setName(name);
                        key.setValue(obj);
                        combinedKeySet.add(key);
                    }
                    if (!m1.containsKey(combinedKeySet)) {
                        m1.put(combinedKeySet, new ArrayList<Map<String, Object>>());
                    }
                    m1.get(combinedKeySet).add(rs1);
                }
                // ?m2order2
                for (int i = 0; i < dplResultSet2.getResultSet().size(); i++) {
                    Map<String, Object> rs2 = dplResultSet2.getResultSet().get(i);
                    order2.put(rs2, i);
                    Set<CombinedKey> combinedKeySet = new HashSet<CombinedKey>();
                    for (String name : shareNames) {
                        Object obj = rs2.get(name);
                        CombinedKey key = new CombinedKey();
                        key.setName(name);
                        key.setValue(obj);
                        combinedKeySet.add(key);
                    }
                    if (!m2.containsKey(combinedKeySet)) {
                        m2.put(combinedKeySet, new ArrayList<Map<String, Object>>());
                    }
                    m2.get(combinedKeySet).add(rs2);
                }

                for (Set<CombinedKey> key : m1.keySet()) {
                    if (m2.containsKey(key)) {
                        // ?CombinedKey??
                        List<Map<String, Object>> list1 = m1.get(key);
                        List<Map<String, Object>> list2 = m2.get(key);
                        for (Map<String, Object> row1 : list1) {
                            for (Map<String, Object> row2 : list2) {
                                Map<String, Object> row = new HashMap<String, Object>();
                                row.putAll(row1);
                                row.putAll(row2);
                                if (!filterSet.contains(row)) {
                                    filterList.add(row);
                                    Integer[] i = new Integer[] { order1.get(row1), order2.get(row2) };
                                    // Join????order
                                    order.put(row, i);
                                }
                            }
                        }
                    }
                }
                // ????order??Join????
                Collections.sort(filterList, new Comparator<Map<String, Object>>() {

                    public int compare(Map<String, Object> map1, Map<String, Object> map2) {
                        Integer[] o1 = order.get(map1);
                        Integer[] o2 = order.get(map2);
                        if (o1[0].equals(o2[0])) {
                            return o1[1] - o2[1];
                        } else {
                            return o1[0] - o2[0];
                        }
                    }
                });
            } else {
                // ??name2???
                for (Map<String, Object> row1 : dplResultSet1.getResultSet()) {
                    for (Map<String, Object> row2 : dplResultSet2.getResultSet()) {
                        Map<String, Object> row = new HashMap<String, Object>();
                        row.putAll(row1);
                        row.putAll(row2);
                        if (!filterSet.contains(row)) {
                            filterList.add(row);
                        }
                    }
                }
            }
            dplResultSet.setResultSet(filterList);
            context.setAttribute(CompareFilter.DPL_RESULT_SET, dplResultSet);
        }
    } else if (dplResultSet1 != null && dplResultSet2 == null) {
        context.setAttribute(CompareFilter.DPL_RESULT_SET, dplResultSet1);
    } else if (dplResultSet2 != null && dplResultSet1 == null) {
        context.setAttribute(CompareFilter.DPL_RESULT_SET, dplResultSet2);
    }
    // List??
    for (String name : context.getAttributeNames()) {
        if (name.equals(CompareFilter.DPL_RESULT_SET)) {
            continue;
        }
        if (!(context1.getAttribute(name) instanceof List)) {
            continue;
        }
        List<Object> list1 = context1.getAttribute(name);
        Set<Object> set = new HashSet<Object>();
        final Map<Object, Integer> map = new HashMap<Object, Integer>();
        for (int i = 0; i < list1.size(); i++) {
            map.put(list1.get(i), i);
            set.add(list1.get(i));
        }
        List<Object> list2 = context2.getAttribute(name);
        set.retainAll(new HashSet<Object>(list2));

        List<Object> list = new ArrayList<Object>(set);
        Collections.sort(list, new Comparator<Object>() {

            public int compare(Object o1, Object o2) {
                int order1 = map.get(o1);
                int order2 = map.get(o2);
                return order1 - order2;
            }
        });
        context.setAttribute(name, list);
    }
    if (log.isTraceEnabled()) {
        log.trace("finish filter[" + this.getExpr() + "]");
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.sync.PersonWorkerImpl.java

/**
 *
 * {@inheritDoc}// w w  w  .  j a  v  a 2s . c o  m
 */
@Override
public void process(final NodeDescription person) throws Throwable {
    // Make a mutable copy of the person properties since they get written back to by person service
    final Map<QName, Serializable> personProperties = new HashMap<>(person.getProperties());
    final String personName = personProperties.get(ContentModel.PROP_USERNAME).toString().trim();
    final String domainUser;

    // divergence from Alfresco: adjust the user name for the tenant
    final String primaryDomain = this.tenantService.getPrimaryDomain(personName);
    if (!EqualsHelper.nullSafeEquals(primaryDomain, this.tenantDomain)) {
        domainUser = this.tenantService.getDomainUser(personName, this.tenantDomain);
    } else {
        domainUser = personName;
    }
    personProperties.put(ContentModel.PROP_USERNAME, domainUser);

    if (this.accountInterpreter != null) {
        final QName propertyNameToCheck = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI,
                "userAccountStatusProperty");
        final Serializable propertyValue = personProperties.get(propertyNameToCheck);
        final Boolean disabled = this.accountInterpreter.isUserAccountDisabled(propertyValue);
        if (disabled != null) {
            personProperties.put(ContentModel.PROP_ENABLED, disabled);
        }
    }

    this.nameChecker.evaluate(domainUser);

    NodeRef personRef = null;
    Serializable avatarValue = null;

    final Set<String> personZones = this.authorityService.getAuthorityZones(domainUser);
    if (personZones == null) {
        LOGGER.debug("Creating user {}", domainUser);

        avatarValue = personProperties.remove(ContentModel.ASSOC_AVATAR);
        personRef = this.personService.createPerson(personProperties, this.targetZoneIds);
    } else if (personZones.contains(this.zoneId)) {
        LOGGER.debug("Updating user {}", domainUser);

        avatarValue = personProperties.remove(ContentModel.ASSOC_AVATAR);
        personRef = this.personService.getPerson(domainUser);
        this.personService.setPersonProperties(domainUser, personProperties, false);
    } else {
        personRef = this.personService.getPerson(domainUser);

        // Check whether the user is in any of the authentication chain zones
        final Set<String> intersection = new TreeSet<>();
        for (final String groupZone : personZones) {
            if (groupZone.startsWith(AuthorityService.ZONE_AUTH_EXT_PREFIX)) {
                final String baseId = groupZone.substring(AuthorityService.ZONE_AUTH_EXT_PREFIX.length());
                intersection.add(baseId);
            }
        }
        intersection.retainAll(this.allIds);
        // Check whether the user is in any of the higher priority authentication chain zones
        final Set<String> visited = new TreeSet<>(intersection);
        visited.retainAll(this.visitedIds);

        if (visited.size() == 0) {
            if (!this.allowDeletions || intersection.isEmpty()) {
                LOGGER.info(
                        "Updating user {} - this user will in future be assumed to originate from user registry {}",
                        domainUser, this.id);
                this.updateAuthorityZones(personName, personZones, this.targetZoneIds);
                this.personService.setPersonProperties(domainUser, personProperties, false);
            } else {
                LOGGER.info(
                        "Recreating occluded user {} - this user was previously created through synchronization with a lower priority user registry",
                        domainUser);
                this.personService.deletePerson(domainUser);

                avatarValue = personProperties.remove(ContentModel.ASSOC_AVATAR);
                personRef = this.personService.createPerson(personProperties, this.targetZoneIds);
            }
        }
    }

    if (personRef != null && avatarValue != null) {
        this.handleAvatar(personRef, avatarValue);
    }

    final Date lastModified = person.getLastModified();
    this.latestModified.updateAndGet(oldLastModified -> {
        long newValue = lastModified.getTime();
        if (oldLastModified > newValue) {
            newValue = oldLastModified;
        }
        return newValue;
    });
}