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.uci.ics.jung.utils.GraphUtils.java

/**
 * Returns a graph which consists of the union of the two input graphs.
 * Assumes that both graphs are of a type that can accept the vertices
 * and edges found in both graphs.//from  www .j a  v  a2 s.  co  m
 * The resultant graph contains all constraints that are common to both graphs.
 */
public static ArchetypeGraph union(ArchetypeGraph g1, ArchetypeGraph g2) {
    ArchetypeGraph g = g1.newInstance();
    //        g.getEdgeConstraints().clear();
    g.getEdgeConstraints()
            .addAll(CollectionUtils.intersection(g1.getEdgeConstraints(), g2.getEdgeConstraints()));

    Collection vertices = CollectionUtils.union(g1.getVertices(), g2.getVertices());
    Collection edges = CollectionUtils.union(g1.getEdges(), g2.getEdges());

    for (Iterator v_iter = vertices.iterator(); v_iter.hasNext();) {
        ArchetypeVertex v = (ArchetypeVertex) v_iter.next();
        v.copy(g);
    }

    for (Iterator e_iter = edges.iterator(); e_iter.hasNext();) {
        ArchetypeEdge e = (ArchetypeEdge) e_iter.next();
        e.copy(g);
    }
    return g;
}

From source file:com.squid.kraken.v4.core.analysis.engine.index.DimensionStore.java

@Override
public List<DimensionMember> getMembersFilterByParents(Map<DimensionIndex, List<DimensionMember>> selections,
        String filter, int offset, int size) {
    ArrayList<DimensionMember> result = new ArrayList<>();
    Set<DimensionMember> flatsel = new HashSet<>();
    int types = 0;
    for (List<DimensionMember> forType : selections.values()) {
        flatsel.addAll(forType);//from w ww. j a  va 2s . c o m
        types++;
    }
    String filterLowerCase = filter.toLowerCase();
    for (DimensionMember member : members) {
        @SuppressWarnings("unchecked")
        Collection<DimensionMember> check = CollectionUtils.intersection(getCorrelations(member), flatsel);
        if (!check.isEmpty() && check.size() >= types && member.match(filterLowerCase)) {
            // ok, in some special cases, the test is not enough - we should check that we have a hit for each type
            result.add(member);
            if (result.size() >= size) {
                break;
            }
        }
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.web.report.RegistrationAdvancedSearchController.java

private List<StudySubject> filterRegistrationsRelatedToLatestScheduledEpoch(List<StudySubject> registrations,
        List<ScheduledEpochWorkFlowStatus> schEpochStatusList, List<EpochType> epochTypesList,
        List<String> offEpochReasonCodesList) {
    List<StudySubject> filteredStudySubjects = new ArrayList<StudySubject>();

    for (StudySubject studySubject : registrations) {
        ScheduledEpoch currentScheduledEpoch = studySubject.getScheduledEpoch();

        List<String> latestEpochOffEpochReasonCodes = new ArrayList<String>();
        for (OffEpochReason offEpochReason : currentScheduledEpoch.getOffEpochReasons()) {
            latestEpochOffEpochReasonCodes.add(offEpochReason.getReason().getCode());
        }//from  w  w  w  .  j ava  2  s. co m
        if (!offEpochReasonCodesList.isEmpty() && CollectionUtils
                .intersection(latestEpochOffEpochReasonCodes, offEpochReasonCodesList).isEmpty()) {
            continue;
        }

        if (!schEpochStatusList.isEmpty()
                && !schEpochStatusList.contains(currentScheduledEpoch.getScEpochWorkflowStatus())) {
            continue;
        }

        if (!epochTypesList.isEmpty() && !epochTypesList.contains(currentScheduledEpoch.getEpoch().getType())) {
            continue;
        }

        filteredStudySubjects.add(studySubject);
    }

    return filteredStudySubjects;
}

From source file:com.dianping.lion.service.impl.ConfigReleaseServiceImpl.java

@SuppressWarnings("unchecked")
@Override//from   w ww. ja  v  a2  s.  c  om
public ConfigRollbackResult rollbackSnapshotSet(ConfigSnapshotSet snapshotSet, String[] keys) {
    ConfigRollbackResult rollbackResult = new ConfigRollbackResult();
    final int projectId = snapshotSet.getProjectId();
    final int envId = snapshotSet.getEnvId();
    try {
        List<ConfigSnapshot> configSnapshots = configReleaseDao.findConfigSnapshots(snapshotSet.getId());
        List<ConfigInstanceSnapshot> configInstSnapshots = configReleaseDao
                .findConfigInstSnapshots(snapshotSet.getId());
        List<Config> currentConfigs = configService.findConfigs(projectId);
        List<ConfigInstance> currentConfigInsts = configService.findInstances(projectId, envId);
        Map<Integer, Date> modifyTimes = configService.findModifyTime(projectId, envId);

        Map<String, ConfigSnapshot> configSnapshotMap = new HashMap<String, ConfigSnapshot>(
                configSnapshots.size());
        for (ConfigSnapshot configSnapshot : configSnapshots) {
            configSnapshotMap.put(configSnapshot.getKey(), configSnapshot);
        }
        Map<Integer, List<ConfigInstanceSnapshot>> configInstSnapshotMap = new HashMap<Integer, List<ConfigInstanceSnapshot>>(
                configSnapshots.size());
        for (ConfigInstanceSnapshot configInstSnapshot : configInstSnapshots) {
            List<ConfigInstanceSnapshot> instList = configInstSnapshotMap.get(configInstSnapshot.getConfigId());
            if (instList == null) {
                instList = new ArrayList<ConfigInstanceSnapshot>();
                configInstSnapshotMap.put(configInstSnapshot.getConfigId(), instList);
            }
            instList.add(configInstSnapshot);
        }
        Set<String> configSnapshotKeys = configSnapshotMap.keySet();

        final Map<String, Config> currentConfigMap = new HashMap<String, Config>(currentConfigs.size());
        for (Config currentConfig : currentConfigs) {
            currentConfigMap.put(currentConfig.getKey(), currentConfig);
        }
        Map<Integer, List<ConfigInstance>> currentConfigInstMap = new HashMap<Integer, List<ConfigInstance>>(
                currentConfigInsts.size());
        for (ConfigInstance currentConfigInst : currentConfigInsts) {
            List<ConfigInstance> instList = currentConfigInstMap.get(currentConfigInst.getConfigId());
            if (instList == null) {
                instList = new ArrayList<ConfigInstance>();
                currentConfigInstMap.put(currentConfigInst.getConfigId(), instList);
            }
            instList.add(currentConfigInst);
        }
        Set<String> currentConfigKeys = currentConfigMap.keySet();

        Set<String> notRemovedKeys = new HashSet<String>();
        Set<String> selectedKeys = null;
        if (keys != null) {
            selectedKeys = new HashSet<String>();
            for (String key : keys) {
                selectedKeys.add(key);
            }
        }
        //1. ????
        /* Notice:
         * ???????????
         * 
         */
        Collection<String> configNeedRemoveKeys = CollectionUtils.subtract(currentConfigKeys,
                configSnapshotKeys);
        notRemovedKeys.addAll(configNeedRemoveKeys);
        //      for (final String configNeedRemoveKey : configNeedRemoveKeys) {
        //         this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        //            @Override
        //            protected void doInTransactionWithoutResult(TransactionStatus status) {
        //               Config configNeedRemove = currentConfigMap.get(configNeedRemoveKey);
        //               configService.deleteInstance(configNeedRemove.getId(), envId);
        //            }
        //         });
        //      }

        //2. ??????
        Collection<String> intersectionKeys = CollectionUtils.intersection(currentConfigKeys,
                configSnapshotKeys);
        for (String intersectionKey : intersectionKeys) {
            if (selectedKeys != null && !selectedKeys.contains(intersectionKey))
                continue;
            ConfigSnapshot configSnapshot = configSnapshotMap.get(intersectionKey);
            final Config currentConfig = currentConfigMap.get(intersectionKey);
            final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap
                    .get(configSnapshot.getConfigId());
            final List<ConfigInstance> currentInstList = currentConfigInstMap.get(currentConfig.getId());
            boolean snapshotNoInst = snapshotInstList == null || snapshotInstList.isEmpty();
            boolean currentNoInst = currentInstList == null || currentInstList.isEmpty();
            if (snapshotNoInst == true && currentNoInst == false) {
                notRemovedKeys.add(intersectionKey);
            } else if (snapshotNoInst == false && currentNoInst == true) {
                //??configinstanceregister server
                this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList);
                    }
                });
            } else if (snapshotNoInst == false && currentNoInst == false) {
                Date modifyTime = modifyTimes.get(currentConfig.getId());
                Date recordModifyTime = configSnapshot.getValueModifyTime();
                if (modifyTime == null || recordModifyTime == null || !modifyTime.equals(recordModifyTime)) {
                    boolean onlyOneSnapshotInst = snapshotInstList.size() == 1;
                    boolean onlyOneCurrentInst = currentInstList.size() == 1;
                    if (onlyOneSnapshotInst && onlyOneCurrentInst) {
                        ConfigInstanceSnapshot snapshotInst = snapshotInstList.get(0);
                        ConfigInstance currentInst = currentInstList.get(0);
                        if (snapshotInst.getContext().equals(currentInst.getContext())
                                && snapshotInst.getValue().equals(currentInst.getValue())) {
                            continue;
                        }
                    }
                    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                        @Override
                        protected void doInTransactionWithoutResult(TransactionStatus status) {
                            configDao.deleteInstances(currentConfig.getId(), envId);
                            restoreConfigInstSnapshots(currentConfig.getId(), envId, snapshotInstList);
                        }
                    });
                }
            }
        }

        //3. ???
        Collection<String> configNeedAddKeys = CollectionUtils.subtract(configSnapshotKeys, currentConfigKeys);
        for (final String configNeedAddKey : configNeedAddKeys) {
            if (selectedKeys != null && !selectedKeys.contains(configNeedAddKey))
                continue;
            final ConfigSnapshot configSnapshot = configSnapshotMap.get(configNeedAddKey);
            final List<ConfigInstanceSnapshot> snapshotInstList = configInstSnapshotMap
                    .get(configSnapshot.getConfigId());
            if (snapshotInstList != null && !snapshotInstList.isEmpty()) {
                this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        int configId = configService.createConfig(configSnapshot.toConfig());
                        restoreConfigInstSnapshots(configId, envId, snapshotInstList);
                    }
                });
            }
        }
        rollbackResult.setNotRemovedKeys(notRemovedKeys);
        return rollbackResult;
    } catch (RuntimeException e) {
        Project project = projectService.getProject(projectId);
        logger.error("rollback configs failed with[project=" + project.getName() + ", task="
                + snapshotSet.getTask() + "].", e);
        throw e;
    }
}

From source file:com.aurel.track.admin.customize.lists.systemOption.IssueTypeBL.java

/**
 * Load all possible item types which can be created by the user
 * @param personID/*from  ww  w  . j av  a2 s.  c o  m*/
 * @param locale
 * @return
 */
public static List<TListTypeBean> loadAllByPerson(Integer personID, Locale locale) {
    //get all create item role assignments for person
    List<TAccessControlListBean> accessControlListBeans = AccessBeans.loadByPersonAndRight(personID,
            new int[] { AccessFlagIndexes.CREATETASK, AccessFlagIndexes.PROJECTADMIN }, true);
    Map<Integer, Set<Integer>> projectsToRolesMap = new HashMap<Integer, Set<Integer>>();
    Set<Integer> allPersonRolesSet = new HashSet<Integer>();
    if (accessControlListBeans != null) {
        for (TAccessControlListBean accessControlListBean : accessControlListBeans) {
            Integer projectID = accessControlListBean.getProjectID();
            Integer roleID = accessControlListBean.getRoleID();
            allPersonRolesSet.add(roleID);
            Set<Integer> rolesInProject = projectsToRolesMap.get(projectID);
            if (rolesInProject == null) {
                rolesInProject = new HashSet<Integer>();
                projectsToRolesMap.put(projectID, rolesInProject);
            }
            rolesInProject.add(roleID);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(accessControlListBeans.size() + " assignments found for person " + personID + ": "
                    + allPersonRolesSet.size() + " roles " + " in " + projectsToRolesMap.size() + " projects ");
        }
    } else {
        return new LinkedList<TListTypeBean>();
    }
    //gets the itemType assignments for the assigned roles 
    Map<Integer, Set<Integer>> roleToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    List<TRoleListTypeBean> itemTypesInRoles = RoleBL
            .loadByRoles(GeneralUtils.createIntegerListFromCollection(allPersonRolesSet));
    if (itemTypesInRoles != null) {
        for (TRoleListTypeBean roleListTypeBean : itemTypesInRoles) {
            Integer roleID = roleListTypeBean.getRole();
            Integer itemTypeID = roleListTypeBean.getListType();
            Set<Integer> itemTypesInRoleSet = roleToItemTypesMap.get(roleID);
            if (itemTypesInRoleSet == null) {
                itemTypesInRoleSet = new HashSet<Integer>();
                roleToItemTypesMap.put(roleID, itemTypesInRoleSet);
            }
            itemTypesInRoleSet.add(itemTypeID);
        }
    }
    Set<Integer> projectSet = projectsToRolesMap.keySet();
    if (projectSet.isEmpty()) {
        LOGGER.info("No project assignment for person " + personID);
        return new LinkedList<TListTypeBean>();
    }
    //gets the project to projectType map
    List<TProjectBean> projectList = ProjectBL
            .loadByProjectIDs(GeneralUtils.createIntegerListFromCollection(projectSet));
    Map<Integer, Integer> projectToProjectTypeMap = new HashMap<Integer, Integer>();
    Set<Integer> projectTypesSet = new HashSet<Integer>();
    for (TProjectBean projectBean : projectList) {
        Integer projectTypeID = projectBean.getProjectType();
        projectToProjectTypeMap.put(projectBean.getObjectID(), projectTypeID);
        projectTypesSet.add(projectTypeID);
    }
    //gets the item type assignments for project types
    List<TPlistTypeBean> plistTypes = loadByProjectTypes(projectTypesSet.toArray());
    Map<Integer, Set<Integer>> projectTypeToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    if (plistTypes != null) {
        for (TPlistTypeBean plistTypeBean : plistTypes) {
            Integer projectTypeID = plistTypeBean.getProjectType();
            Integer itemTypeID = plistTypeBean.getCategory();
            Set<Integer> itemTypesSet = projectTypeToItemTypesMap.get(projectTypeID);
            if (itemTypesSet == null) {
                itemTypesSet = new HashSet<Integer>();
                projectTypeToItemTypesMap.put(projectTypeID, itemTypesSet);
            }
            itemTypesSet.add(itemTypeID);
        }
    }
    Set<Integer> allowedItemTypeIDs = new HashSet<Integer>();
    List<TListTypeBean> allSelectableitemTypeBeans = IssueTypeBL.loadAllSelectable(locale);
    Set<Integer> allSelectableItemTypeIDs = GeneralUtils
            .createIntegerSetFromBeanList(allSelectableitemTypeBeans);
    for (Map.Entry<Integer, Set<Integer>> rolesInProjectEntry : projectsToRolesMap.entrySet()) {
        Integer projectID = rolesInProjectEntry.getKey();
        Set<Integer> roleIDs = rolesInProjectEntry.getValue();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(roleIDs.size() + " roles found in project " + projectID);
        }
        Integer projectTypeID = projectToProjectTypeMap.get(projectID);
        Set<Integer> projectTypeLimitedItemTypes = projectTypeToItemTypesMap.get(projectTypeID);
        Set<Integer> rolesLimitedItemTypes = new HashSet<Integer>();
        //get the item types limited in all roles
        for (Integer roleID : roleIDs) {
            Set<Integer> roleLimitedItemTypes = roleToItemTypesMap.get(roleID);
            if (roleLimitedItemTypes != null) {
                rolesLimitedItemTypes.addAll(roleLimitedItemTypes);
            } else {
                //at least one role has no item type limitations
                rolesLimitedItemTypes.clear();
                break;
            }
        }
        if ((projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty())
                && rolesLimitedItemTypes.isEmpty()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No roles or project type specific limitation found for project " + projectID);
            }
            return allSelectableitemTypeBeans;
        } else {
            if (projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Add role specific item type limitations for project " + projectID);
                }
                allowedItemTypeIDs.addAll(rolesLimitedItemTypes);
            } else {
                if (rolesLimitedItemTypes.isEmpty()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "Add project type specific item type limitations for project " + projectID);
                    }
                    allowedItemTypeIDs.addAll(projectTypeLimitedItemTypes);
                } else {
                    Collection<Integer> intersection = CollectionUtils.intersection(projectTypeLimitedItemTypes,
                            rolesLimitedItemTypes);
                    if (intersection != null) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug(
                                    "Add project type specific and role specific item type limitations for project "
                                            + projectID);
                        }
                        allowedItemTypeIDs.addAll(intersection);
                    }
                }
            }
        }
    }
    allowedItemTypeIDs.retainAll(allSelectableItemTypeIDs);
    if (allowedItemTypeIDs.isEmpty()) {
        return new LinkedList<TListTypeBean>();
    } else {
        return LocalizeUtil.localizeDropDownList(
                loadByIssueTypeIDs(GeneralUtils.createIntegerListFromCollection(allowedItemTypeIDs)), locale);
    }
}

From source file:edu.internet2.middleware.changelogconsumer.googleapps.GoogleAppsFullSync.java

private void processMatchedGroups(boolean dryRun, Collection<ComparableGroupItem> matchedGroups) {
    for (ComparableGroupItem item : matchedGroups) {
        LOG.info("Google Apps Consumer '{}' Full Sync - examining matched group: {} ({})",
                new Object[] { consumerName, item.getGrouperGroup().getName(), item });

        Group gooGroup = null;//from  w  ww .ja  v  a  2s. c  om
        try {
            gooGroup = connector.fetchGooGroup(item.getName());
        } catch (IOException e) {
            LOG.error("Google Apps Consume '{}' Full Sync - Error fetching matched group ({}): {}",
                    new Object[] { consumerName, item.getName(), e.getMessage() });
        }
        boolean updated = false;

        if (gooGroup == null) {
            LOG.error(
                    "Google Apps Consume '{}' Full Sync - Error fetching matched group ({}); it disappeared during processing.",
                    new Object[] { consumerName, item.getName() });
        } else {

            if (!item.getGrouperGroup().getDescription().equalsIgnoreCase(gooGroup.getDescription())) {
                if (!dryRun) {
                    gooGroup.setDescription(item.getGrouperGroup().getDescription());
                    updated = true;
                }
            }

            if (!item.getGrouperGroup().getDisplayExtension().equalsIgnoreCase(gooGroup.getName())) {
                if (!dryRun) {
                    gooGroup.setName(item.getGrouperGroup().getDisplayExtension());
                    updated = true;
                }
            }

            if (updated) {
                try {
                    connector.updateGooGroup(item.getName(), gooGroup);
                } catch (IOException e) {
                    LOG.error("Google Apps Consume '{}' Full Sync - Error updating matched group ({}): {}",
                            new Object[] { consumerName, item.getName(), e.getMessage() });
                }
            }

            //Retrieve Membership
            ArrayList<ComparableMemberItem> grouperMembers = new ArrayList<ComparableMemberItem>();
            for (edu.internet2.middleware.grouper.Member member : item.getGrouperGroup().getMembers()) {
                if (member.getSubjectType() == SubjectTypeEnum.PERSON) {
                    grouperMembers.add(new ComparableMemberItem(
                            connector.getAddressFormatter().qualifySubjectAddress(member.getSubjectId()),
                            member));
                }
            }

            ArrayList<ComparableMemberItem> googleMembers = new ArrayList<ComparableMemberItem>();
            List<Member> memberList = null;

            try {
                memberList = connector.getGooMembership(item.getName());
            } catch (IOException e) {
                LOG.error(
                        "Google Apps Consume '{}' Full Sync - Error fetching membership list for group({}): {}",
                        new Object[] { consumerName, item.getName(), e.getMessage() });
            }

            if (memberList == null) {
                LOG.error(
                        "Google Apps Consume '{}' Full Sync - Error fetching membership list for group ({}); it's null",
                        new Object[] { consumerName, item.getName() });

            } else {
                for (Member member : memberList) {
                    googleMembers.add(new ComparableMemberItem(member.getEmail()));
                }

                Collection<ComparableMemberItem> extraMembers = CollectionUtils.subtract(googleMembers,
                        grouperMembers);
                if (!properties.shouldIgnoreExtraGoogleMembers()) {
                    processExtraGroupMembers(item, extraMembers, dryRun);
                }

                Collection<ComparableMemberItem> missingMembers = CollectionUtils.subtract(grouperMembers,
                        googleMembers);
                processMissingGroupMembers(item, missingMembers, gooGroup, dryRun);

                Collection<ComparableMemberItem> matchedMembers = CollectionUtils.intersection(grouperMembers,
                        googleMembers);
                processMatchedGroupMembers(item, matchedMembers, dryRun);
            }
        }
    }
}

From source file:fr.paris.lutece.plugins.directory.service.directorysearch.DirectorySearchService.java

/**
 * Return a list of record key return by the search
 * @param directory the directory//from www  .j  a  v a2s  .  c  om
 * @param mapSearch a map which contains for each entry the list of
 *            recorField(value of field search) associate
 * @param dateCreation the creation date
 * @param dateCreationBegin the date begin to search for the creation date
 * @param dateCreationEnd the date end to search for the creation date
 * @param dateModification the modification date
 * @param dateModificationBegin the date begin to search for the
 *            modification date
 * @param dateModificationEnd the date end to search for the modification
 *            date
 * @param filter the filter
 * @param plugin the plugin
 * @return a list of record key return by the search
 */
public List<Integer> getSearchResults(Directory directory, HashMap<String, List<RecordField>> mapSearch,
        Date dateCreation, Date dateCreationBegin, Date dateCreationEnd, Date dateModification,
        Date dateModificationBegin, Date dateModificationEnd, RecordFieldFilter filter, Plugin plugin) {
    List<Integer> listRecordResult = new ArrayList<Integer>();

    IRecordService recordService = SpringContextService.getBean(RecordService.BEAN_SERVICE);
    listRecordResult = recordService.getListRecordId(filter, plugin);

    if (mapSearch != null) {
        List<Integer> listRecordResultTmp = null;
        List<RecordField> recordFieldSearch;
        HashMap<String, Object> mapSearchItemEntry;
        boolean bSearchRecordEmpty;
        boolean bSearchEmpty;

        try {
            _searcher = new IndexSearcher(DirectoryReader.open(_luceneDirectory));

            IDirectorySearchEngine engine = SpringContextService.getBean(BEAN_SEARCH_ENGINE);

            listRecordResultTmp = new ArrayList<Integer>();
            bSearchEmpty = true;

            for (Object entryMapSearch : mapSearch.entrySet()) {
                recordFieldSearch = ((Entry<String, List<RecordField>>) entryMapSearch).getValue();

                int nIdEntry = DirectoryUtils
                        .convertStringToInt(((Entry<String, List<RecordField>>) entryMapSearch).getKey());
                bSearchRecordEmpty = true;

                if (recordFieldSearch != null) {
                    mapSearchItemEntry = new HashMap<String, Object>();

                    boolean bIsArray = false;
                    boolean bFirstRecord = true;

                    for (RecordField recordField : recordFieldSearch) {
                        if (recordField.getEntry() instanceof EntryTypeArray) {
                            // for array, we do a search on content for each case
                            bIsArray = true;
                            mapSearchItemEntry = new HashMap<String, Object>();
                            recordField.getEntry().addSearchCriteria(mapSearchItemEntry, recordField);

                            if (mapSearchItemEntry.size() > 0) {
                                bSearchRecordEmpty = false;
                                bSearchEmpty = false;
                                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY,
                                        directory.getIdDirectory());
                                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY_ENTRY, nIdEntry);

                                List<Integer> ids = engine.getSearchResults(mapSearchItemEntry);

                                if (CollectionUtils.isEmpty(ids)) {
                                    listRecordResultTmp = new ArrayList<Integer>();

                                    break;
                                } else if (bFirstRecord) {
                                    listRecordResultTmp = ids;
                                    bFirstRecord = false;
                                } else {
                                    listRecordResultTmp = (List<Integer>) CollectionUtils
                                            .intersection(listRecordResultTmp, ids);
                                }
                            }
                        } else {
                            recordField.getEntry().addSearchCriteria(mapSearchItemEntry, recordField);
                        }
                    }

                    if (!bIsArray && (mapSearchItemEntry.size() > 0)) {
                        bSearchRecordEmpty = false;
                        bSearchEmpty = false;
                        mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY,
                                directory.getIdDirectory());
                        mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY_ENTRY, nIdEntry);
                        listRecordResultTmp.addAll(engine.getSearchResults(mapSearchItemEntry));
                    }

                    if (!bSearchRecordEmpty && !directory.isSearchOperatorOr()) {
                        // keeping order is important for display
                        listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                                listRecordResultTmp);
                        listRecordResultTmp = new ArrayList<Integer>();
                    }
                }
            }

            if (directory.isSearchOperatorOr() && !bSearchEmpty) {
                listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                        listRecordResultTmp);
            }

            //date creation of a record
            if (dateCreation != null) {
                listRecordResultTmp = new ArrayList<Integer>();
                mapSearchItemEntry = new HashMap<String, Object>();
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY, directory.getIdDirectory());
                dateCreation.setTime(dateCreation.getTime() + CONSTANT_TIME_CORRECTION);

                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_CREATION, dateCreation);
                listRecordResultTmp.addAll(engine.getSearchResults(mapSearchItemEntry));

                // keeping order is important for display
                listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                        listRecordResultTmp);
            } else if ((dateCreationBegin != null) && (dateCreationEnd != null)) {
                dateCreationBegin.setTime(dateCreationBegin.getTime() + CONSTANT_TIME_CORRECTION);
                dateCreationEnd.setTime(dateCreationEnd.getTime() + CONSTANT_TIME_CORRECTION);

                listRecordResultTmp = new ArrayList<Integer>();
                mapSearchItemEntry = new HashMap<String, Object>();
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY, directory.getIdDirectory());
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_CREATION_BEGIN, dateCreationBegin);
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_CREATION_END, dateCreationEnd);
                listRecordResultTmp.addAll(engine.getSearchResults(mapSearchItemEntry));

                // keeping order is important for display
                listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                        listRecordResultTmp);
            }

            //date modification of a record
            if (dateModification != null) {
                listRecordResultTmp = new ArrayList<Integer>();
                mapSearchItemEntry = new HashMap<String, Object>();
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY, directory.getIdDirectory());
                dateModification.setTime(dateModification.getTime() + CONSTANT_TIME_CORRECTION);

                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_MODIFICATION, dateModification);
                listRecordResultTmp.addAll(engine.getSearchResults(mapSearchItemEntry));

                // keeping order is important for display
                listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                        listRecordResultTmp);
            } else if ((dateModificationBegin != null) && (dateModificationEnd != null)) {
                dateModificationBegin.setTime(dateModificationBegin.getTime() + CONSTANT_TIME_CORRECTION);
                dateModificationEnd.setTime(dateModificationEnd.getTime() + CONSTANT_TIME_CORRECTION);

                listRecordResultTmp = new ArrayList<Integer>();
                mapSearchItemEntry = new HashMap<String, Object>();
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_ID_DIRECTORY, directory.getIdDirectory());
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_MODIFICATION_BEGIN,
                        dateModificationBegin);
                mapSearchItemEntry.put(DirectorySearchItem.FIELD_DATE_MODIFICATION_END, dateModificationEnd);
                listRecordResultTmp.addAll(engine.getSearchResults(mapSearchItemEntry));

                // keeping order is important for display
                listRecordResult = DirectoryUtils.retainAllIdsKeepingFirstOrder(listRecordResult,
                        listRecordResultTmp);
            }
        } catch (Exception e) {
            AppLogService.error(e.getMessage(), e);
            // If an error occurred clean result list
            listRecordResult = new ArrayList<Integer>();
        }
    }

    return listRecordResult;
}

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

@SuppressWarnings("unchecked")
public Map<Protein, Map<String, PromiscuityCount<?>>> allAssayCountPerProtein(
        Map<String, PromiscuityCount<?>> countMap, Map<Protein, List<Long>> proteinAIDMap) {
    Map<Protein, Map<String, PromiscuityCount<?>>> perProteinPromiscuityCountMap = new HashMap<Protein, Map<String, PromiscuityCount<?>>>();

    PromiscuityCount<Protein> proteinCount = (PromiscuityCount<Protein>) countMap.get(allProteinsName);
    if (proteinCount != null) {
        List<Protein> totalProteins = proteinCount.getTotal();
        PromiscuityCount<Long> allAssayCount = (PromiscuityCount<Long>) countMap.get(allAssayName);
        if (allAssayCount != null) {
            List<Long> allAssays = allAssayCount.getTotal();
            List<Long> activeAssays = allAssayCount.getActive();

            for (Protein protein : totalProteins) {
                List<Long> activeAIDsPerProtein = new ArrayList<Long>();
                List<Long> totalAIDsPerProtein = new ArrayList<Long>();
                Map<String, PromiscuityCount<?>> promiscuityCountMap = new HashMap<String, PromiscuityCount<?>>();
                List<Long> aids = proteinAIDMap.get(protein);
                activeAIDsPerProtein = (List<Long>) CollectionUtils.intersection(activeAssays, aids);
                totalAIDsPerProtein = (List<Long>) CollectionUtils.intersection(allAssays, aids);
                PromiscuityCount<Long> count = new PromiscuityCount<Long>(allAssayName, activeAIDsPerProtein,
                        totalAIDsPerProtein);
                promiscuityCountMap.put(count.getName(), count);
                perProteinPromiscuityCountMap.put(protein, promiscuityCountMap);
            }//  w  ww .j av a 2s  .c om
        }
    }
    return perProteinPromiscuityCountMap;
}

From source file:expansionBlocks.ProcessCommunities.java

private static void printTopologicalExtension(Query query, Map<Entity, Double> community)
        throws FileNotFoundException, UnsupportedEncodingException {

    File theDir = new File("images");
    if (!theDir.exists()) {
        boolean result = theDir.mkdir();
    }/* w w w . j a v a2 s  .co  m*/

    PrintWriter writer = FileManagement.Writer
            .getWriter("images/" + query.getId() + "TopologicalCommunity.txt");

    writer.println("strict digraph G{");
    Set<Entity> entitySet = community.keySet();
    Set<Long> categoriesSet = new HashSet<>();
    for (Entity e : entitySet) {
        categoriesSet.addAll(Article.getCategories(e.getId()));
    }
    Map<Long, Double> categoryWeightMap = new HashMap<>();
    Double maxW = 0.0;
    for (Entity entity : entitySet) {
        Long entityID = entity.getId();

        maxW = maxW < community.get(entityID) ? community.get(entityID) : maxW;

        Set<Long> neighbors = Article.getNeighbors(entityID, Graph.EDGES_OUT);
        Collection<Long> intersection = CollectionUtils.intersection(neighbors, entitySet);
        for (Long neighbourID : intersection) {
            if (!Article.isARedirect(entityID) && !Article.isARedirect(neighbourID)) {
                writer.println(entityID + " -> " + neighbourID + " [color=red];");
            }

        }

        Set<Long> categories = Article.getCategories(entityID);
        for (Long categoryID : categories) {
            writer.println(entityID + " -> " + categoryID + " [color=green];");
            Double w = categoryWeightMap.put(categoryID, community.get(entityID));
            if (w != null && w > community.get(entityID))
                categoryWeightMap.put(categoryID, w);

        }

        Set<Long> redirects = Article.getRedirections(entityID);
        /*
         for (Long redirectID : redirects)
         {
         if (!Article.isARedirect(articleID))
         {
         }
         }*/

    }
    for (Long categoryID : categoriesSet) {
        Set<Long> neighbors = Category.getNeigbors(categoryID, Graph.EDGES_OUT);
        Collection<Long> intersection = CollectionUtils.intersection(neighbors, categoriesSet);
        for (Long neighbourID : intersection) {
            writer.println(categoryID + " -> " + neighbourID + " [color=blue];");
        }
        neighbors = Category.getNeigbors(categoryID, Graph.EDGES_IN);
        intersection = CollectionUtils.intersection(neighbors, categoriesSet);
        for (Long neighbourID : intersection) {
            writer.println(neighbourID + " -> " + categoryID + " [color=blue];");
        }

    }

    for (Entity entity : entitySet) {
        String title = entity.getName();
        title = Normalizer.normalize(title, Normalizer.NFD);
        title = title.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
        title = title.replaceAll("[.]+", " ");

        //writer.println(id + "[label=\"" + title + "\"];");
        //         String  weight =  new BigDecimal(community.get(id)*10).toPlainString();
        BigDecimal weightDouble = new BigDecimal(2 / maxW * community.get(entity) + .5);
        String weight = weightDouble.toPlainString();
        writer.println(entity + "[label=\"" + title + "\", width=" + weight + ", height=" + weight
                + " fixedsize=true,style=filled,color=\"#c0c0c0\"];");
    }
    for (Long id : categoriesSet) {
        String title = (new Category(id)).getName();
        title = Normalizer.normalize(title, Normalizer.NFD);
        title = title.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
        title = title.replaceAll("[.]+", " ");

        BigDecimal weightDouble = new BigDecimal(2 / maxW * categoryWeightMap.get(id) + .5);
        String weight = weightDouble.toPlainString();
        writer.println(id + "[label=\"" + title + "\", width=" + weight + ", height=" + weight
                + " fixedsize=true,style=filled,color=\"#f0f0f0\"];");
    }

    writer.println("}");
    writer.close();

}

From source file:edu.psu.iam.cpr.core.api.helper.FindPersonHelper.java

/**
 * Do a match using an open source algorithm.
 * @param serviceCoreReturn contains the service core return object.
 * @param requestedBy contains the user who requested the search.
 * @param psuId penn state id.// w ww  . ja v  a  2  s  . com
 * @param userId userid.
 * @param ssn contains the social security number.
 * @param firstName contains the first name.
 * @param lastName contains the last name.
  * @param middleName contains the middle name(s).
 * @param address1 contains the address line #1.
 * @param address2 contains the address line #2.
 * @param address3 contains the address line #3.
 * @param city contains the city.
 * @param state contains the state.
 * @param postalCode contains the postal code.
 * @param plus4 contains the plus4 postal code.
 * @param country contains the country.
 * @param dateOfBirth contains the dob.
 * @param gender contains the gender.
 * @param rankCutOff contains the rank cutoff - penn state only.
 * @return will a return a find person service return object if successful.
 * @throws GeneralDatabaseException will be thrown if there is a general database problem.
 * @throws CprException will be thrown if there is a cpr specific problem.
 * @throws ParseException 
 */
@SuppressWarnings("unchecked")
public FindPersonServiceReturn doSearchForPersonOS(final ServiceCoreReturn serviceCoreReturn,
        final String requestedBy, final String psuId, final String userId, final String ssn,
        final String firstName, final String lastName, final String middleName, final String address1,
        final String address2, final String address3, final String city, final String state,
        final String postalCode, final String plus4, final String country, final String dateOfBirth,
        final String gender, final String rankCutOff) throws CprException, ParseException {

    String localSSN = (ssn != null) ? ssn.trim() : null;
    String localUserid = (userId != null) ? userId.trim() : null;
    String localFirstName = (firstName != null) ? firstName.trim() : null;
    String localLastName = (lastName != null) ? lastName.trim() : null;
    String localDateOfBirth = (dateOfBirth != null) ? dateOfBirth.trim() : null;
    String localCity = (city != null) ? city.trim() : null;

    if (localSSN != null && localSSN.length() > 0) {
        LOG4J_LOGGER.debug("SearchForPerson: found ssn parm = " + localSSN);
        if (ValidateSSN.validateSSN(localSSN)) {
            localSSN = ValidateSSN.extractNumericSSN(localSSN);
            LOG4J_LOGGER.debug("SearchForPerson: found valid ssn = " + localSSN);
        } else {
            LOG4J_LOGGER.debug("SearchForPerson: found invalid ssn = " + localSSN);
            return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                    "Invalid value was specified for the SSN.");
        }
    }

    if (localFirstName == null || localFirstName.length() == 0) {
        LOG4J_LOGGER.debug("SearchForPerson: found invalid first name = " + localFirstName);
        return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                "First name must contain a value.");
    }

    if (localLastName == null || localLastName.length() == 0) {
        LOG4J_LOGGER.debug("SearchForPerson: found invalid last name = " + localLastName);
        return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                "Last name must contain a value.");
    }

    if (localDateOfBirth == null || localDateOfBirth.length() == 0) {
        LOG4J_LOGGER.debug("SearchForPerson: no date of birth entered");
        return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                "A date of birth must be entered.");
    }

    if (localCity == null || localCity.length() == 0) {
        LOG4J_LOGGER.debug("SearchForPerson: no city entered");
        return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                "A city must be entered.");
    }

    else {
        String numericDateOfBirth = localDateOfBirth;
        // Take care of MM/DD and MM/DD/YYYY cases.
        if (localDateOfBirth.length() == MMDD_FORMATTED || localDateOfBirth.length() == MMDDYYYY_FORMATTED) {
            // If the DOB has a dash in it, replace it with a slash.
            localDateOfBirth = localDateOfBirth.replace('-', '/');
            // Attempt to validate the DOB.
            if (!ValidateDateOfBirth.isDateOfBirthValid(localDateOfBirth)) {
                LOG4J_LOGGER.debug("SearchForPerson: found invalid date of birth = " + localDateOfBirth);
                return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                        "An invalid date of birth was entered.");
            }

            // Extract a character representation of the date of birth.
            numericDateOfBirth = DateOfBirthTable.toDobChar(localDateOfBirth);
            LOG4J_LOGGER.debug(
                    "SearchForPerson: converting date of birth to a numeric string " + numericDateOfBirth);
        }
        // Verify that the resultant DOB is exactly 8 characters.
        LOG4J_LOGGER.debug("SearchForPerson: Verify that DOB is exactly 8 characters.");
        if (numericDateOfBirth.length() != MMDDYYYY) {
            LOG4J_LOGGER.debug("SearchForPerson: found invalid date of birth = " + localDateOfBirth);
            return new FindPersonServiceReturn(ReturnType.INVALID_PARAMETERS_EXCEPTION.index(),
                    "An invalid date of birth was entered.");
        } else {
            LOG4J_LOGGER.debug("SearchForPerson: found valid date of birth = " + localDateOfBirth);
        }
    }

    // Get the list of matching person ids for the name.  We are doing a simple exact match.
    List<Long> nameMatch = new ArrayList<Long>();
    if (localLastName != null) {

        // We are doing a query for names with history.
        Session session = db.getSession();
        String sqlQuery = "select distinct personId from Names where upper(lastName)=:last_name AND upper(firstName)=:first_name";
        Query query = session.createQuery(sqlQuery);
        query.setParameter("last_name", localLastName.toUpperCase());
        query.setParameter("first_name", localFirstName.toUpperCase());
        for (Iterator<?> it = query.list().iterator(); it.hasNext();) {
            Long personIdValue = (Long) it.next();
            nameMatch.add(personIdValue);
        }
    }

    // Get the list of matches for the SSN.
    List<Long> ssnMatch = new ArrayList<Long>();
    if (localSSN != null) {

        // Need to find the key that is associated with the SSN person identifier.
        Map<String, Object> map = DBTypes.INSTANCE.getTypeMaps(DBTypes.IDENTIFIER_TYPE);
        IdentifierType identifierType = null;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            identifierType = (IdentifierType) entry.getValue();
            if (identifierType.getTypeName().equals(Database.SSN_IDENTIFIER)) {
                break;
            }
        }

        // Do a query for the active person identifier.
        Session session = db.getSession();
        String sqlQuery = "select distinct personId from PersonIdentifier where typeKey = :type_key AND identifierValue = :identifier_value AND endDate is null";
        Query query = session.createQuery(sqlQuery);
        query.setParameter("type_key", identifierType.getTypeKey());
        query.setParameter("identifier_value", localSSN);
        for (Iterator<?> it = query.list().iterator(); it.hasNext();) {
            Long personIdValue = (Long) it.next();
            ssnMatch.add(personIdValue);
        }
    }

    // Get the list of matches for the userid.
    List<Long> useridMatch = new ArrayList<Long>();
    if (localUserid != null) {
        Session session = db.getSession();
        String sqlQuery = "select distinct personId from Userid where userid = :userid";
        Query query = session.createQuery(sqlQuery);
        query.setParameter("userid", localUserid);
        for (Iterator<?> it = query.list().iterator(); it.hasNext();) {
            Long personIdValue = (Long) it.next();
            useridMatch.add(personIdValue);
        }
    }

    // Get the list of matches for the city.
    List<Long> cityMatch = new ArrayList<Long>();
    if (localCity != null) {
        Session session = db.getSession();
        String sqlQuery = "select distinct personId from Addresses where upper(city) = :city";
        Query query = session.createQuery(sqlQuery);
        query.setParameter("city", localCity.toUpperCase());
        for (Iterator<?> it = query.list().iterator(); it.hasNext();) {
            Long personIdValue = (Long) it.next();
            cityMatch.add(personIdValue);
        }
    }

    // Check name, SSN, and DOB, has to be an exact match of a single record.
    if (localSSN != null) {
        List<Long> finalMatch = new ArrayList<Long>();
        finalMatch = (List<Long>) CollectionUtils.intersection(nameMatch, ssnMatch);

        if (finalMatch.size() == 1) {

            setPersonId(finalMatch.get(0));

            // Verify that the DOB matches.
            if (matchDOBInCPR(localDateOfBirth)) {
                LOG4J_LOGGER.info("SearchForPerson: match by ssn successful");
                FindPersonServiceReturn findPersonReturn = new FindPersonServiceReturn(
                        ReturnType.SUCCESS.index(), "SUCCESS");
                findPersonReturn.setMatchingMethod(MatchType.SSN.toString());
                findPersonReturn.setPersonID(getPersonId());
                findPersonReturn.setPsuID(null);
                findPersonReturn.setUserId(getPrimaryUserIdFromCPR());
                return findPersonReturn;
            }
        }
    }

    // Check name, userid and DOB, has to be a single match of one record.
    if (localUserid != null) {
        List<Long> finalMatch = new ArrayList<Long>();
        finalMatch = (List<Long>) CollectionUtils.intersection(nameMatch, useridMatch);
        if (finalMatch.size() == 1) {

            setPersonId(finalMatch.get(0));

            // Verify that the DOB matches.
            if (matchDOBInCPR(localDateOfBirth)) {
                // Log a success!
                LOG4J_LOGGER.info("SearchForPerson: match by user id successful");
                FindPersonServiceReturn findPersonReturn = new FindPersonServiceReturn(
                        ReturnType.SUCCESS.index(), "SUCCESS");
                findPersonReturn.setMatchingMethod(MatchType.USERID.toString());
                findPersonReturn.setPersonID(getPersonId());
                findPersonReturn.setPsuID(null);
                findPersonReturn.setUserId(getPrimaryUserIdFromCPR());

                return findPersonReturn;
            }
        }
    }

    // Check name, city and DOB.
    if (localCity != null) {
        List<Long> finalMatch = new ArrayList<Long>();
        finalMatch = (List<Long>) CollectionUtils.intersection(nameMatch, cityMatch);
        for (Iterator<Long> it = finalMatch.iterator(); it.hasNext();) {
            setPersonId(it.next());

            // Verify that the DOB matches.
            if (matchDOBInCPR(localDateOfBirth)) {

                // Log a success!
                LOG4J_LOGGER.info("SearchForPerson: match by city successful");
                FindPersonServiceReturn findPersonReturn = new FindPersonServiceReturn(
                        ReturnType.SUCCESS.index(), "SUCCESS");
                findPersonReturn.setMatchingMethod(MatchType.CITY.toString());
                findPersonReturn.setPersonID(getPersonId());
                findPersonReturn.setPsuID(null);
                findPersonReturn.setUserId(getPrimaryUserIdFromCPR());

                return findPersonReturn;
            }
        }

    }

    // No match was found.
    FindPersonServiceReturn findPersonReturn = new FindPersonServiceReturn(
            ReturnType.PERSON_NOT_FOUND_EXCEPTION.index(), "FAILURE");
    findPersonReturn.setMatchingMethod(MatchType.NO_MATCH.toString());
    return findPersonReturn;
}