Example usage for org.apache.commons.collections CollectionUtils intersection

List of usage examples for org.apache.commons.collections CollectionUtils intersection

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils intersection.

Prototype

public static Collection intersection(final Collection a, final Collection b) 

Source Link

Document

Returns a Collection containing the intersection of the given Collection s.

Usage

From source file:edu.scripps.fl.pubchem.promiscuity.PCPromiscuityFactory.java

private void checkIfActiveSummary(List<Long> xrefAIDs, List<Long> allAssayActive, Long summaryAID,
        List<Long> summaryActive, Map<Long, List<Protein>> aidProteinMap,
        Map<Long, List<Protein>> summaryProteinMap) {

    List<Long> activeXrefAIDs = (List<Long>) CollectionUtils.intersection(xrefAIDs, allAssayActive);
    if (activeXrefAIDs.size() > 0) {
        Boolean isActive = true;//from   w w  w .  jav  a2 s  . c  o m
        int ii = 0;
        List<Protein> summaryProteins = summaryProteinMap.get(summaryAID);

        while (isActive && ii < activeXrefAIDs.size()) {
            Long activeXrefAID = activeXrefAIDs.get(ii);
            List<Protein> xrefProteins = aidProteinMap.get(activeXrefAID);
            if (summaryProteins != null) {
                if (xrefProteins != null) {
                    if (!summaryProteins.containsAll(xrefProteins))
                        isActive = false;
                    else if (summaryProteins.size() > 0 && xrefProteins.size() == 0) {
                        isActive = false;
                    } else
                        ii = ii + 1;
                } else if (xrefProteins == null && summaryProteins.size() > 0)
                    isActive = false;
                else
                    ii = ii + 1;
            } else {
                if (xrefProteins != null && xrefProteins.size() > 0)
                    isActive = false;
                else
                    ii = ii + 1;
            }

        }

        if (isActive)
            summaryActive.add(summaryAID);
    }

}

From source file:com.silverpeas.gallery.web.AbstractGalleryResource.java

/**
 * Indicates if the current user is a privileged one.
 * @return/*from   w  w w.ja  va 2 s. c  om*/
 */
protected boolean isUserPrivileged() {
    return !CollectionUtils.intersection(EnumSet.of(SilverpeasRole.admin, SilverpeasRole.publisher,
            SilverpeasRole.writer, SilverpeasRole.privilegedUser), getUserRoles()).isEmpty();
}

From source file:net.sourceforge.fenixedu.domain.phd.SearchPhdIndividualProgramProcessBean.java

private AndPredicate<PhdIndividualProgramProcess> getManagedPhdProgramsAndProcessesPredicate() {
    final AndPredicate<PhdIndividualProgramProcess> result = new AndPredicate<PhdIndividualProgramProcess>();
    if (getFilterPhdPrograms() != null && getFilterPhdPrograms().booleanValue()) {
        result.add(new InlinePredicate<PhdIndividualProgramProcess, List<PhdProgram>>(getPhdPrograms()) {

            @Override//from ww w  .j ava 2  s  . c om
            public boolean eval(PhdIndividualProgramProcess toEval) {
                if (toEval.getPhdProgram() != null) {
                    return getValue().contains(toEval.getPhdProgram());
                } else if (toEval.getPhdProgramFocusArea() != null) {
                    return !CollectionUtils
                            .intersection(getValue(), toEval.getPhdProgramFocusArea().getPhdProgramsSet())
                            .isEmpty();
                } else {
                    return false;
                }
            }
        });
    }

    if (getFilterPhdProcesses() != null && getFilterPhdProcesses().booleanValue()) {
        result.add(new InlinePredicate<PhdIndividualProgramProcess, List<PhdIndividualProgramProcess>>(
                getProcesses()) {

            @Override
            public boolean eval(PhdIndividualProgramProcess toEval) {
                return getValue().contains(toEval);
            }
        });
    }
    return result;
}

From source file:com.aurel.track.item.consInf.ConsInfBL.java

/**
 * Whether the watcher list changed//www  . j a  v  a2s. co  m
 * @param oldValues
 * @param newValues
 */
public static boolean watcherChanged(List<Integer> oldValues, List<Integer> newValues) {
    if ((oldValues == null || oldValues.isEmpty()) && (newValues == null || newValues.isEmpty())) {
        return false;
    }
    if (oldValues == null) {
        return true;

    } else {
        if (newValues == null) {
            return true;
        } else {
            if (oldValues.size() != newValues.size()) {
                return true;
            }
            Collection<Integer> intersection = CollectionUtils.intersection(oldValues, newValues);
            return intersection == null || newValues.size() != intersection.size();
        }
    }
}

From source file:com.github.NearestNeighbors.java

/**
 * Calculates Euclidian distance between two repositories.
 * /*from  w w w .  j a v a 2  s .co  m*/
 * @param training_watcher
 * @param first
 * @param second
 * @return
 */
private float euclidian_distance(final Watcher training_watcher, final Repository first,
        final Repository second) {
    if (first.equals(second)) {
        return 1000.0f;
    }

    final Collection<Watcher> common_watchers = CollectionUtils.intersection(first.watchers, second.watchers);
    float distance = 1000.0f;

    // Set up weights.

    final float parent_child_weight = 0.4f;
    final float related_weight = 0.75f;
    final float same_owner_weight = 0.65f;
    final float common_watcher_weight = 1.0f;

    // Penalize repositories that have no parent nor children.
    final float lone_repo_weight = (first.parent == null && first.children.isEmpty())
            || (second.parent == null && second.children.isEmpty()) ? 2.0f : 1.0f;
    final float leaf_repo_weight = second.children.isEmpty() ? 1.0f : 1.0f;

    /*
    // Figure out how many repositories the common watchers have in common with the test watcher.
    final Map<String, Number> similar_watcher_counts = new HashMap<String, Number>();
    for (final NeighborRegion watched_region : watchers_to_regions.get(training_watcher.id))
    {
      for (final Watcher w : watched_region.watchers)
      {
        if (similar_watcher_counts.get(w.id) == null)
        {
          similar_watcher_counts.put(w.id, new Integer(0));
        }
            
        similar_watcher_counts.put(w.id, new Integer(similar_watcher_counts.get(w.id).intValue() + 1));
      }
    }
            
    // Convert raw counts to ratios.
    for (final Map.Entry<String, Number> pair : similar_watcher_counts.entrySet())
    {
      similar_watcher_counts.put(pair.getKey(), pair.getValue().floatValue() / watchers_to_regions.get(training_watcher.id).size());
    }
            
    // Figure out how many repositories the test watcher watches that are owned by the first repository owner.
    float similarly_owned_count = 0.0f;
    for (final NeighborRegion watched_region : watchers_to_regions.get(training_watcher.id))
    {
      if (watched_region.most_forked.owner == first.owner)
      {
        similarly_owned_count += 1.0f;
      }
    }
            
    // TODO: (KJM 08/29/09) Consider looking up the region, since that's what we use everywhere else.
    int total_watchers = 1;
    for (final Repository repo : owners_to_repositories.get(first.owner))
    {
      total_watchers += repo.watchers.size();
    }
            
    // If common_watchers is empty, just make the value 1.0 because we use the value as a divisor.
    float common_watchers_repo_diversity = common_watchers.isEmpty() ? 1.0f : 0.0f;
    for (final Watcher w : common_watchers)
    {
      common_watchers_repo_diversity += w.repositories.size();
    }
    common_watchers_repo_diversity /= common_watchers.size();
    */

    final float first_common_watchers_ratio = ((float) common_watchers.size()) / first.watchers.size();
    final float second_common_watchers_ratio = ((float) common_watchers.size()) / second.watchers.size();

    if ((first.parent != null) && first.parent.equals(second)) {
        distance = 0.9f;
        //distance = (float) (parent_child_weight * (1.0 - (((float)common_watchers.size()) / MyUtils.mean(Arrays.asList(first.watchers.size(), second.watchers.size()))))
        //    * (1.0 - ((similarly_owned_count + total_watchers) / Math.max(owners_to_repositories.get(first.owner).size(), 1))) + MyUtils.mean(similar_watcher_counts.values()));
    } else if (first.isRelated(second)) {
        distance = 0.5f;
        //distance = (float) (related_weight * (1.0 - (common_watchers.size() / MyUtils.mean(Arrays.asList(first.watchers.size(), second.watchers.size()))))
        //    - ((common_watchers.size() / common_watchers_repo_diversity) / MyUtils.mean(Arrays.asList(first.watchers.size(), second.watchers.size()))));
    } else if (first.owner.equals(second.owner)) {
        distance = 0.4f * (1.0f - training_watcher.owner_distribution(second.owner))
                / Math.max(1.0f, second.children.size());
        //distance = (float) (same_owner_weight * (1.0 - (MyUtils.mean(Arrays.asList(((float)common_watchers.size()) / first.watchers.size(), ((float)common_watchers.size()) / second.watchers.size()))))
        //    * (1.0 - ((similarly_owned_count + total_watchers) / owners_to_repositories.get(first.owner).size())) + MyUtils.mean(similar_watcher_counts.values()));
    } else {
        if (!common_watchers.isEmpty()) {
            distance = 0.7f;
            //final float first_common_watchers_ratio = ((float) common_watchers.size()) / first.watchers.size();
            //final float second_common_watchers_ratio = ((float) common_watchers.size()) / second.watchers.size();

            //distance = (float) (common_watcher_weight * (1.0 - (MyUtils.mean(Arrays.asList(first_common_watchers_ratio, second_common_watchers_ratio))))
            //    - (((float)common_watchers.size()) / common_watchers_repo_diversity) / MyUtils.mean(Arrays.asList(first.watchers.size(), second.watchers.size())));
        }
    }

    int divisor = second.children.isEmpty() ? 1 : second.children.size();
    return (leaf_repo_weight * lone_repo_weight * distance);// - MyUtils.mean(Arrays.asList(first_common_watchers_ratio, second_common_watchers_ratio));

    /*
    common_watchers_repo_diversity = common_watchers.empty? ? 1 : common_watchers.collect {|w| training_watchers[w].repositories.size}.mean
            
    distance
            
            
    # Other factors for calculating distance:
    # - Ages of repositories
    # - Ancestry of two repositories (give higher weight if one of the repositories is the most popular by watchings and/or forks)
    # - # of forks
    # - watcher chains (e.g., repo a has watchers <2, 5>, repo b has watchers <5, 7>, repo c has watchers <7> . . . a & c may be slightly related.
    # - Language overlaps
    # - Size of repositories?
            
    # Also, look at weighting different attributes.  Maybe use GA to optimize.
     */
}

From source file:biz.netcentric.cq.tools.actool.aceservice.impl.AceServiceImpl.java

private Set<String> getAuthorizablesToRemoveAcesFor(
        Map<String, Set<AuthorizableConfigBean>> authorizablesMapfromConfig) {
    Set<String> authorizablesToRemoveAcesFor = new HashSet<String>(authorizablesMapfromConfig.keySet());
    Set<String> authorizablesToBeMigrated = collectAuthorizablesToBeMigrated(authorizablesMapfromConfig);
    Collection<?> invalidAuthorizablesInConfig = CollectionUtils.intersection(authorizablesToRemoveAcesFor,
            authorizablesToBeMigrated);/* www.  j ava  2s. c  o  m*/
    if (!invalidAuthorizablesInConfig.isEmpty()) {
        String message = "If migrateFrom feature is used, groups that shall be migrated from must not be present in regular configuration (offending groups: "
                + invalidAuthorizablesInConfig + ")";
        LOG.error(message);
        throw new IllegalArgumentException(message);
    }
    authorizablesToRemoveAcesFor.addAll(authorizablesToBeMigrated);
    return authorizablesToRemoveAcesFor;
}

From source file:edu.scripps.fl.pubchem.promiscuity.PCPromiscuityFactory.java

public List<Long> getTotalSummaryListPerCompoundAndProtein(List<Long> compoundSummaries,
        Map<Long, List<Long>> summaryToAIDsMap, List<Long> allAssayTotal) {
    List<Long> summaryTotal = new ArrayList<Long>();
    for (Long summaryAID : compoundSummaries) {
        List<Long> xrefAIDs = summaryToAIDsMap.get(summaryAID);
        if (CollectionUtils.intersection(xrefAIDs, allAssayTotal).size() > 0)
            summaryTotal.add(summaryAID);
    }/* w w w  .  ja  v a2s .c om*/
    return summaryTotal;
}

From source file:info.archinnov.achilles.schemabuilder.Create.java

private void validateColumnsDeclaration() {
    final Collection partitionAndClusteringColumns = CollectionUtils.intersection(partitionColumnsMap.keySet(),
            clusteringColumnsMap.keySet());
    final Collection partitionAndSimpleColumns = CollectionUtils.intersection(partitionColumnsMap.keySet(),
            simpleColumnsMap.keySet());/*from  w ww .  jav  a  2  s  .c om*/
    final Collection clusteringAndSimpleColumns = CollectionUtils.intersection(clusteringColumnsMap.keySet(),
            simpleColumnsMap.keySet());
    final Collection partitionAndStaticColumns = CollectionUtils.intersection(partitionColumnsMap.keySet(),
            staticColumnsMap.keySet());
    final Collection clusteringAndStaticColumns = CollectionUtils.intersection(clusteringColumnsMap.keySet(),
            staticColumnsMap.keySet());
    final Collection simpleAndStaticColumns = CollectionUtils.intersection(simpleColumnsMap.keySet(),
            staticColumnsMap.keySet());

    if (!partitionAndClusteringColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as partition keys and clustering keys at the same time",
                partitionAndClusteringColumns));
    }

    if (!partitionAndSimpleColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as partition keys and simple columns at the same time",
                partitionAndSimpleColumns));
    }

    if (!clusteringAndSimpleColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as clustering keys and simple columns at the same time",
                clusteringAndSimpleColumns));
    }

    if (!partitionAndStaticColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as partition keys and static columns at the same time",
                partitionAndStaticColumns));
    }

    if (!clusteringAndStaticColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as clustering keys and static columns at the same time",
                clusteringAndStaticColumns));
    }

    if (!simpleAndStaticColumns.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The '%s' columns can not be declared as simple columns and static columns at the same time",
                simpleAndStaticColumns));
    }

    if (!staticColumnsMap.isEmpty() && clusteringColumnsMap.isEmpty()) {
        throw new IllegalStateException(
                String.format("The table '%s' cannot declare static columns '%s' without clustering columns",
                        tableName, staticColumnsMap.keySet()));
    }
}

From source file:expansionBlocks.ProcessCommunities.java

private static boolean isSonOf(Set<Category> secondLevelCategories, Category c) {
    Set<Category> fathers = Category.getFathers(c);
    Collection intersection = CollectionUtils.intersection(secondLevelCategories, fathers);
    if (intersection.isEmpty())
        return false;
    return true;//  w  w  w  .j  a  v a 2  s  .  c o  m
}

From source file:biz.netcentric.cq.tools.actool.authorizableutils.impl.AuthorizableCreatorServiceImpl.java

@SuppressWarnings("unchecked")
void mergeMemberOfGroups(String principalId, AcInstallationHistoryPojo status, UserManager userManager,
        Set<String> membershipGroupsFromConfig, Set<String> membershipGroupsFromRepository)
        throws RepositoryException, AuthorizableExistsException, AuthorizableCreatorException {
    LOG.debug("mergeMemberOfGroups() for {}", principalId);

    // membership to everyone cannot be removed or added => take it out from both lists
    membershipGroupsFromConfig.remove(PRINCIPAL_EVERYONE);
    membershipGroupsFromRepository.remove(PRINCIPAL_EVERYONE);

    logAndVerboseHistoryMessage(status,//  w  w  w .  j  a va2s  .  c o  m
            "Principal " + principalId + " isMemberOf(repo)=" + membershipGroupsFromRepository);
    logAndVerboseHistoryMessage(status,
            "Principal " + principalId + " isMemberOf(conifg)=" + membershipGroupsFromConfig);

    Set<String> validatedMembershipGroupsFromConfig = validateAssignedGroups(userManager, principalId,
            membershipGroupsFromConfig);

    Collection<String> unChangedMembers = CollectionUtils.intersection(membershipGroupsFromRepository,
            validatedMembershipGroupsFromConfig);
    logAndVerboseHistoryMessage(status,
            "Principal " + principalId + " remains member of groups " + unChangedMembers);

    Collection<String> toBeAddedMembers = CollectionUtils.subtract(validatedMembershipGroupsFromConfig,
            membershipGroupsFromRepository);
    logAndVerboseHistoryMessage(status,
            "Principal " + principalId + " will be added as member of " + toBeAddedMembers);

    Collection<String> toBeRemovedMembers = CollectionUtils.subtract(membershipGroupsFromRepository,
            validatedMembershipGroupsFromConfig);
    Set<String> toBeSkippedFromRemovalMembers = new HashSet<String>();

    Pattern ignoredMembershipsPattern = status.getAcConfiguration().getGlobalConfiguration()
            .getAllowExternalGroupNamesRegEx();

    Iterator<String> toBeRemovedMembersIt = toBeRemovedMembers.iterator();
    while (toBeRemovedMembersIt.hasNext()) {
        String groupId = toBeRemovedMembersIt.next();
        if ((ignoredMembershipsPattern != null) && ignoredMembershipsPattern.matcher(groupId).find()) {
            toBeSkippedFromRemovalMembers.add(groupId);
            toBeRemovedMembersIt.remove();
        }
    }
    logAndVerboseHistoryMessage(status,
            "Principal " + principalId + " will be removed from members of " + toBeRemovedMembers);

    if (!toBeSkippedFromRemovalMembers.isEmpty()) {
        logAndVerboseHistoryMessage(status,
                "Principal " + principalId + " remains member of groups " + toBeSkippedFromRemovalMembers
                        + " (due to configured ignoredMembershipsPattern=" + ignoredMembershipsPattern + ")");

    }

    // perform changes

    Authorizable currentAuthorizable = userManager.getAuthorizable(principalId);

    for (String groupId : toBeAddedMembers) {
        LOG.debug("Membership Change: Adding {} to members of group {} in repository", principalId, groupId);
        Authorizable targetAuthorizable = userManager.getAuthorizable(groupId);
        ((Group) targetAuthorizable).addMember(currentAuthorizable);
    }

    for (String groupId : toBeRemovedMembers) {
        LOG.debug("Membership Change: Removing {} from members of group {} in repository", principalId,
                groupId);
        Authorizable targetAuthorizable = userManager.getAuthorizable(groupId);
        ((Group) targetAuthorizable).removeMember(currentAuthorizable);
    }

    if (!toBeAddedMembers.isEmpty() && !toBeAddedMembers.isEmpty()) {
        logAndVerboseHistoryMessage(status, "Membership Change: Principal " + principalId + " was added to "
                + toBeAddedMembers.size() + " and removed from " + toBeRemovedMembers.size() + " groups");
    }

}