View Javadoc

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