View Javadoc

1   /**
2    * Copyright 2005-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.kim.impl.role;
17  
18  import org.apache.commons.collections.CollectionUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.apache.ojb.broker.query.Criteria;
21  import org.apache.ojb.broker.query.Query;
22  import org.apache.ojb.broker.query.QueryFactory;
23  import org.apache.ojb.broker.query.ReportQueryByCriteria;
24  import org.joda.time.DateTime;
25  import org.kuali.rice.core.api.criteria.Predicate;
26  import org.kuali.rice.core.api.criteria.PredicateFactory;
27  import org.kuali.rice.core.api.criteria.PredicateUtils;
28  import org.kuali.rice.core.api.criteria.QueryByCriteria;
29  import org.kuali.rice.core.api.membership.MemberType;
30  import org.kuali.rice.core.framework.persistence.ojb.dao.PlatformAwareDaoBaseOjb;
31  import org.kuali.rice.kim.api.KimConstants;
32  import org.kuali.rice.kim.api.group.GroupMember;
33  import org.kuali.rice.kim.api.identity.entity.EntityDefault;
34  import org.kuali.rice.kim.api.identity.principal.Principal;
35  import org.kuali.rice.kim.api.permission.Permission;
36  import org.kuali.rice.kim.api.responsibility.Responsibility;
37  import org.kuali.rice.kim.api.responsibility.ResponsibilityQueryResults;
38  import org.kuali.rice.kim.api.responsibility.ResponsibilityService;
39  import org.kuali.rice.kim.api.role.Role;
40  import org.kuali.rice.kim.api.role.RoleMember;
41  import org.kuali.rice.kim.api.role.RoleMembership;
42  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
43  import org.kuali.rice.kim.impl.KIMPropertyConstants;
44  import org.kuali.rice.kim.impl.common.delegate.DelegateTypeBo;
45  import org.kuali.rice.kim.impl.common.delegate.DelegateMemberBo;
46  
47  import java.sql.Timestamp;
48  import java.util.ArrayList;
49  import java.util.Collection;
50  import java.util.HashMap;
51  import java.util.List;
52  import java.util.Map;
53  import java.util.Map.Entry;
54  
55  import static org.kuali.rice.core.api.criteria.PredicateFactory.*;
56  
57  public class RoleDaoOjb extends PlatformAwareDaoBaseOjb implements RoleDao {
58      /**
59       * Adds SubCriteria to the Query Criteria using the role qualification passed in
60       *
61       * @param c             The Query Criteria object to be used
62       * @param qualification The role qualification
63       */
64      private void addSubCriteriaBasedOnRoleQualification(Criteria c, Map<String, String> qualification) {
65          if (qualification != null && CollectionUtils.isNotEmpty(qualification.keySet())) {
66              for (Map.Entry<String, String> qualifier : qualification.entrySet()) {
67                  Criteria subCrit = new Criteria();
68                  if (StringUtils.isNotEmpty(qualifier.getValue())) {
69                      String value = (qualifier.getValue()).replace('*', '%');
70                      subCrit.addLike("attributeValue", value);
71                      subCrit.addEqualTo("kimAttributeId", qualifier.getKey());
72                      subCrit.addEqualToField("assignedToId", Criteria.PARENT_QUERY_PREFIX + "id");
73                      ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(RoleMemberAttributeDataBo.class, subCrit);
74                      c.addExists(subQuery);
75                  }
76              }
77          }
78      }
79  
80      public List<RoleMemberBo> getRoleMembersForGroupIds(String roleId, List<String> groupIds) {
81          Criteria crit = new Criteria();
82          crit.addEqualTo(KIMPropertyConstants.RoleMember.ROLE_ID, roleId);
83          crit.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode());
84          crit.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, groupIds);
85          Query query = QueryFactory.newQuery(RoleMemberBo.class, crit);
86          Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
87          List<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
88          for (RoleMemberBo rm : coll) {
89              if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
90                  results.add(rm);
91              }
92          }
93          return results;
94      }
95  
96      @SuppressWarnings("unchecked")
97      public List<RoleMemberBo> getRolePrincipalsForPrincipalIdAndRoleIds(Collection<String> roleIds, String principalId, Map<String, String> qualification) {
98  
99          Criteria c = new Criteria();
100 
101         if (CollectionUtils.isNotEmpty(roleIds)) {
102             if (roleIds.size() == 1) {
103                 c.addEqualTo(KIMPropertyConstants.RoleMember.ROLE_ID, roleIds.iterator().next());
104             } else {
105             	c.addIn(KIMPropertyConstants.RoleMember.ROLE_ID, roleIds);
106             }
107         }
108         if (principalId != null) {
109             c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_ID, principalId);
110         }
111         c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode());
112         addSubCriteriaBasedOnRoleQualification(c, qualification);
113 
114         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
115         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
116         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
117         for (RoleMemberBo rm : coll) {
118             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
119                 results.add(rm);
120             }
121         }
122         return results;
123     }
124 
125     public List<GroupMember> getGroupPrincipalsForPrincipalIdAndGroupIds(Collection<String> groupIds, String principalId) {
126         List<String> groupIdValues = new ArrayList<String>();
127         List<GroupMember> groupPrincipals = new ArrayList<GroupMember>();
128         if (groupIds != null
129                 && principalId == null) {
130             groupIdValues = new ArrayList<String>(groupIds);
131         } else if (principalId != null) {
132             groupIdValues = KimApiServiceLocator.getGroupService().getGroupIdsByPrincipalId(principalId);
133         }
134         if (groupIdValues != null
135                 && groupIdValues.size() > 0) {
136             Collection<GroupMember> groupMembers = KimApiServiceLocator.getGroupService().getMembers(groupIdValues);
137             for (GroupMember groupMembershipInfo : groupMembers) {
138                 if (principalId != null) {
139                     if (MemberType.PRINCIPAL.equals(groupMembershipInfo.getType())
140                             && StringUtils.equals(principalId, groupMembershipInfo.getMemberId())
141                             && groupMembershipInfo.isActive(new DateTime())) {
142                         groupPrincipals.add(groupMembershipInfo);
143                     }
144                 } else {
145                     groupPrincipals.add(groupMembershipInfo);
146                 }
147             }
148         }
149         return groupPrincipals;
150     }
151 
152     public List<GroupMember> getGroupMembers(Collection<String> groupIds) {
153         List<GroupMember> groupMembers = new ArrayList<GroupMember>();
154         if (groupIds != null) {
155             List<String> groupIdValues = new ArrayList<String>(groupIds);
156 
157             if (groupIdValues.size() > 0) {
158 
159                 Collection<GroupMember> groupMemberships = KimApiServiceLocator.getGroupService().getMembers(groupIdValues);
160 
161                 if (!CollectionUtils.isEmpty(groupMemberships)) {
162                     for (GroupMember groupMembershipInfo : groupMemberships) {
163                         if (MemberType.GROUP.equals(groupMembershipInfo.getType())
164                                 && groupMembershipInfo.isActive(new DateTime())) {
165                             groupMembers.add(groupMembershipInfo);
166                         }
167                     }
168                 }
169             }
170         }
171         return groupMembers;
172     }
173 
174     @SuppressWarnings("unchecked")
175     public List<RoleMemberBo> getRoleGroupsForGroupIdsAndRoleIds(Collection<String> roleIds, Collection<String> groupIds, Map<String, String> qualification) {
176         Criteria c = new Criteria();
177         if (roleIds != null && !roleIds.isEmpty()) {
178             c.addIn(KIMPropertyConstants.RoleMember.ROLE_ID, roleIds);
179         }
180         if (groupIds != null && !groupIds.isEmpty()) {
181             c.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, groupIds);
182         }
183         c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode());
184         addSubCriteriaBasedOnRoleQualification(c, qualification);
185 
186         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
187         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
188         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
189         for (RoleMemberBo rm : coll) {
190             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
191                 results.add(rm);
192             }
193         }
194         return results;
195     }
196 
197     @SuppressWarnings("unchecked")
198     public Map<String, DelegateTypeBo> getDelegationImplMapFromRoleIds(Collection<String> roleIds) {
199         Map<String, DelegateTypeBo> results = new HashMap<String, DelegateTypeBo>();
200         if (CollectionUtils.isNotEmpty(roleIds)) {
201             Criteria c = new Criteria();
202             c.addIn(KIMPropertyConstants.Delegation.ROLE_ID, roleIds);
203             c.addEqualTo(KIMPropertyConstants.Delegation.ACTIVE, Boolean.TRUE);
204             Query query = QueryFactory.newQuery(DelegateTypeBo.class, c);
205             Collection<DelegateTypeBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
206             for (DelegateTypeBo delegateBo : coll) {
207                 results.put(delegateBo.getDelegationId(), delegateBo);
208             }
209         }
210         return results;
211     }
212 
213     @SuppressWarnings("unchecked")
214     public List<DelegateTypeBo> getDelegationBosForRoleIds(Collection<String> roleIds) {
215         List<DelegateTypeBo> results = new ArrayList<DelegateTypeBo>();
216         if (roleIds != null && !roleIds.isEmpty()) {
217             Criteria c = new Criteria();
218             c.addIn(KIMPropertyConstants.Delegation.ROLE_ID, roleIds);
219             c.addEqualTo(KIMPropertyConstants.Delegation.ACTIVE, Boolean.TRUE);
220             Query query = QueryFactory.newQuery(DelegateTypeBo.class, c);
221             Collection<DelegateTypeBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
222             for (DelegateTypeBo delegateBo : coll) {
223                 results.add(delegateBo);
224             }
225         }
226         return results;
227     }
228 
229     @SuppressWarnings("unchecked")
230     public List<DelegateMemberBo> getDelegationPrincipalsForPrincipalIdAndDelegationIds(
231             Collection<String> delegationIds, String principalId) {
232         Criteria c = new Criteria();
233 
234         if (principalId != null) {
235             c.addEqualTo(KIMPropertyConstants.DelegationMember.MEMBER_ID, principalId);
236         }
237         c.addEqualTo(KIMPropertyConstants.DelegationMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode());
238         if (delegationIds != null && !delegationIds.isEmpty()) {
239             c.addIn(KIMPropertyConstants.DelegationMember.DELEGATION_ID, delegationIds);
240         }
241         Query query = QueryFactory.newQuery(DelegateMemberBo.class, c);
242         Collection<DelegateMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
243         ArrayList<DelegateMemberBo> results = new ArrayList<DelegateMemberBo>(coll.size());
244         for (DelegateMemberBo rm : coll) {
245             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
246                 results.add(rm);
247             }
248         }
249         return results;
250     }
251 
252     @SuppressWarnings("unchecked")
253     public List<DelegateMemberBo> getDelegationGroupsForGroupIdsAndDelegationIds(
254             Collection<String> delegationIds, List<String> groupIds) {
255         Criteria c = new Criteria();
256         if (delegationIds != null && !delegationIds.isEmpty()) {
257             c.addIn(KIMPropertyConstants.DelegationMember.DELEGATION_ID, delegationIds);
258         }
259         if (groupIds != null && !groupIds.isEmpty()) {
260             c.addIn(KIMPropertyConstants.DelegationMember.MEMBER_ID, groupIds);
261         }
262         c.addEqualTo(KIMPropertyConstants.DelegationMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode());
263         Query query = QueryFactory.newQuery(DelegateMemberBo.class, c);
264         Collection<DelegateMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
265         ArrayList<DelegateMemberBo> results = new ArrayList<DelegateMemberBo>(coll.size());
266         for (DelegateMemberBo rm : coll) {
267             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
268                 results.add(rm);
269             }
270         }
271         return results;
272     }
273 
274     @SuppressWarnings("unchecked")
275     public List<RoleMemberBo> getRoleMembersForRoleIds(Collection<String> roleIds, String memberTypeCode, Map<String, String> qualification) {
276         Criteria c = new Criteria();
277 
278         if (roleIds != null && !roleIds.isEmpty()) {
279             c.addIn(KIMPropertyConstants.RoleMember.ROLE_ID, roleIds);
280         }
281         if (memberTypeCode != null) {
282             c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, memberTypeCode);
283         }
284         addSubCriteriaBasedOnRoleQualification(c, qualification);
285 
286         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
287         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
288         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
289         for (RoleMemberBo rm : coll) {
290             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
291                 results.add(rm);
292             }
293         }
294         return results;
295     }
296 
297     @SuppressWarnings("unchecked")
298     public List<RoleMemberBo> getRoleMembershipsForRoleIdsAsMembers(Collection<String> roleIds, Map<String, String> qualification) {
299         Criteria c = new Criteria();
300 
301         if (roleIds != null && !roleIds.isEmpty()) {
302             c.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, roleIds);
303         }
304         c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.ROLE.getCode());
305         addSubCriteriaBasedOnRoleQualification(c, qualification);
306 
307         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
308         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
309         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
310         for (RoleMemberBo rm : coll) {
311             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
312                 results.add(rm);
313             }
314         }
315         return results;
316     }
317 
318     @SuppressWarnings("unchecked")
319     public List<RoleMemberBo> getRoleMembershipsForMemberId(String memberType, String memberId, Map<String, String> qualification) {
320         Criteria c = new Criteria();
321         List<RoleMemberBo> parentRoleMembers = new ArrayList<RoleMemberBo>();
322 
323         if (StringUtils.isEmpty(memberId)
324                 || StringUtils.isEmpty(memberType)) {
325             return parentRoleMembers;
326         }
327 
328         c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_ID, memberId);
329         c.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, memberType);
330         addSubCriteriaBasedOnRoleQualification(c, qualification);
331 
332         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
333         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
334         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
335         for (RoleMemberBo rm : coll) {
336             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
337                 results.add(rm);
338             }
339         }
340         return results;
341     }
342 
343     @SuppressWarnings("unchecked")
344     public List<RoleMemberBo> getRoleMembersForRoleIdsWithFilters(Collection<String> roleIds, String principalId, Collection<String> groupIds, Map<String, String> qualification) {
345         Criteria c = new Criteria();
346 
347         if (roleIds != null && !roleIds.isEmpty()) {
348             c.addIn(KIMPropertyConstants.RoleMember.ROLE_ID, roleIds);
349         }
350         Criteria orSet = new Criteria();
351         orSet.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.ROLE.getCode());
352         Criteria principalCheck = new Criteria();
353         if (principalId != null) {
354             principalCheck.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_ID, principalId);
355         }
356         principalCheck.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode());
357         orSet.addOrCriteria(principalCheck);
358         Criteria groupCheck = new Criteria();
359         if (groupIds != null && !groupIds.isEmpty()) {
360             groupCheck.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, groupIds);
361         }
362         groupCheck.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode());
363         orSet.addOrCriteria(groupCheck);
364         c.addAndCriteria(orSet);
365         addSubCriteriaBasedOnRoleQualification(c, qualification);
366 
367         Query query = QueryFactory.newQuery(RoleMemberBo.class, c);
368         Collection<RoleMemberBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
369         ArrayList<RoleMemberBo> results = new ArrayList<RoleMemberBo>(coll.size());
370         for (RoleMemberBo rm : coll) {
371             if (rm.isActive(new Timestamp(System.currentTimeMillis()))) {
372                 results.add(rm);
373             }
374         }
375         return results;
376     }
377 
378     public List<RoleBo> getRoles(Map<String, String> fieldValues) {
379         Criteria criteria = new Criteria();
380         Map<String, Map<String, String>> criteriaMap = setupCritMaps(fieldValues);
381 
382 //      List lookupNames = boEntry.getLookupDefinition().getLookupFieldNames();
383         Map<String, String> lookupNames = criteriaMap.get("lookupNames");
384         for (Map.Entry<String, String> entry : lookupNames.entrySet()) {
385             if (StringUtils.isNotBlank(entry.getValue())) {
386                 if (!entry.getKey().equals(KIMPropertyConstants.Principal.PRINCIPAL_NAME)) {
387                     addLikeToCriteria(criteria, entry.getKey(), entry.getValue());
388                 } else {
389                     List<String> roleIds = getRoleIdsForPrincipalName(entry.getValue());
390                     if (roleIds != null && !roleIds.isEmpty()) {
391                         criteria.addIn(KimConstants.PrimaryKeyConstants.ID, roleIds);
392                     } else {
393                         // TODO : if no role id found that means principalname not matched, need to do something to force to return empty list
394                         roleIds.add("NOTFOUND");
395                         criteria.addIn(KimConstants.PrimaryKeyConstants.ID, roleIds);
396                     }
397                 }
398             }
399         }
400         if (!criteriaMap.get("attr").isEmpty()) {
401             String kimTypeId = null;
402             for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
403                 if (entry.getKey().equals("kimTypeId")) {
404                     kimTypeId = entry.getValue();
405                     break;
406                 }
407             }
408             setupAttrCriteria(criteria, criteriaMap.get("attr"), kimTypeId);
409         }
410         if (!criteriaMap.get("perm").isEmpty()) {
411             criteria.addExists(setupPermCriteria(criteriaMap.get("perm")));
412         }
413         if (!criteriaMap.get("resp").isEmpty()) {
414             criteria.addExists(setupRespCriteria(criteriaMap.get("resp")));
415         }
416         if (!criteriaMap.get("group").isEmpty()) {
417             criteria.addExists(setupGroupCriteria(criteriaMap.get("group")));
418         }
419 
420         Query q = QueryFactory.newQuery(RoleBo.class, criteria);
421 
422         return (List) getPersistenceBrokerTemplate().getCollectionByQuery(q);
423     }
424 
425 
426     private List<String> getPrincipalIdsForPrincipalName(String principalName) {
427         QueryByCriteria.Builder qb = QueryByCriteria.Builder.create();
428         qb.setPredicates(equal("principals.principalName", principalName));
429         List<EntityDefault> entities = KimApiServiceLocator.getIdentityService().findEntityDefaults(qb.build()).getResults();
430 
431         List<String> principalIds = new ArrayList<String>();
432         for (EntityDefault entity : entities) {
433             for (Principal principal : entity.getPrincipals()) {
434                 principalIds.add(principal.getPrincipalId());
435             }
436         }
437 
438         return principalIds;
439 
440     }
441 
442     private List<String> getRoleIdsForPrincipalName(String value) {
443         String principalName = value.replace('*', '%');
444         List<String> roleIds = new ArrayList<String>();
445         Criteria memberSubCrit = new Criteria();
446         QueryByCriteria.Builder qb = QueryByCriteria.Builder.create();
447         qb.setPredicates(like("principals.principalName", principalName));
448         List<EntityDefault> entities = KimApiServiceLocator.getIdentityService().findEntityDefaults(qb.build()).getResults();
449         if (entities == null
450                 || entities.size() == 0) {
451             return roleIds;
452         }
453 
454         List<String> principalIds = new ArrayList<String>();
455         for (EntityDefault entity : entities) {
456             for (Principal principal : entity.getPrincipals()) {
457                 principalIds.add(principal.getPrincipalId());
458             }
459         }
460         if (principalIds != null && !principalIds.isEmpty()) {
461             memberSubCrit.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode());
462             memberSubCrit.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, principalIds);
463 
464             ReportQueryByCriteria memberSubQuery = QueryFactory.newReportQuery(RoleMemberBo.class, memberSubCrit);
465             for (RoleMemberBo roleMbr : (List<RoleMemberBo>) getPersistenceBrokerTemplate().getCollectionByQuery(memberSubQuery)) {
466                 if (roleMbr.isActive(new Timestamp(System.currentTimeMillis())) && !roleIds.contains(roleMbr.getRoleId())) {
467                     roleIds.add(roleMbr.getRoleId());
468                 }
469             }
470         }
471 
472         List<String> groupIds = new ArrayList<String>();
473         for (String principalId : principalIds) {
474             List<String> principalGroupIds = KimApiServiceLocator.getGroupService().getGroupIdsByPrincipalId(
475                     principalId);
476             for (String groupId : principalGroupIds) {
477                 if (!groupIds.contains(groupId)) {
478                     groupIds.add(groupId);
479                 }
480             }
481         }
482 
483         if (groupIds != null && !groupIds.isEmpty()) {
484             Criteria grpRoleCrit = new Criteria();
485             grpRoleCrit.addEqualTo(KIMPropertyConstants.RoleMember.MEMBER_TYPE_CODE, MemberType.GROUP.getCode());
486             grpRoleCrit.addIn(KIMPropertyConstants.RoleMember.MEMBER_ID, groupIds);
487 
488             ReportQueryByCriteria memberSubQuery = QueryFactory.newReportQuery(RoleMemberBo.class, grpRoleCrit);
489 
490             for (RoleMemberBo roleMbr : (List<RoleMemberBo>) getPersistenceBrokerTemplate().getCollectionByQuery(memberSubQuery)) {
491                 if (roleMbr.isActive(new Timestamp(System.currentTimeMillis())) && !roleIds.contains(roleMbr.getRoleId())) {
492                     roleIds.add(roleMbr.getRoleId());
493                 }
494             }
495         }
496 
497         return roleIds;
498     }
499 
500     private Map<String, Map<String, String>> setupCritMaps(Map<String, String> fieldValues) {
501 
502         Map<String, Map<String, String>> critMap = new HashMap<String, Map<String, String>>();
503         List<String> permFieldName = new ArrayList<String>();
504         permFieldName.add("permName");
505         permFieldName.add("permNamespaceCode");
506         permFieldName.add("permTmplName");
507         permFieldName.add("permTmplNamespaceCode");
508         List<String> respFieldName = new ArrayList<String>();
509         respFieldName.add("respName");
510         respFieldName.add("respNamespaceCode");
511         respFieldName.add("respTmplName");
512         respFieldName.add("respTmplNamespaceCode");
513         Map<String, String> permFieldMap = new HashMap<String, String>();
514         Map<String, String> respFieldMap = new HashMap<String, String>();
515         Map<String, String> attrFieldMap = new HashMap<String, String>();
516         Map<String, String> groupFieldMap = new HashMap<String, String>();
517         Map<String, String> lookupNamesMap = new HashMap<String, String>();
518 
519         for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
520             if (StringUtils.isNotBlank(entry.getValue())) {
521                 String nameValue = entry.getValue();
522                 if (permFieldName.contains(entry.getKey())) {
523                     permFieldMap.put(entry.getKey(), nameValue);
524                 } else if (respFieldName.contains(entry.getKey())) {
525                     respFieldMap.put(entry.getKey(), nameValue);
526                 } else if (entry.getKey().startsWith(KimConstants.AttributeConstants.GROUP_NAME)) {
527                     groupFieldMap.put(entry.getKey(), nameValue);
528                 } else if (entry.getKey().contains(".")) {
529                     attrFieldMap.put(entry.getKey(), nameValue).replace('*', '%');
530                 } else {
531                     lookupNamesMap.put(entry.getKey(), nameValue);
532                 }
533             }
534         }
535 
536         critMap.put("perm", permFieldMap);
537         critMap.put("resp", respFieldMap);
538         critMap.put("group", groupFieldMap);
539         critMap.put("attr", attrFieldMap);
540         critMap.put("lookupNames", lookupNamesMap);
541         return critMap;
542     }
543 
544 
545     private void setupAttrCriteria(Criteria crit, Map<String, String> attrCrit, String kimTypeId) {
546         for (Map.Entry<String, String> entry : attrCrit.entrySet()) {
547             Criteria subCrit = new Criteria();
548             addLikeToCriteria(subCrit, "attributes.attributeValue", entry.getValue());
549             addEqualToCriteria(subCrit, "attributes.kimAttributeId", entry.getKey().substring(entry.getKey().indexOf(".") + 1, entry.getKey().length()));
550             addEqualToCriteria(subCrit, "attributes.kimTypeId", kimTypeId);
551             subCrit.addEqualToField("roleId", Criteria.PARENT_QUERY_PREFIX + "id");
552             crit.addExists(QueryFactory.newReportQuery(RoleMemberBo.class, subCrit));
553         }
554     }
555 
556     private ReportQueryByCriteria setupPermCriteria(Map<String, String> permCrit) {
557 
558         Map<String, String> actualCriteriaMap = new HashMap<String, String>();
559         for (Map.Entry<String, String> entry : permCrit.entrySet()) {
560             if (entry.getKey().equals("permTmplName") || entry.getKey().equals("permTmplNamespaceCode")) {
561                 if (entry.getKey().equals("permTmplName")) {
562                     actualCriteriaMap.put("template." + KimConstants.UniqueKeyConstants.PERMISSION_TEMPLATE_NAME, entry.getValue());
563                 } else {
564                     actualCriteriaMap.put("template." + KimConstants.UniqueKeyConstants.NAMESPACE_CODE, entry.getValue());
565                 }
566             }
567 
568             if (entry.getKey().equals("permName") || entry.getKey().equals("permNamespaceCode")) {
569                 if (entry.getKey().equals("permName")) {
570                     actualCriteriaMap.put(KimConstants.UniqueKeyConstants.PERMISSION_NAME, entry.getValue());
571                 } else {
572                     actualCriteriaMap.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, entry.getValue());
573                 }
574             }
575         }
576 
577         Predicate predicate = PredicateUtils.convertMapToPredicate(actualCriteriaMap);
578         List<Permission> permList = KimApiServiceLocator.getPermissionService().findPermissions(
579                 QueryByCriteria.Builder.fromPredicates(predicate)).getResults();
580         List<String> roleIds = null;
581 
582         if (permList != null && !permList.isEmpty()) {
583             roleIds = getRoleIdsForPermissions(permList);
584         }
585 
586         if (roleIds == null || roleIds.isEmpty()) {
587             roleIds = new ArrayList<String>();
588             roleIds.add("-1"); // this forces a blank return.
589         }
590 
591         Criteria memberSubCrit = new Criteria();
592         memberSubCrit.addIn("id", roleIds);
593         memberSubCrit.addEqualToField("id", Criteria.PARENT_QUERY_PREFIX + "id");
594         return QueryFactory.newReportQuery(RoleBo.class, memberSubCrit);
595 
596     }
597 
598     private List<String> getRoleIdsForPermissions(Collection<Permission> permissions) {
599 		if ( permissions.isEmpty() ) {
600 			return new ArrayList<String>(0);
601 		}
602 		List<String> permissionIds = new ArrayList<String>( permissions.size() );
603 		for ( Permission permission : permissions ) {
604 			permissionIds.add( permission.getId() );
605 		}
606 		Criteria c = new Criteria();
607 		c.addIn( "permissionId", permissionIds );
608 		c.addEqualTo( "active", true );
609 
610 		Query query = QueryFactory.newQuery( RolePermissionBo.class, c, true );
611 		Collection<RolePermissionBo> coll = getPersistenceBrokerTemplate().getCollectionByQuery(query);
612 		List<String> roleIds = new ArrayList<String>( coll.size() );
613 		for ( RolePermissionBo rp : coll ) {
614 			roleIds.add( rp.getRoleId() );
615 		}
616 		return roleIds;
617 	}
618 
619     private ReportQueryByCriteria setupRespCriteria(Map<String, String> respCrit) {
620         QueryByCriteria.Builder queryByCriteriaBuilder = QueryByCriteria.Builder.create();
621         Map<String, String> actualCriteriaMap = new HashMap<String, String>();
622         for (Map.Entry<String, String> entry : respCrit.entrySet()) {
623             if (entry.getKey().equals("respTmplName") || entry.getKey().equals("respTmplNamespaceCode")) {
624                 if (entry.getKey().equals("respTmplName")) {
625                     actualCriteriaMap.put("template." + KimConstants.UniqueKeyConstants.RESPONSIBILITY_TEMPLATE_NAME, entry.getValue());
626                 } else {
627                     actualCriteriaMap.put("template." + KimConstants.UniqueKeyConstants.NAMESPACE_CODE, entry.getValue());
628                 }
629             }
630             if (entry.getKey().equals("respName") || entry.getKey().equals("respNamespaceCode")) {
631                 if (entry.getKey().equals("respName")) {
632                     actualCriteriaMap.put(KimConstants.UniqueKeyConstants.RESPONSIBILITY_NAME, entry.getValue());
633                 } else {
634                     actualCriteriaMap.put(KimConstants.UniqueKeyConstants.NAMESPACE_CODE, entry.getValue());
635                 }
636             }
637         }
638         Predicate predicate = PredicateUtils.convertMapToPredicate(actualCriteriaMap);
639         queryByCriteriaBuilder.setPredicates(predicate);
640 
641         ResponsibilityService responsibilityService = KimApiServiceLocator.getResponsibilityService();
642         ResponsibilityQueryResults results = responsibilityService.findResponsibilities(queryByCriteriaBuilder.build());
643         List<Responsibility> responsibilities = results.getResults();
644 
645 
646         List<String> roleIds = new ArrayList<String>();
647         for (Responsibility responsibility : responsibilities) {
648             roleIds.addAll(responsibilityService.getRoleIdsForResponsibility(responsibility.getId()));
649         }
650 
651         if (roleIds.isEmpty()) {
652             roleIds.add("-1"); // this forces a blank return.
653         }
654 
655         Criteria memberSubCrit = new Criteria();
656         memberSubCrit.addIn("id", roleIds);
657         memberSubCrit.addEqualToField("id", Criteria.PARENT_QUERY_PREFIX + "id");
658         return QueryFactory.newReportQuery(RoleBo.class, memberSubCrit);
659 
660     }
661 
662     private ReportQueryByCriteria setupGroupCriteria(Map<String,String> groupCrit) {
663 
664         //Map<String,String> searchCrit = new HashMap<String, String>();
665         final QueryByCriteria.Builder searchCrit = QueryByCriteria.Builder.create();
666         Map<String, String> actualCrit = new HashMap<String, String>();
667         for (Entry<String, String> entry : groupCrit.entrySet()) {
668             if (entry.getKey().equals(KimConstants.AttributeConstants.GROUP_NAME)) {
669                 actualCrit.put(KimConstants.AttributeConstants.NAME, entry.getValue());
670             } else { // the namespace code for the group field is named something besides the default. Set it to the default.
671                 actualCrit.put(KimConstants.AttributeConstants.NAMESPACE_CODE, entry.getValue());
672             }
673        }
674 
675        Criteria crit = new Criteria();
676        Predicate predicate = PredicateUtils.convertMapToPredicate(actualCrit);
677        searchCrit.setPredicates(predicate);
678        List<String> groupIds = KimApiServiceLocator.getGroupService().findGroupIds(searchCrit.build());
679 
680        if(groupIds == null || groupIds.isEmpty()){
681                groupIds = new ArrayList<String>();
682                groupIds.add("-1");  // this forces a blank return.
683        }
684        crit.addIn("memberId", groupIds);
685        crit.addEqualToField("roleId", Criteria.PARENT_QUERY_PREFIX + "id");
686 
687                 return QueryFactory.newReportQuery(RoleMemberBo.class, crit);
688 
689    }
690 
691     private void addLikeToCriteria(Criteria criteria, String propertyName, String propertyValue) {
692         String[] keyValues = getCaseInsensitiveValues(propertyName, propertyValue);
693         criteria.addLike(keyValues[0], keyValues[1]);
694     }
695 
696     private void addEqualToCriteria(Criteria criteria, String propertyName, String propertyValue) {
697         String[] keyValues = getCaseInsensitiveValues(propertyName, propertyValue);
698         criteria.addEqualTo(keyValues[0], keyValues[1]);
699     }
700 
701     private String[] getCaseInsensitiveValues(String propertyName, String propertyValue) {
702         String[] keyValues = new String[2];
703         keyValues[0] = propertyName == null ? "" : getDbPlatform().getUpperCaseFunction() + "(" + propertyName + ")";
704         keyValues[1] = propertyValue == null ? "" : propertyValue.toUpperCase();
705         return keyValues;
706     }
707 
708     private boolean hasCoreRoleMemberCriteria(Map<String, String> fieldValues) {
709         return StringUtils.isNotEmpty(fieldValues.get(KimConstants.PrimaryKeyConstants.ID)) ||
710                 StringUtils.isNotEmpty(fieldValues.get(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID)) ||
711                 StringUtils.isNotEmpty(fieldValues.get(KimConstants.PrimaryKeyConstants.MEMBER_ID)) ||
712                 StringUtils.isNotEmpty(fieldValues.get(KIMPropertyConstants.KimMember.MEMBER_TYPE_CODE)) ||
713                 StringUtils.isNotEmpty(fieldValues.get(KIMPropertyConstants.KimMember.ACTIVE_FROM_DATE)) ||
714                 StringUtils.isNotEmpty(fieldValues.get(KIMPropertyConstants.KimMember.ACTIVE_TO_DATE));
715     }
716 
717     private boolean hasExtraRoleMemberCriteria(Map<String, String> fieldValues) {
718         return StringUtils.isNotEmpty(fieldValues.get(KimConstants.KimUIConstants.MEMBER_NAME)) ||
719                 StringUtils.isNotEmpty(fieldValues.get(KimConstants.KimUIConstants.MEMBER_NAMESPACE_CODE));
720     }
721 
722     @SuppressWarnings("unchecked")
723     private List<RoleBo> getRoleMembersRoles(String memberNamespaceCode, String memberName) {
724         Criteria queryCriteria = new Criteria();
725         addEqualToCriteria(queryCriteria, KimConstants.UniqueKeyConstants.NAMESPACE_CODE, memberNamespaceCode);
726         addEqualToCriteria(queryCriteria, KimConstants.UniqueKeyConstants.NAME, memberName);
727         Query q = QueryFactory.newQuery(RoleBo.class, queryCriteria);
728         return (List<RoleBo>) getPersistenceBrokerTemplate().getCollectionByQuery(q);
729     }
730 }