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