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.jamocha.filter.optimizer.NodeShareOptimizer.java

private void buildBlock(final Defrule.PathRule rule, final PathNodeFilterSet pathFilter) {
    final Set<PathNodeFilterSet> preBlock = new HashSet<>();
    final Map<Defrule.PathRule, Map<Path, Path>> rule2PathMap = new HashMap<>();
    preBlock.add(pathFilter);//from   ww  w.j  a v a  2 s  . com
    // add all filters producing conflicts in the same rule
    {
        Set<PathNodeFilterSet> newFilters = new HashSet<>();
        newFilters.add(pathFilter);
        while (!newFilters.isEmpty()) {
            final Set<PathNodeFilterSet> conflictFilters = new HashSet<>();
            for (final PathNodeFilterSet newFilter : newFilters) {
                for (final Path path : filter2Paths.get(newFilter)) {
                    conflictFilters.addAll(path2Filters.getOrDefault((path), Collections.emptySet()));
                }
            }
            conflictFilters.removeAll(preBlock);
            newFilters = new HashSet<>();
            for (final PathNodeFilterSet conflictFilter : conflictFilters) {
                final Set<PathNodeFilterSet> conflictingInBlock = filter2Paths.get(conflictFilter).stream()
                        .flatMap(p -> path2Filters.get(p).stream()).filter(f -> preBlock.contains(f))
                        .collect(toSet());
                if (!filter2Blocks.get(conflictFilter).stream()
                        .allMatch(b -> b.containsAll(conflictingInBlock))) {
                    newFilters.add(conflictFilter);
                    preBlock.add(conflictFilter);
                }
            }
        }
    }
    // Add all rules which do not produce conflicts
    {
        final Set<PathNodeFilterSet> preBlockAdds = new HashSet<>();
        final Set<Defrule.PathRule> possibleRules = new HashSet<>();
        possibleRules.addAll(allRules);
        for (final PathNodeFilterSet filter : preBlock) {
            possibleRules.retainAll(
                    pool.getEqualFilters(filter).stream().map(f -> filter2Rule.get(f)).collect(toSet()));
        }
        for (final Defrule.PathRule possibleRule : possibleRules) {
            final Map<Path, Path> pathMap = new HashMap<>();
            final Map<PathNodeFilterSet, PathNodeFilterSet> filterMap = comparePathFilters(preBlock,
                    Sets.newHashSet(possibleRule.getCondition()), pathMap);
            if (null != filterMap && checkForConflicts(filterMap.values())) {
                preBlockAdds.addAll(filterMap.values());
                rule2PathMap.put(possibleRule, pathMap);
            }
        }
    }
    {
        for (final PathNodeFilterSet filter : rule.getCondition()) {
            if (preBlock.contains(filter))
                continue;
            for (final Defrule.PathRule otherRule : rule2PathMap.keySet()) {
                // TBD hier weiterarbeiten
                otherRule.toString();
            }
        }
    }
}

From source file:org.mskcc.cbio.cgds.dao.DaoProteinArrayInfo.java

public ArrayList<ProteinArrayInfo> getProteinArrayInfoForEntrezIds(int cancerStudyId,
        Collection<Long> entrezIds, Collection<String> types) throws DaoException {
    Set<String> arrayIds = getArrayIdsOfCancerType(cancerStudyId);
    arrayIds.retainAll(DaoProteinArrayTarget.getInstance().getProteinArrayIds(entrezIds));
    return getProteinArrayInfo(arrayIds, types);
}

From source file:org.trellisldp.webac.WebACService.java

@Override
public Set<IRI> getAccessModes(final IRI identifier, final Session session) {
    requireNonNull(session, "A non-null session must be provided!");

    if (Trellis.AdministratorAgent.equals(session.getAgent())) {
        return unmodifiableSet(allModes);
    }//from www  .java  2  s  . c  o m

    final Set<IRI> cachedModes = cache.get(getCacheKey(identifier, session.getAgent()),
            k -> getAuthz(identifier, session.getAgent()));
    return session.getDelegatedBy().map(delegate -> {
        final Set<IRI> delegatedModes = new HashSet<>(
                cache.get(getCacheKey(identifier, delegate), k -> getAuthz(identifier, delegate)));
        delegatedModes.retainAll(cachedModes);
        return unmodifiableSet(delegatedModes);
    }).orElseGet(() -> unmodifiableSet(cachedModes));
}

From source file:com.github.vseguip.sweet.contacts.SweetContactSync.java

Set<String> getConflictSet(List<ISweetContact> list1, List<ISweetContact> list2) {
    Set<String> set1 = getSetOfIds(list1);
    Set<String> set2 = getSetOfIds(list2);
    set1.retainAll(set2);
    return set1;/*  w ww. j  a v a  2s. c o m*/
}

From source file:edu.tum.cs.conqat.quamoco.qiesl.QIESLEngine.java

/** Checks if the sets contain no overlapping variables */
private void checkOverlappingVariables(Set<String> set1, Set<String> set2) throws QIESLException {
    Set<String> intersection = new HashSet<String>(set1);
    intersection.retainAll(set2);
    if (!intersection.isEmpty()) {
        throw new QIESLException("Overlapping variables: " + StringUtils.concat(intersection, ", "));
    }//w ww.  j  a v a 2  s.  co m
}

From source file:com.microsoft.tfs.core.clients.workitem.internal.metadata.ConstantSet.java

private Set<Integer> query(final DBConnection connection, // the DB connection to use
        final Set<Integer> rootIds, // these IDs form the starting set
        final boolean addLeaf, // leaf node values should be added to this
        // constant set
        final boolean addNonLeaf, // non-leaf node values should be added to
        // this constant set
        final boolean needChildren) // we need to return children ids that are
// non-leaf nodes
{
    final Set<Integer> childIds = getChildIDs(connection, rootIds);

    final Set<Integer> selfContainedIds = new HashSet<Integer>(rootIds);
    selfContainedIds.retainAll(childIds);

    childIds.removeAll(selfContainedIds);

    final Set<Integer> idsToAdd = new HashSet<Integer>();
    Set<Integer> nonLeafChildIds = new HashSet<Integer>();

    if (addLeaf) {
        final Set<Integer> leafIds = new HashSet<Integer>(childIds);
        leafIds.removeAll(distinctConstantSetIds);
        leafIds.addAll(selfContainedIds);
        idsToAdd.addAll(leafIds);/*ww w  . j av  a2  s.co m*/
    }

    if (addNonLeaf | needChildren) {
        nonLeafChildIds = new HashSet<Integer>(childIds);
        nonLeafChildIds.retainAll(distinctConstantSetIds);
        if (addNonLeaf) {
            idsToAdd.addAll(nonLeafChildIds);
        }
    }

    if (idsToAdd.size() > 0) {
        final StringBuffer sb = new StringBuffer(
                "select ConstID, String, DisplayName from Constants where ConstID in ("); //$NON-NLS-1$
        for (final Iterator<Integer> it = idsToAdd.iterator(); it.hasNext();) {
            final Integer i = it.next();
            sb.append(i);
            if (it.hasNext()) {
                sb.append(","); //$NON-NLS-1$
            }
        }
        sb.append(")"); //$NON-NLS-1$

        connection.createStatement(sb.toString()).executeQuery(new ResultHandler() {
            @Override
            public void handleRow(final ResultSet rset) throws SQLException {
                final int constId = rset.getInt(1);
                final String string = rset.getString(2);
                final String displayName = rset.getString(3);
                values.add(displayName != null ? displayName : string);
                constIds.add(new Integer(constId));
            }
        });
    }

    if (needChildren) {
        return nonLeafChildIds;
    } else {
        return Collections.emptySet();
    }
}

From source file:op.tools.SYSTools.java

public static Collection intersect(Collection set1, Collection set2) {
    // http://code.hammerpig.com/find-the-difference-between-two-lists-in-java.html
    Set intersection = new HashSet(set1);
    intersection.retainAll(new HashSet(set2));
    return intersection;
}

From source file:com.devicehive.service.DeviceClassService.java

@Transactional
public Set<DeviceClassEquipmentVO> createEquipment(@NotNull Long classId,
        @NotNull Set<DeviceClassEquipmentVO> equipments) {
    DeviceClassWithEquipmentVO deviceClass = deviceClassDao.find(classId);
    Set<String> existingCodesSet = deviceClass.getEquipment().stream().map(DeviceClassEquipmentVO::getCode)
            .collect(Collectors.toSet());
    Set<String> newCodeSet = equipments.stream().map(DeviceClassEquipmentVO::getCode)
            .collect(Collectors.toSet());

    newCodeSet.retainAll(existingCodesSet);
    if (!newCodeSet.isEmpty()) {
        String codeSet = StringUtils.join(newCodeSet, ",");
        throw new HiveException(String.format(Messages.DUPLICATE_EQUIPMENT_ENTRY, codeSet, classId),
                FORBIDDEN.getStatusCode());
    }/*from ww w  . j  a v a  2  s. c o  m*/

    deviceClass.getEquipment().addAll(equipments);

    deviceClass = deviceClassDao.merge(deviceClass);

    //TODO [rafa] duuumb, and lazy, in case of several equipments linked to the class two for loops is fine.
    for (DeviceClassEquipmentVO equipment : equipments) {
        for (DeviceClassEquipmentVO s : deviceClass.getEquipment()) {
            if (equipment.getCode().equals(s.getCode())) {
                equipment.setId(s.getId());
            }
        }
    }

    return equipments;
}

From source file:org.zaizi.alfresco.redlink.webscript.RelatedDocuments.java

@SuppressWarnings("unchecked")
@Override//from  w w  w .ja  v  a  2s. c om
public Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    Map<String, Object> model = new HashMap<String, Object>(1);

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieving and checking the parameters...");
    }

    JSONObject results = new JSONObject();

    try {
        String nodeString = req.getParameter(PARAM_NODEREF);
        int limit = getLimitFromRequest(req);
        if (NodeRef.isNodeRef(nodeString)) {
            NodeRef nodeRef = new NodeRef(nodeString);

            if (nodeService.exists(nodeRef)) {
                List<NodeRef> relatedDocs = new ArrayList<NodeRef>();

                List<NodeRef> prevCategories = (List<NodeRef>) nodeService.getProperty(nodeRef,
                        ContentModel.PROP_CATEGORIES);

                if (prevCategories != null && !prevCategories.isEmpty()) {
                    Set<NodeRef> categories = new LinkedHashSet<NodeRef>(prevCategories);

                    if (!categories.isEmpty()) {
                        String query = "NOT ID:\"" + nodeRef.toString() + "\" AND (";

                        boolean first = true;
                        for (NodeRef cat : categories) {
                            if (!first) {
                                query += " OR ";
                            } else {
                                first = false;
                            }
                            query += "@"
                                    + QueryParser.escape(
                                            ContentModel.PROP_CATEGORIES.toPrefixString(namespaceService))
                                    + ":\"" + QueryParser.escape(cat.toString()) + "\"";
                        }

                        query += " )";

                        SearchParameters sp = new SearchParameters();
                        sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
                        sp.setLanguage(SearchService.LANGUAGE_LUCENE);
                        sp.setQuery(query);
                        sp.setLimit(limit);
                        sp.setLimitBy(LimitBy.FINAL_SIZE);
                        ResultSet rs = null;
                        try {
                            relatedDocs = searchService.query(sp).getNodeRefs();
                        } finally {
                            if (rs != null) {
                                rs.close();
                            }
                        }
                    }

                    JSONArray arrayResults = new JSONArray();
                    for (NodeRef node : relatedDocs) {
                        if (nodeService.exists(node)) {
                            JSONObject nodejson = new JSONObject();
                            nodejson.put("nodeRef", node.toString());

                            Set<String> categoriesNode = new LinkedHashSet<String>(
                                    (List<String>) nodeService.getProperty(node, ContentModel.PROP_CATEGORIES));
                            categoriesNode.retainAll(categories);
                            if (categoriesNode.size() != 0) {
                                nodejson.put("score", categoriesNode.size());
                                nodejson.put("name",
                                        (String) nodeService.getProperty(node, ContentModel.PROP_NAME));
                                arrayResults.put(nodejson);
                            }
                        }
                    }
                    results.put("results", arrayResults);
                }
            } else {
                status.setCode(404);
                results.put("status", status.getCode());
                results.put("response",
                        "NodeRef not exists or doesn't have proper aspect: " + nodeRef.toString());
            }

        } else {
            status.setCode(400);
            results.put("response", "NodeRef not valid: " + nodeString);
        }

    } catch (Exception e) {
        logger.error("Error when querying for related documents: " + e.getMessage(), e);
        status.setCode(Status.STATUS_INTERNAL_SERVER_ERROR);
        try {
            results.put("status", status.getCode());
            results.put("response", e.getMessage());
        } catch (JSONException e1) {
            logger.error("Error building json response", e);
        }
    }
    model.put("results", results);
    return model;

}

From source file:ca.sqlpower.architect.enterprise.ArchitectNetworkConflictResolver.java

/**
 * This method will make sure that column mappings of the same relationship
 * do not point to the same column of a table, since this is illegal.
 *//*from  www.ja v  a 2s  . c  om*/
private void disallowColumnMappingsPointingToSameColumn(List<ConflictMessage> conflicts) {
    /**
     * Stores the uuids of columns that are being pointed to
     * by column mappings. Will store them like so: relationshipId:columnId
     */
    Set<String> duplicates = getColumnMappingChanges(outboundPropertiesToChange);
    duplicates.retainAll(getColumnMappingChanges(inboundPropertiesToChange));
    for (String duplicate : duplicates) {
        String[] ids = duplicate.split("\\:");
        String relationshipId = ids[0];
        String columnId = ids[1];
        String relationshipName = session.getWorkspace().getObjectInTree(relationshipId).getName();
        String columnName = session.getWorkspace().getObjectInTree(columnId).getName();
        String message = "More than one column mapping of relationship " + relationshipName
                + " points to the column " + columnName;
        conflicts.add(new ConflictMessage(message, ConflictCase.SPECIAL_CASE, relationshipId, columnId));
    }

}