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.wso2.carbon.governance.registry.extensions.aspects.utils.Utils.java

public static boolean isCheckItemClickAllowed(String[] roles, List<PermissionsBean> permissionsBeans) {
    Set<String> permissionSet = new HashSet<String>(Arrays.asList(roles));
    if (permissionsBeans != null) {
        for (PermissionsBean permission : permissionsBeans) {
            if (permission.getRoles() != null) {
                List permRoles = permission.getRoles();
                permissionSet.retainAll(permRoles);
            }/*from  ww w. j  av  a2 s.c  o  m*/
        }
    }
    return !permissionSet.isEmpty();
}

From source file:eu.edisonproject.training.wsd.DisambiguatorImpl.java

/**
 * Returns a set with strings common to the two given maps.
 *
 * @param leftVector left vector map//from  w  ww.  j a  v a 2  s . c  om
 * @param rightVector right vector map
 * @return common strings
 */
private static Set<String> getIntersection(Map<String, Double> leftVector, Map<String, Double> rightVector) {

    //        ValueComparator bvc = new ValueComparator(leftVector);
    //        TreeMap<String, Double> Lsorted_map = new TreeMap(bvc);
    //        Lsorted_map.putAll(leftVector);
    //
    //        bvc = new ValueComparator(rightVector);
    //        TreeMap<String, Double> Rsorted_map = new TreeMap(bvc);
    //        Rsorted_map.putAll(rightVector);
    //
    //        SortedSet<String> Lkeys = new TreeSet<>(leftVector.keySet());
    //        SortedSet<String> Rkeys = new TreeSet<>(rightVector.keySet());
    Set<String> intersection = new HashSet<>(leftVector.keySet());
    intersection.retainAll(rightVector.keySet());
    return intersection;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_LibraryJars.java

/** Want to end up with 3 lists:
 *  - v1 objects that don't exist in v2 (Create them)
 *  - v2 objects that don't exist in v1 (Delete them)
 *  - matching v1/v2 objects with different modified times (Update them)
 * @param to_compare//from w  w w .  ja  v  a2 s.c om
 * @returns a 3-tuple with "to create", "to delete", "to update" - NOTE: none of the _ids here include the "v1_"
 */
protected static Tuple3<Collection<String>, Collection<String>, Collection<String>> compareJarsToLibraryBeans_categorize(
        final Tuple2<Map<String, String>, Map<String, Date>> to_compare) {

    // Want to end up with 3 lists:
    // - v1 sources that don't exist in v2 (Create them)
    // - v2 sources that don't exist in v1 (Delete them)
    // - matching v1/v2 sources with different modified times (Update them)

    // (do delete first, then going to filter to_compare._1() on value==null)      
    final Set<String> v2_not_v1 = new HashSet<String>(to_compare._2().keySet());
    v2_not_v1.removeAll(to_compare._1().keySet());

    // OK not worried about deletes any more, not interested in isApproved:false

    final Set<String> to_compare_approved = to_compare._1().entrySet().stream()
            .filter(kv -> null != kv.getValue() && !kv.getValue().isEmpty()).map(kv -> kv.getKey())
            .collect(Collectors.toSet());

    final Set<String> v1_and_v2 = new HashSet<String>(to_compare_approved);
    v1_and_v2.retainAll(to_compare._2().keySet());

    final List<String> v1_and_v2_mod = v1_and_v2.stream().filter(id -> {
        try {
            final Date v1_date = parseJavaDate(to_compare._1().get(id));
            final Date v2_date = to_compare._2().get(id);
            return v1_date.getTime() > v2_date.getTime();
        } catch (Exception e) {
            return false; // (just ignore)
        }
    }).collect(Collectors.toList());

    final Set<String> v1_not_v2 = new HashSet<String>(to_compare_approved);
    v1_not_v2.removeAll(to_compare._2().keySet());

    return Tuples._3T(v1_not_v2, v2_not_v1, v1_and_v2_mod);
}

From source file:com.liferay.events.global.mobile.Utils.java

private static double getExpertiseMatch(EventContact me, EventContact targetContact) throws JSONException {

    Map<String, Double> desires1 = getJSONWordWeightsFromString(me.getDesires());
    Map<String, Double> desires2 = getJSONWordWeightsFromString(targetContact.getDesires());
    Map<String, Double> expertise1 = getJSONWordWeightsFromString(me.getExpertise());
    Map<String, Double> expertise2 = getJSONWordWeightsFromString(targetContact.getExpertise());

    // how many of my desires do they have expertise in?
    Set<String> common1 = new HashSet<String>(desires1.keySet());
    common1.retainAll(expertise2.keySet());

    // how matchy is it?
    double common1Val = 0.0;
    double uncommon1Val = 0.0;

    for (String desire1 : desires1.keySet()) {
        if (expertise2.containsKey(desire1)) {
            common1Val += (desires1.get(desire1) + expertise2.get(desire1));
        } else {//from w  ww  .  j a  v a2s  .  co m
            uncommon1Val += desires1.get(desire1);
        }
    }

    // now look the other way
    for (String desire2 : desires2.keySet()) {
        if (expertise1.containsKey(desire2)) {
            common1Val += (desires2.get(desire2) + expertise1.get(desire2));
        } else {
            uncommon1Val += desires2.get(desire2);
        }
    }

    if ((common1Val + uncommon1Val) <= 0.0) {
        return 0.0;
    } else {
        return common1Val / (common1Val + uncommon1Val);
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.aspects.utils.Utils.java

public static boolean isTransitionAllowed(String[] roles, List<PermissionsBean> permissionsBeans,
        String eventName) {//www .  ja  v  a 2  s .  co m
    Set<String> permissionSet = new HashSet<String>(Arrays.asList(roles));
    if (permissionsBeans != null) {
        for (PermissionsBean permission : permissionsBeans) {
            if (permission.getForEvent().equals(eventName) && permission.getRoles() != null) {
                List permRoles = permission.getRoles();
                permissionSet.retainAll(permRoles);
            }
        }
    }
    return !permissionSet.isEmpty();
}

From source file:com.facebook.login.LoginManager.java

static LoginResult computeLoginResult(final LoginClient.Request request, final AccessToken newToken) {
    Set<String> requestedPermissions = request.getPermissions();
    Set<String> grantedPermissions = new HashSet<String>(newToken.getPermissions());

    // If it's a reauth, subset the granted permissions to just the requested permissions
    // so we don't report implicit permissions like user_profile as recently granted.
    if (request.isRerequest()) {
        grantedPermissions.retainAll(requestedPermissions);
    }//from   w  w  w .  j  a  v  a  2 s . co m

    Set<String> deniedPermissions = new HashSet<String>(requestedPermissions);
    deniedPermissions.removeAll(grantedPermissions);
    return new LoginResult(newToken, grantedPermissions, deniedPermissions);
}

From source file:com.liferay.events.global.mobile.Utils.java

public static double getInterestLikeness(EventContact me, EventContact targetContact) throws JSONException {

    JSONArray words1o = JSONFactoryUtil.createJSONArray(me.getInterests());
    JSONArray words2o = JSONFactoryUtil.createJSONArray(targetContact.getInterests());

    List<String> words1 = new ArrayList<String>();
    List<String> words2 = new ArrayList<String>();
    Map<String, Integer> count1 = new HashMap<String, Integer>();
    Map<String, Integer> count2 = new HashMap<String, Integer>();
    Map<String, Double> weight1 = new HashMap<String, Double>();
    Map<String, Double> weight2 = new HashMap<String, Double>();

    for (int i = 0; i < words1o.length(); i++) {
        JSONObject o = words1o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words1.add(word);/*from   w  w  w . j  a va  2  s . c  o  m*/
        count1.put(word, count);
        weight1.put(word, weight);
    }

    for (int i = 0; i < words2o.length(); i++) {
        JSONObject o = words2o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words2.add(word);
        count2.put(word, count);
        weight2.put(word, weight);
    }

    Set<String> commonWords = new HashSet<String>(words1);
    commonWords.retainAll(words2);

    Set<String> uncommonWords = new HashSet<String>(words1);
    uncommonWords.addAll(words2);
    uncommonWords.removeAll(commonWords);

    double matchedScore = 0.0;
    double unmatchedScore = 0.0;

    for (String commonWord : commonWords) {
        matchedScore += (((double) count1.get(commonWord) * weight1.get(commonWord))
                + (((double) count2.get(commonWord) * weight2.get(commonWord))));
    }

    for (String uncommonWord : uncommonWords) {
        if (words1.contains(uncommonWord)) {
            unmatchedScore += ((double) count1.get(uncommonWord) * weight1.get(uncommonWord));
        } else {
            unmatchedScore += ((double) count2.get(uncommonWord) * weight2.get(uncommonWord));
        }
    }

    return unmatchedScore > 0 ? ((matchedScore * 2.0) / (unmatchedScore + (matchedScore * 2.0))) : 1.0;
}

From source file:grails.plugin.springsecurity.SpringSecurityUtils.java

/**
 * Find authorities in <code>granted</code> that are also in <code>required</code>.
 * @param granted the granted authorities (a collection or array of {@link SpringSecurityUtils}).
 * @param required the required authorities (a collection or array of {@link SpringSecurityUtils}).
 * @return the authority names//from ww w .j  a v  a 2  s  .  co  m
 */
public static Set<String> retainAll(final Object granted, final Object required) {
    Set<String> grantedRoles = authoritiesToRoles(granted);
    Set<String> requiredRoles = authoritiesToRoles(required);
    grantedRoles.retainAll(requiredRoles);
    return grantedRoles;
}

From source file:com.amalto.core.storage.inmemory.InMemoryJoinResults.java

private static Set<Object> _evaluateConditions(Storage storage, InMemoryJoinNode node) {
    if (node.expression != null) {
        Set<Object> expressionIds = new HashSet<Object>();
        StorageResults results = storage.fetch(node.expression); // Expects an active transaction here
        try {/*ww w  . ja  v a2s  .co m*/
            for (DataRecord result : results) {
                for (FieldMetadata field : result.getSetFields()) {
                    expressionIds.add(result.get(field));
                }
            }
        } finally {
            results.close();
        }
        return expressionIds;
    } else {
        Executor executor = getExecutor(node);
        Set<Object> ids = new HashSet<Object>();
        switch (node.merge) {
        case UNION:
        case NONE:
            for (InMemoryJoinNode child : node.children.keySet()) {
                ids.addAll(executor.execute(storage, child));
            }
            break;
        case INTERSECTION:
            for (InMemoryJoinNode child : node.children.keySet()) {
                if (ids.isEmpty()) {
                    ids.addAll(executor.execute(storage, child));
                } else {
                    ids.retainAll(executor.execute(storage, child));
                }
            }
            break;
        default:
            throw new NotImplementedException("No support for '" + node.merge + "'.");
        }
        //
        Set<Object> returnIds = new HashSet<Object>();
        if (node.childProperty != null) {
            if (ids.isEmpty()) {
                return Collections.emptySet();
            }
            long execTime = System.currentTimeMillis();
            {
                UserQueryBuilder qb = from(node.type).selectId(node.type)
                        .where(buildConditionFromValues(null, node.childProperty, ids));
                node.expression = qb.getSelect();
                StorageResults results = storage.fetch(qb.getSelect()); // Expects an active transaction here
                try {
                    for (DataRecord result : results) {
                        for (FieldMetadata field : result.getSetFields()) {
                            returnIds.add(result.get(field));
                        }
                    }
                } finally {
                    results.close();
                }
            }
            node.execTime = System.currentTimeMillis() - execTime;
        }
        return returnIds;
    }
}

From source file:com.liferay.events.global.mobile.Utils.java

public static String getJSONLikenessDescription(EventContact me, EventContact targetContact)
        throws JSONException {

    JSONArray result = JSONFactoryUtil.createJSONArray();

    Map<String, Double> desires1 = getJSONWordWeightsFromString(me.getDesires());
    Map<String, Double> desires2 = getJSONWordWeightsFromString(targetContact.getDesires());
    Map<String, Double> expertise1 = getJSONWordWeightsFromString(me.getExpertise());
    Map<String, Double> expertise2 = getJSONWordWeightsFromString(targetContact.getExpertise());

    // how many of my desires do they have expertise in?
    Set<String> common1 = new HashSet<String>(desires1.keySet());
    common1.retainAll(expertise2.keySet());

    // how many of my expertises do they desire?
    Set<String> common2 = new HashSet<String>(desires2.keySet());
    common2.retainAll(expertise1.keySet());

    if (common1.size() > 0) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();

        List<String> myNeeds = new ArrayList<String>(common1);
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(StringUtils.join(myNeeds.size() > 5 ? myNeeds.subList(0, 5) : myNeeds,
                " " + StringPool.SLASH + " "));

        bit.put("key", "HAS_EXPERTISE_IN_MY_AREAS");
        bit.put("args", args);
        result.put(bit);//from ww w .j a va2s . c o m
    }

    if (common2.size() > 0) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();

        List<String> myExpertise = new ArrayList<String>(common2);
        args.put(targetContact.getGivenName());
        args.put(StringUtils.join(myExpertise.size() > 5 ? myExpertise.subList(0, 5) : myExpertise,
                " " + StringPool.SLASH + " "));

        bit.put("key", "HAS_NEEDS_IN_MY_AREAS");
        bit.put("args", args);
        result.put(bit);

    }

    double industrySimilarity = getJaroWinklerDistance(me.getIndustry(), targetContact.getIndustry());
    double jobTitleSimilarity = getJaroWinklerDistance(me.getJobTitle(), targetContact.getJobTitle());
    double locationDistance;

    if (me.getLat() == 0 || me.getLng() == 0 || targetContact.getLat() == 0 || targetContact.getLng() == 0) {
        locationDistance = 100000;
    } else {
        locationDistance = getDistanceBetween(me.getLat(), me.getLng(), targetContact.getLat(),
                targetContact.getLng());
    }

    double locationSimilarity = 1.0 - (locationDistance / 1000.0);
    if (locationSimilarity < 0)
        locationSimilarity = 0;

    if (locationSimilarity > .5 && me.getCountry().equals(targetContact.getCountry())) {

        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getCity());
        bit.put("key", "IS_NEARBY");
        bit.put("args", args);
        result.put(bit);

    } else if (me.getCountry().equals(targetContact.getCountry())) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        bit.put("key", "LIVES_WORKS_IN_COUNTRY");
        bit.put("args", args);
        result.put(bit);

    }

    if (industrySimilarity > .7) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getIndustry());
        bit.put("key", "SIMILAR_INDUSTRY");
        bit.put("args", args);
        result.put(bit);

    }
    if (jobTitleSimilarity > .7) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(targetContact.getGivenName());
        args.put(targetContact.getJobTitle());
        bit.put("key", "SIMILAR_JOB");
        bit.put("args", args);
        result.put(bit);

    }

    JSONArray words1o = JSONFactoryUtil.createJSONArray(me.getInterests());
    JSONArray words2o = JSONFactoryUtil.createJSONArray(targetContact.getInterests());

    List<String> words1 = new ArrayList<String>();
    List<String> words2 = new ArrayList<String>();
    final Map<String, Integer> count1 = new HashMap<String, Integer>();
    final Map<String, Integer> count2 = new HashMap<String, Integer>();
    final Map<String, Double> weight1 = new HashMap<String, Double>();
    final Map<String, Double> weight2 = new HashMap<String, Double>();

    for (int i = 0; i < words1o.length(); i++) {
        JSONObject o = words1o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words1.add(word);
        count1.put(word, count);
        weight1.put(word, weight);
    }

    for (int i = 0; i < words2o.length(); i++) {
        JSONObject o = words2o.getJSONObject(i);

        String word = o.getString("word");
        int count = o.getInt("count");
        double weight = o.getDouble("weight");

        words2.add(word);
        count2.put(word, count);
        weight2.put(word, weight);
    }

    Set<String> commonWords = new HashSet<String>(words1);
    commonWords.retainAll(words2);

    List<String> sortedCommon = new SortedArrayList<String>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return (int) Math.floor(
                    ((((double) count1.get(o2) * weight1.get(o2)) + ((double) count2.get(o2) * weight2.get(o2)))
                            - (((double) count1.get(o1) * weight1.get(o1))
                                    + ((double) count2.get(o1) * weight2.get(o1)))));

        }
    });

    sortedCommon.addAll(commonWords);

    if (!sortedCommon.isEmpty()) {
        JSONObject bit = JSONFactoryUtil.createJSONObject();
        JSONArray args = JSONFactoryUtil.createJSONArray();
        args.put(StringUtils.join(sortedCommon.size() > 5 ? sortedCommon.subList(0, 5) : sortedCommon, " / "));
        bit.put("key", "SIMILAR_SKILLS_INTERESTS");
        bit.put("args", args);
        result.put(bit);

    }

    if (result.length() <= 0) {
        List<String> sortedTargetWords = new SortedArrayList<String>(new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return (int) Math.floor(((weight2.get(b) * (double) count2.get(b))
                        - (weight2.get(a) * (double) count2.get(a))));
            }
        });
        sortedTargetWords.addAll(words2);

        if (!sortedTargetWords.isEmpty()) {
            JSONObject bit = JSONFactoryUtil.createJSONObject();
            JSONArray args = JSONFactoryUtil.createJSONArray();
            args.put(StringUtils.join(
                    sortedTargetWords.size() > 3 ? sortedTargetWords.subList(0, 3) : sortedTargetWords, " / "));
            bit.put("key", "MIGHT_BE_INTERESTED");
            bit.put("args", args);
            result.put(bit);

        }
    }
    return result.toString();
}