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:org.kuali.kpme.tklm.time.timesummary.service.TimeSummaryServiceImpl.java

private List<EarnGroupSection> sortEarnGroupSections(List<EarnGroupSection> sections,
        Set<String> regularEarnCodes) {
    List<EarnGroupSection> sortedList = new ArrayList<EarnGroupSection>();
    //first sort by alpha
    Collections.sort(sections, new Comparator<EarnGroupSection>() {
        @Override//w w w  .jav a  2 s . co m
        public int compare(EarnGroupSection egs1, EarnGroupSection egs2) {
            if (egs1 == null ^ egs2 == null) {
                return egs1 == null ? -1 : 1;
            }
            if (egs1 == null && egs2 == null) {
                return 0;
            }
            //'other' earn group needs to be last.
            boolean isOther1 = StringUtils.equals(egs1.getEarnGroup(), OTHER_EARN_GROUP);
            boolean isOther2 = StringUtils.equals(egs2.getEarnGroup(), OTHER_EARN_GROUP);
            if (isOther1 ^ isOther2) {
                return isOther1 ? 1 : -1;
            }
            if (isOther1 && isOther2) {
                return 0;
            }
            return egs1.getEarnGroup().compareTo(egs2.getEarnGroup());
        }
    });

    List<EarnGroupSection> copy = new ArrayList<EarnGroupSection>(sections);
    //loop through in reverse
    for (EarnGroupSection egs : copy) {
        if (!CollectionUtils.intersection(regularEarnCodes, egs.getEarnCodeToEarnCodeSectionMap().keySet())
                .isEmpty()) {
            sortedList.add(egs);
            sections.remove(egs);
        }
    }
    sortedList.addAll(sections);
    return sortedList;
}

From source file:org.kuali.rice.kim.lookup.RoleMemberLookupableHelperServiceImpl.java

@SuppressWarnings("unchecked")
protected List<RoleBo> searchRoles(Map<String, String> roleSearchCriteria, boolean unbounded) {
    List<RoleBo> roles = (List<RoleBo>) getLookupService().findCollectionBySearchHelper(RoleBo.class,
            roleSearchCriteria, unbounded);
    String membersCrt = roleSearchCriteria.get("members.memberId");
    List<RoleBo> roles2Remove = new ArrayList<RoleBo>();
    if (StringUtils.isNotBlank(membersCrt)) {
        List<String> memberSearchIds = new ArrayList<String>();
        List<String> memberIds = new ArrayList<String>();
        if (membersCrt.contains(KimConstants.KimUIConstants.OR_OPERATOR)) {
            memberSearchIds = new ArrayList<String>(Arrays.asList(membersCrt.split("\\|")));
        } else {// w w  w  . ja  v  a2 s . c  o  m
            memberSearchIds.add(membersCrt);
        }
        for (RoleBo roleBo : roles) {
            List<RoleMemberBo> roleMembers = roleBo.getMembers();
            memberIds.clear();
            CollectionUtils.filter(roleMembers, new Predicate() {
                public boolean evaluate(Object object) {
                    RoleMemberBo member = (RoleMemberBo) object;
                    // keep active member
                    return member.isActive(new Timestamp(System.currentTimeMillis()));
                }
            });

            if (roleMembers != null && !roleMembers.isEmpty()) {
                for (RoleMemberBo memberImpl : roleMembers) {
                    memberIds.add(memberImpl.getMemberId());
                }
                if (((List<String>) CollectionUtils.intersection(memberSearchIds, memberIds)).isEmpty()) {
                    roles2Remove.add(roleBo);
                }
            } else {
                roles2Remove.add(roleBo);
            }
        }
    }
    if (!roles2Remove.isEmpty()) {
        roles.removeAll(roles2Remove);
    }
    return roles;
}

From source file:org.kuali.student.ap.coursesearch.service.impl.CourseDetailsViewHelperServiceImpl.java

/**
 * Filters a list of registration groups based on a list of activity offering ids
 *
 * @param regGroupIds - List of registration ids to filter
 * @param selectedActivities - List of activity ids to be found in valid reg groups
 * @return A list of filtered registration groups
 *//*  ww w  .j  av  a2  s  . com*/
private List<String> getValidRegGroupsFilteredBySelectedActivities(List<String> regGroupIds,
        List<String> selectedActivities) {
    // If no activities are sent skip filtering
    if (selectedActivities != null && !selectedActivities.isEmpty()) {
        List<String> regGroupIdsFromSelectedAOs = new ArrayList<String>();
        for (String activityId : selectedActivities) {
            try {
                SearchRequestInfo request = new SearchRequestInfo(
                        CourseSearchConstants.KSAP_COURSE_SEARCH_OFFERED_REG_GROUP_IDS_BY_AO_ID_KEY);
                request.addParam(CourseSearchConstants.SearchParameters.ACTIVITY_OFFERING_ID, activityId);
                List<SearchResultRowInfo> rows = KsapFrameworkServiceLocator.getSearchService()
                        .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows();
                List<String> tempIds = new ArrayList<>();
                for (SearchResultRowInfo row : rows) {
                    tempIds.add(KsapHelperUtil.getCellValue(row,
                            CourseSearchConstants.SearchResultColumns.REG_GROUP_ID));
                }
                if (regGroupIdsFromSelectedAOs.isEmpty()) {
                    regGroupIdsFromSelectedAOs.addAll(tempIds);
                } else {
                    regGroupIdsFromSelectedAOs = (List<String>) CollectionUtils
                            .intersection(regGroupIdsFromSelectedAOs, tempIds);
                }
            } catch (InvalidParameterException e) {
                throw new IllegalArgumentException("Lui Service lookup error", e);
            } catch (MissingParameterException e) {
                throw new IllegalArgumentException("Lui Service lookup error", e);
            } catch (OperationFailedException e) {
                throw new IllegalArgumentException("Lui Service lookup error", e);
            } catch (PermissionDeniedException e) {
                throw new IllegalArgumentException("Lui Service lookup error", e);
            }
        }
        List<String> validAOGroups = new ArrayList<String>();
        for (String id : regGroupIds) {
            if (regGroupIdsFromSelectedAOs.contains(id)) {
                validAOGroups.add(id);
            }
        }

        regGroupIds = validAOGroups;
    }
    return regGroupIds;
}

From source file:org.kuali.student.common.util.krms.proposition.CourseCompletionProposition.java

@Override
public PropositionResult evaluate(ExecutionEnvironment environment) {

    Collection<String> completedCourses = environment
            .resolveTerm(RulesExecutionConstants.STUDENT_COMPLETED_COURSE_IDS_TERM, this);

    Collection<String> termCourses = getTermCourseIds(environment);

    PropositionResult result = null;// w ww.  j a va  2 s  .  c  o  m

    if (checkForAllCompleted) {
        result = new PropositionResult(completedCourses.containsAll(termCourses));
    }

    else {
        result = new PropositionResult(
                CollectionUtils.intersection(completedCourses, termCourses).size() >= minToComplete);
    }

    environment.getEngineResults().addResult(
            new BasicResult(ResultEvent.PROPOSITION_EVALUATED, this, environment, result.getResult()));

    return result;

}

From source file:org.kuali.student.common.util.krms.proposition.CourseEnrollmentProposition.java

@Override
public PropositionResult evaluate(ExecutionEnvironment environment) {

    Collection<String> enrolledCourses = environment
            .resolveTerm(RulesExecutionConstants.STUDENT_ENROLLED_COURSE_IDS_TERM, this);

    Collection<String> requiredCourseIds = getRequiredCourseIds(environment);

    PropositionResult result = null;/*from  ww w  .  ja va 2s  . c  o  m*/

    if (checkForAllEnrolled) {
        result = new PropositionResult(enrolledCourses.containsAll(requiredCourseIds));
    }

    else {
        result = new PropositionResult(
                CollectionUtils.intersection(enrolledCourses, requiredCourseIds).size() >= minToEnroll);
    }

    environment.getEngineResults().addResult(
            new BasicResult(ResultEvent.PROPOSITION_EVALUATED, this, environment, result.getResult()));

    return result;

}

From source file:org.kuali.student.common.util.krms.proposition.MaxCourseCompletionProposition.java

@Override
public PropositionResult evaluate(ExecutionEnvironment environment) {
    Collection<String> completedCourses = environment
            .resolveTerm(RulesExecutionConstants.STUDENT_COMPLETED_COURSE_IDS_TERM, this);
    Collection<String> coursesToCheck;

    if (singleCourseId == null) {
        Term term = new Term(RulesExecutionConstants.COURSE_SET_TERM.getName(),
                Collections.singletonMap(RulesExecutionConstants.COURSE_SET_ID_TERM.getName(), courseSetId));
        coursesToCheck = environment.resolveTerm(term, this);
    } else {//w w w.ja  v a 2s .c  o m
        coursesToCheck = Collections.singleton(singleCourseId);
    }

    PropositionResult result = new PropositionResult(
            CollectionUtils.intersection(completedCourses, coursesToCheck).size() <= maxCoursesCompleted);

    environment.getEngineResults().addResult(
            new BasicResult(ResultEvent.PROPOSITION_EVALUATED, this, environment, result.getResult()));

    return result;
}

From source file:org.matsim.contrib.socnetgen.sna.graph.matrix.AdjacencyMatrixTest.java

private int countCommonNeighbours(Vertex v1, Vertex v2) {
    List<? extends Vertex> n1set = v1.getNeighbours();
    List<? extends Vertex> n2set = v2.getNeighbours();

    return CollectionUtils.intersection(n1set, n2set).size();
}

From source file:org.medici.bia.controller.manuscriptviewer.AjaxController.java

/**
 * @param entryId//from w w w  . jav a  2  s .com
 * @param volNum
 * @param volLetExt
 * @param imageType
 * @param imageProgTypeNum
 * @param imageOrder
 * @param imageName
 * @param total
 * @param totalRubricario
 * @param totalCarta
 * @param totalAppendix
 * @param totalOther
 * @param totalGuardia
 * @param modeEdit
 * @param request
 * @return
 */
@RequestMapping(value = { "/src/mview/GetLinkedDocument.json",
        "/de/mview/GetLinkedDocument.json" }, method = RequestMethod.GET)
public ModelAndView findLinkedDocument(@RequestParam(value = "entryId", required = false) Integer entryId,
        @RequestParam(value = "volNum", required = false) Integer volNum,
        @RequestParam(value = "volLetExt", required = false) String volLetExt,
        @RequestParam(value = "imageType", required = false) String imageType,
        @RequestParam(value = "imageProgTypeNum", required = false) Integer imageProgTypeNum,
        @RequestParam(value = "imageOrder", required = false) Integer imageOrder,
        @RequestParam(value = "imageName", required = false) String imageName,
        @RequestParam(value = "total", required = false) Long total,
        @RequestParam(value = "totalRubricario", required = false) Long totalRubricario,
        @RequestParam(value = "totalCarta", required = false) Long totalCarta,
        @RequestParam(value = "totalAppendix", required = false) Long totalAppendix,
        @RequestParam(value = "totalOther", required = false) Long totalOther,
        @RequestParam(value = "totalGuardia", required = false) Long totalGuardia,
        @RequestParam(value = "modeEdit", required = false) Boolean modeEdit, HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>(0);

    try {
        Integer documentId = null;
        List<Document> linkedDocumentOnStartFolio = null;
        List<Document> linkedDocumentOnTranscribeFolio = null;
        boolean isExtract = false;
        Image image = new Image();

        int intersectionSize = 0;
        int unionSize = 0;

        //         if (entryId != null) {
        //            documentId = entryId;
        //         } else {
        if (org.medici.bia.common.util.StringUtils.safeTrim(imageType) != null
                && !"C".equals(imageType.trim())) {
            model.put("error", "wrongType");
        } else {
            // We extract image
            image = getManuscriptViewerService().findVolumeImage(null, volNum, volLetExt,
                    (imageType != null) ? ImageType.valueOf(imageType) : null, imageProgTypeNum, imageOrder);

            if (image != null) {
                model.put("imageName", image.getImageName());
                model.put("imageId", image.getImageId());
                model.put("imageType", image.getImageType());
                model.put("imageOrder", image.getImageOrder());

                if (!ImageType.C.equals(image.getImageType())) {
                    model.put("error", "wrongType");
                } else {
                    // We check if this image has linked document on start folio...
                    linkedDocumentOnStartFolio = getManuscriptViewerService()
                            .findLinkedDocumentOnStartFolioWithOrWithoutRectoVerso(volNum, volLetExt,
                                    image.getInsertNum(), image.getInsertLet(), image.getImageProgTypeNum(),
                                    image.getMissedNumbering(),
                                    image.getImageRectoVerso() != null ? image.getImageRectoVerso().toString()
                                            : null);

                    // ..and on transcribe folio
                    linkedDocumentOnTranscribeFolio = getManuscriptViewerService()
                            .findLinkedDocumentOnTranscriptionWithOrWithoutRectoVerso(volNum, volLetExt,
                                    image.getInsertNum(), image.getInsertLet(), image.getImageProgTypeNum(),
                                    image.getMissedNumbering(),
                                    image.getImageRectoVerso() != null ? image.getImageRectoVerso().toString()
                                            : null);

                    if (!linkedDocumentOnStartFolio.isEmpty() && !linkedDocumentOnTranscribeFolio.isEmpty()) {
                        intersectionSize = CollectionUtils
                                .intersection(linkedDocumentOnStartFolio, linkedDocumentOnTranscribeFolio)
                                .size();
                        unionSize = CollectionUtils
                                .union(linkedDocumentOnStartFolio, linkedDocumentOnTranscribeFolio).size();
                    } else {
                        unionSize = Math.max(linkedDocumentOnStartFolio.size(),
                                linkedDocumentOnTranscribeFolio.size());
                    }

                    if (unionSize == 1) {
                        documentId = linkedDocumentOnStartFolio.isEmpty()
                                ? linkedDocumentOnTranscribeFolio.iterator().next().getEntryId()
                                : linkedDocumentOnStartFolio.iterator().next().getEntryId();
                    } else if (unionSize > 1) {
                        isExtract = true;
                    }
                }
            }
        }
        //         }         
        if (documentId != null) {
            isExtract = getManuscriptViewerService().isDocumentExtract(documentId);
        }

        // old one
        //model.put("linkedDocument", (linkedDocumentOnStartFolio != null && linkedDocumentOnStartFolio.size() > 0) ? true : false);
        // new ones
        model.put("linkedDocumentOnStartFolio",
                (linkedDocumentOnStartFolio != null && linkedDocumentOnStartFolio.size() > 0) ? true : false);
        model.put("linkedDocumentOnTranscribeFolio",
                (linkedDocumentOnTranscribeFolio != null && linkedDocumentOnTranscribeFolio.size() > 0) ? true
                        : false);
        model.put("countAlreadyEntered", unionSize);
        model.put("countStartAndTranscribeHere", intersectionSize);
        model.put("entryId", documentId);
        if (unionSize == 1) {
            model.put("showLinkedDocument", HtmlUtils.showDocument(documentId));
        } else if (unionSize > 1) {
            model.put("showLinkedDocument",
                    HtmlUtils.showSameFolioDocuments(volNum, volLetExt, image.getInsertNum(),
                            image.getInsertLet(), image.getImageProgTypeNum(), image.getMissedNumbering(),
                            image.getImageRectoVerso().toString()));
        }
        model.put("isExtract", isExtract);
    } catch (ApplicationThrowable applicationThrowable) {
        model.put("entryId", null);
        //model.put("linkedDocument", false);
        model.put("linkedDocumentOnStartFolio", false);
        model.put("linkedDocumentOnTranscribeFolio", false);
        model.put("showLinkedDocument", "");
        model.put("imageName", "");
        model.put("imageId", "");
        model.put("imageOrder", "");
        model.put("isExtract", false);
    }

    return new ModelAndView("responseOK", model);
}

From source file:org.mmadsen.sim.transmissionlab.analysis.IndividualTraitFrequencyAnalyzer.java

/**
 * calculateTurnover() runs through the prev and current sorted lists of TraitCount
 * objects, and calculates turnover (additions and removals) of traits from "top N"
 * lists (i.e., truncating prev and cur sorted lists if list.size > topNlistsize).
 * The topN cur and prev lists are then intersected, and we return turnover as:
 * (prevsize + cursize) - (2 * intersection.size)
 * @return turnover - double representing turnover, calculated from current data
 *//*from   w ww .j a va  2  s  .  c  o m*/
private double calculateTurnover() {
    double turnover = 0.0;
    //log.debug("lists should be trimmed to " + topNListSize);

    if (prevSortedTraitCounts == null) {
        // this will happen on the first tick, after that we should be fine
        return 0;
    }

    // given the sorted trait frequencies tallied in the IDataCollector process()
    // method, extract the top N traits and the number of agents that have traits in that top N list
    List prevList = this.getTopNTraits(prevSortedTraitCounts);
    List curList = this.getTopNTraits(curSortedTraitCounts);
    int numAgentsInTopN = this.getNumAgentsInTopN(curSortedTraitCounts);

    log.debug("TFA:  num agents with traits in top N: " + numAgentsInTopN);

    // update the tracking information for how long traits in the TopN spend in each position
    this.updateCumTopNResidenceByTrait(curList);

    // now find the intersection of these two sorted trait ID lists
    Collection intersection = CollectionUtils.intersection(prevList, curList);
    log.debug("TFA:  previous: " + Arrays.deepToString(prevList.toArray()));
    log.debug("TFA:  current: " + Arrays.deepToString(curList.toArray()));
    log.debug("TFA:  intersection: " + Arrays.deepToString(intersection.toArray()));

    // now use the list sizes and the cardinality of the intersection set to calculate turnover
    int prevSize = prevList.size();
    int curSize = curList.size();
    int intersectionSize = intersection.size();
    turnover = (prevSize + curSize) - (2 * intersection.size());
    log.debug("prev size: " + prevSize + " cursize: " + curSize + " intersection size: " + intersectionSize
            + " turnover: " + turnover);

    // add the calculated to the turnover history
    this.turnoverHistory.add(turnover);
    this.agentsInTopNHistory.add((double) numAgentsInTopN);

    return turnover;
}

From source file:org.montp2.m1decol.ter.preprocessing.GlobalPreProcessing.java

public Collection<String> intersectVocabulary(String path) throws IOException {
    List<Set<String>> list = new ArrayList<Set<String>>();
    for (File file : FileUtils.ls(path)) {
        list.add(splitWordsByFiles(file.getAbsolutePath()));
    }/*from w w w  .ja  va 2 s  .  c  om*/

    Collection<String> intersections = list.get(0);
    for (int i = 1; i < list.size(); i++) {
        intersections = CollectionUtils.intersection(intersections, list.get(i));
    }

    /*
    Set<String> val = new HashSet<String>();
    int ix = list.size()-1;
    int n;
    for (int i = 0; i < list.size(); i++) {
    Collection<String> intersections2 = null;
    if(ix != 0){
        intersections2 = list.get(0);
        n = 0;
    }else{
        intersections2 = list.get(1);
        n = 1;
    }
    for (int j = 0; j < list.size(); j++) {
        if(ix != j && n != j){
            intersections = CollectionUtils.intersection(intersections2,list.get(j));
        }
    }
    ix--;
    val.addAll(intersections2);
    }
            
    intersections.addAll(val);    */

    return intersections;
}