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:net.sourceforge.fenixedu.applicationTier.Servico.coordinator.degreeCurricularPlanManagement.ReadCurriculumHistoryByCurricularCourseCodeAndExecutionYearName.java

@Atomic
public static InfoCurriculum run(Integer executionDegreeCode, String curricularCourseCode,
        String stringExecutionYear) throws FenixServiceException {
    check(RolePredicates.COORDINATOR_PREDICATE);
    InfoCurriculum infoCurriculum = null;

    if (curricularCourseCode == null) {
        throw new FenixServiceException("nullCurricularCourse");
    }//from w ww. jav a2s. c  om
    if (stringExecutionYear == null || stringExecutionYear.length() == 0) {
        throw new FenixServiceException("nullExecutionYearName");
    }
    CurricularCourse curricularCourse = (CurricularCourse) FenixFramework.getDomainObject(curricularCourseCode);
    if (curricularCourse == null) {
        throw new NonExistingServiceException("noCurricularCourse");
    }

    final ExecutionYear executionYear = ExecutionYear.readExecutionYearByName(stringExecutionYear);
    if (executionYear == null) {
        throw new NonExistingServiceException("noExecutionYear");
    }

    Curriculum curriculumExecutionYear = curricularCourse
            .findLatestCurriculumModifiedBefore(executionYear.getEndDate());
    if (curriculumExecutionYear != null) {
        List allCurricularCourseScopes = new ArrayList();
        List allExecutionCourses = new ArrayList();
        Collection executionPeriods = executionYear.getExecutionPeriodsSet();
        Iterator iterExecutionPeriods = executionPeriods.iterator();
        while (iterExecutionPeriods.hasNext()) {
            ExecutionSemester executionSemester = (ExecutionSemester) iterExecutionPeriods.next();
            Set<CurricularCourseScope> curricularCourseScopes = curricularCourse
                    .findCurricularCourseScopesIntersectingPeriod(executionSemester.getBeginDate(),
                            executionSemester.getEndDate());
            if (curricularCourseScopes != null) {
                List disjunctionCurricularCourseScopes = (List) CollectionUtils
                        .disjunction(allCurricularCourseScopes, curricularCourseScopes);
                List intersectionCurricularCourseScopes = (List) CollectionUtils
                        .intersection(allCurricularCourseScopes, curricularCourseScopes);

                allCurricularCourseScopes = (List) CollectionUtils.union(disjunctionCurricularCourseScopes,
                        intersectionCurricularCourseScopes);
            }
            List associatedExecutionCourses = new ArrayList();
            Collection<ExecutionCourse> executionCourses = curricularCourse.getAssociatedExecutionCoursesSet();
            for (ExecutionCourse executionCourse : executionCourses) {
                if (executionCourse.getExecutionPeriod().equals(executionSemester)) {
                    associatedExecutionCourses.add(executionCourse);
                }
            }

            if (associatedExecutionCourses != null) {
                allExecutionCourses.addAll(associatedExecutionCourses);
            }

        }

        infoCurriculum = createInfoCurriculum(curriculumExecutionYear, allCurricularCourseScopes,
                allExecutionCourses);
    }
    return infoCurriculum;
}

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

/**
 * advanced counts for per Compound mode(i.e. MLP assays,ChEMBL assays, Beta
 * Lactamase assays, Luciferase assays, Projects, MLP projects)
 *///from ww w .  j a  va2 s .  c  o  m
@SuppressWarnings("unchecked")
private void addAdvancedAssayCounts(OverallListsAndMaps overall, Map<String, PromiscuityCount<?>> countMap) {
    PromiscuityCount<Long> allAssayCount = (PromiscuityCount<Long>) countMap
            .get(PCPromiscuityFactory.allAssayName);
    if (allAssayCount != null) {
        List<Long> allAssayTotal = allAssayCount.getTotal();
        List<Long> allAssayActive = allAssayCount.getActive();

        Map<String, List<Long>> advancedCountTotalMap = overall.getAdvancedCountTotalAIDMap();
        for (String searchName : advancedCountTotalMap.keySet()) {
            List<Long> aidList = advancedCountTotalMap.get(searchName);
            List<Long> compoundAIDTotalList = (List<Long>) CollectionUtils.intersection(allAssayTotal, aidList);
            List<Long> compoundAIDActiveList = (List<Long>) CollectionUtils.intersection(allAssayActive,
                    aidList);
            PromiscuityCount<Long> count = new PromiscuityCount<Long>(searchName, compoundAIDActiveList,
                    compoundAIDTotalList);
            countMap.put(count.getName(), count);
        }
    }
}

From source file:net.sf.firemox.token.CardPropertiesOperation.java

/**
 * Return the result operation result applied on the given properties.
 * //from   w  w  w. jav  a  2 s.c o m
 * @param properties
 *          first properties set.
 * @param properties2
 *          second properties set.
 * @param lower
 *          The minimal property value included used by the operation.
 * @param higher
 *          The maximal property value included used by the operation.
 * @return the result operation result applied on the given properties.
 */
@SuppressWarnings("unchecked")
public int getValue(Set<Integer> properties, Set<Integer> properties2, int lower, int higher) {
    final Collection<Integer> workingSet;
    switch (this) {
    case INTERSECTION_SIZE:
        workingSet = CollectionUtils.intersection(properties, properties2);
        break;
    case UNION_SIZE:
        workingSet = CollectionUtils.union(properties, properties2);
        break;
    case DISJONCTION_SIZE:
        workingSet = CollectionUtils.disjunction(properties, properties2);
        break;
    default:
        Log.fatal("Unhandled CardPropertiesOperation +" + this);
        workingSet = new ArrayList<Integer>();
    }
    int count = workingSet.size();
    for (Integer value : workingSet) {
        if (value < lower || higher > value) {
            count--;
        }
    }
    return count;
}

From source file:de.hybris.platform.secureportaladdon.tests.util.B2BSecurePortalTestsUtil.java

public static boolean compareLists(final List<String> listA, final List<String> listB) {
    return listA.size() == listB.size() && CollectionUtils.intersection(listA, listB).size() == listA.size();
}

From source file:controllers.transformer.ExcelTransformer.java

public byte[] getBytes() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Sheet1");

    if (results == null) {
        results = survey.resultCollection;
    }/*from  w ww  .  j a  v  a  2 s .  c o  m*/

    /** Header **/
    HSSFRow row = sheet.createRow(0);
    int fieldcounter = 0;
    row.createCell(fieldcounter++).setCellValue("ResultId");
    row.createCell(fieldcounter++).setCellValue("SurveyId");
    row.createCell(fieldcounter++).setCellValue("Title");
    row.createCell(fieldcounter++).setCellValue("Start time");
    row.createCell(fieldcounter++).setCellValue("End time");
    row.createCell(fieldcounter++).setCellValue("Date Sent");
    row.createCell(fieldcounter++).setCellValue("User");
    row.createCell(fieldcounter++).setCellValue("Phone Number");
    row.createCell(fieldcounter++).setCellValue("Lat");
    row.createCell(fieldcounter++).setCellValue("Lon");

    /** Header Fields**/
    for (Question question : survey.getQuestions()) {
        row.createCell(fieldcounter++).setCellValue(question.label);
    }

    int countrow = 0;
    row = sheet.createRow(++countrow);

    //SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z");

    for (NdgResult result : results) {
        fieldcounter = 0;
        row.createCell(fieldcounter++).setCellValue(result.resultId);
        row.createCell(fieldcounter++).setCellValue(result.survey.surveyId);
        row.createCell(fieldcounter++).setCellValue(result.title);
        row.createCell(fieldcounter++).setCellValue(dateFormat.format(result.startTime));
        row.createCell(fieldcounter++).setCellValue(dateFormat.format(result.endTime));

        if (result.dateSent != null) {
            row.createCell(fieldcounter++).setCellValue(dateFormat.format(result.dateSent));
        } else {
            row.createCell(fieldcounter++).setCellValue("");
        }

        row.createCell(fieldcounter++).setCellValue(result.ndgUser.username);
        row.createCell(fieldcounter++).setCellValue(result.ndgUser.phoneNumber);
        row.createCell(fieldcounter++).setCellValue(result.latitude);
        row.createCell(fieldcounter++).setCellValue(result.longitude);

        for (Question question : survey.getQuestions()) {//to ensure right answer order
            Collection<Answer> answers = CollectionUtils.intersection(question.answerCollection,
                    result.answerCollection);//only one should left, hope that it does not modify results
            if (answers.isEmpty()) {
                row.createCell(fieldcounter++).setCellValue("");
            } else if (answers.size() == 1) {
                Answer answer = answers.iterator().next();
                if (answer.question.questionType.typeName.equalsIgnoreCase(QuestionTypesConsts.IMAGE)) {//TODO handle other binary data
                    row.createCell(fieldcounter++).setCellValue(storeImagesAndGetValueToExport(survey.surveyId,
                            result.resultId, answer.id, answer.binaryData));
                } else if (answer.question.questionType.typeName.equalsIgnoreCase(QuestionTypesConsts.INT)) {
                    Integer value = Integer.valueOf(answer.textData);
                    row.createCell(fieldcounter++).setCellValue(value);
                } else if (answer.question.questionType.typeName
                        .equalsIgnoreCase(QuestionTypesConsts.DECIMAL)) {
                    Float value = Float.valueOf(answer.textData);
                    row.createCell(fieldcounter++).setCellValue(value);
                } else {
                    String value = answer.textData;
                    value = value.trim().replaceAll("\n", "");
                    row.createCell(fieldcounter++).setCellValue(value);
                }
            } else {
                Logger.getAnonymousLogger().log(Level.WARNING,
                        "to many answers. ResID={0}questioId={1}answerCount={2}",
                        new Object[] { result.resultId, question.id, question.answerCollection.size() });
                break;
            }
        }
        row = sheet.createRow(++countrow);
    }
    try {
        wb.write(out);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return out.toByteArray();
}

From source file:edu.northwestern.bioinformatics.studycalendar.domain.StudySite.java

@Transient
public static StudySite findStudySite(Study study, Site site) {
    if (study != null && site != null) {
        Collection<StudySite> studySite = CollectionUtils.intersection(study.getStudySites(),
                site.getStudySites());//from w ww. j  a  v a 2  s.c  o  m
        if (studySite != null && studySite.size() > 0) {
            return studySite.iterator().next();
        }
    }
    return null;
}

From source file:controllers.Service.java

public static void allToKML(String surveyId) {
    Survey survey = Survey.findById(Long.decode(surveyId));
    Collection<NdgResult> results = new ArrayList<NdgResult>();
    Collection<NdgResult> removalResults = new ArrayList<NdgResult>();
    results = survey.resultCollection;//from  w w w  . j  a va 2s  .  c o m

    for (NdgResult current : results) {
        if (current.latitude == null || current.longitude == null) {
            removalResults.add(current);
        }
    }
    results.removeAll(removalResults);

    ByteArrayOutputStream arqExport = new ByteArrayOutputStream();
    String fileName = surveyId + ".kml";

    try {
        final Kml kml = new Kml();
        final Document document = kml.createAndSetDocument();

        for (NdgResult current : results) {
            //                String description = "<![CDATA[ ";
            String description = "";
            int i = 0;

            List<Question> questions = new ArrayList<Question>();
            questions = survey.getQuestions();

            if (questions.isEmpty()) {
                description += "<b> NO QUESTION </b> <br><br>";
            }

            for (Question question : questions) {
                i++;
                description += "<h3><b>" + i + " - " + question.label + "</b></h3><br>";

                Collection<Answer> answers = CollectionUtils.intersection(question.answerCollection,
                        current.answerCollection);
                if (answers.isEmpty()) {
                    description += "<br><br>";
                } else if (answers.size() == 1) {
                    Answer answer = answers.iterator().next();

                    if (answer.question.questionType.typeName.equalsIgnoreCase(QuestionTypesConsts.IMAGE)) {
                        /*                            ByteArrayOutputStream baos = new ByteArrayOutputStream(); //TODO Include image, right
                                                    byte[] buf = new byte[1024];                                //now it adds base64 to the img
                                                    InputStream in = answer.binaryData.get();                   //tag but it doesn't show on
                                                    int n = 0;                                                  //the map
                                                    try {
                        while( (n = in.read(buf) ) >= 0) {
                            baos.write(buf, 0, n);
                        }
                        in.close();
                                                    } catch(IOException ex) {
                        System.out.println("IO");
                                                    }
                                
                                                    byte[] bytes = baos.toByteArray();
                                                    System.out.println("image = " + Base64.encodeBase64String(bytes));
                                                    description += "<img src='data:image/jpeg;base64," + Base64.encodeBase64String(bytes)
                                + "'/> <br><br>"; */
                        description += "<b> #image</b> <br><br>";
                    } else {
                        description += "<h4 style='color:#3a77ca'><b>" + answer.textData + "</b></h4><br>";
                    }
                }
            }
            //                description += " ]]>";

            document.createAndAddPlacemark().withName(current.title).withOpen(Boolean.TRUE)
                    .withDescription(description).createAndSetPoint()
                    .addToCoordinates(current.longitude + ", " + current.latitude);
        }

        kml.marshal(arqExport);
        send(fileName, arqExport.toByteArray());
    } catch (FileNotFoundException ex) {
    }
}

From source file:com.comcast.cats.service.ir.redrat.RedRatManagerImpl.java

@SuppressWarnings("unchecked")
@Schedule(second = "0", minute = "*/5", hour = "*", persistent = false)
@AccessTimeout(value = TelnetConnection.DEFAULT_READ_TIMEOUT, unit = TimeUnit.MILLISECONDS)
public synchronized void refresh() {
    // TODO: Once MDS in CATS 4 is available this should obtain data from
    // MDS./*from   www  .j a  va  2 s .  co m*/
    // For now, it will be made available through keymanager web app.
    logger.info("RedRatManager refresh ");
    KeyManagerProxy kmProxy = keyManagerProxyProvider.get();
    logger.info("RedRatManager refresh  kmProxy " + kmProxy);
    if (kmProxy != null) {
        List<IrDeviceDTO> irDevicesDTOList = kmProxy.getIrDevices();
        logger.info("RedRatManager refresh  irDevicesDTOList " + irDevicesDTOList);
        List<RedRatDevice> irDevicesNewList = processDTO(irDevicesDTOList);
        logger.info("RedRatManager refresh " + irDevicesNewList);

        if (irDevicesNewList != null) {
            List<RedRatDevice> removedIrDevices = new ArrayList<RedRatDevice>(irDevices);
            Collection<RedRatDevice> retainedDevicesCollection = null;
            if (!irDevices.isEmpty()) {
                retainedDevicesCollection = CollectionUtils.intersection(irDevices, irDevicesNewList);
                logger.info("RedRatManager refresh retainedDevicesCollection " + retainedDevicesCollection);
                removedIrDevices.removeAll(retainedDevicesCollection);

            }
            logger.info("RedRatManager refresh removedIrDevices " + removedIrDevices);
            boolean response = false;
            if (removedIrDevices != null && !removedIrDevices.isEmpty()) {
                for (RedRatDevice removedDevice : removedIrDevices) {
                    RedRatHub redratHub = irNetBoxHubMap.get(removedDevice);
                    response = redratHub.blackListRedRat(removedDevice);
                }
            }
            logger.info("RedRatManager blacklist response " + response);

            //lets whitelist all boxes all times
            //else if we restart the hub (to accommodate a new keyset
            // we'll have no way of whitelisting already added boxes unless we redploy.
            if (irDevicesNewList != null && !irDevicesNewList.isEmpty()) {
                for (RedRatDevice redratDevice : irDevicesNewList) {
                    RedRatHub redratHub = irNetBoxHubMap.get(redratDevice);
                    response = redratHub.whiteListRedRat(redratDevice);
                }
            }
            logger.info("RedRatManager whitelist response " + response);
            irDevices = irDevicesNewList;
        }
    }

}

From source file:com.day.cq.wcm.foundation.forms.FormResourceEdit.java

/**
 * Calculates the set of common values and the set of partially present
 * values for a multi-value property on a list of resources. The
 * {@link #common} values will be the ones that are present in the property
 * in all resources, whereas the {@link #partial} values will be the set of
 * all values that are present at least in one resource, but not all of
 * them. The multi-value property is seen as set, so the order and multiple
 * occurences of the same value in a single property do not make any
 * difference./*ww w.  j av a  2 s  . c  om*/
 * 
 * @param resources
 *            a list of resources
 * @param name
 *            the name of the multi-value property to inspect
 * @return a struct object with the {@link #common} and {@link #partial}
 *         sets of values
 */
@SuppressWarnings("unchecked")
public static CommonAndPartial getCommonAndPartialMultiValues(List<Resource> resources, String name) {
    CommonAndPartial r = new CommonAndPartial();

    boolean firstResource = true;
    for (Resource resource : resources) {
        ValueMap map = resource.adaptTo(ValueMap.class);
        if (map != null) {
            String[] values = map.get(name, new String[0]);
            if (firstResource) {
                for (String v : values) {
                    r.common.add(v);
                }
                firstResource = false;
            } else {
                List<String> newValues = Arrays.asList(values);
                // partial: add all that are not in common
                r.partial.addAll(CollectionUtils.disjunction(r.common, newValues));
                // common: reset to only what actually overlaps, all the time
                r.common = new HashSet<String>(CollectionUtils.intersection(r.common, newValues));
            }
        }
    }
    return r;
}

From source file:gov.nih.nci.caintegrator.application.study.GenomicDataSourceConfiguration.java

/**
 * @return the mapped samples//  w  w  w .  j a va2  s .  c  om
 */
@SuppressWarnings("unchecked")
public List<Sample> getMappedSamples() {
    List<Sample> mappedSamples = new ArrayList<Sample>();
    mappedSamples.addAll(CollectionUtils.intersection(getSamples(), getStudyConfiguration().getSamples()));
    addRefreshFlagToMappedSamples(mappedSamples, getRefreshSampleNames());
    return mappedSamples;
}