View Javadoc
1   /**
2    * Copyright 2005-2014 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.service.impl;
17  
18  import static org.junit.Assert.assertEquals;
19  import static org.junit.Assert.assertFalse;
20  import static org.junit.Assert.assertNotNull;
21  import static org.junit.Assert.assertTrue;
22  import static org.junit.Assert.fail;
23  
24  import java.util.ArrayList;
25  import java.util.Collections;
26  import java.util.HashMap;
27  import java.util.List;
28  import java.util.Map;
29  
30  import javax.xml.namespace.QName;
31  
32  import org.apache.commons.lang.StringUtils;
33  import org.joda.time.DateTime;
34  import org.joda.time.format.DateTimeFormat;
35  import org.joda.time.format.DateTimeFormatter;
36  import org.junit.Test;
37  import org.kuali.rice.core.api.delegation.DelegationType;
38  import org.kuali.rice.core.api.exception.RiceIllegalStateException;
39  import org.kuali.rice.core.api.membership.MemberType;
40  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
41  import org.kuali.rice.kew.api.action.ActionType;
42  import org.kuali.rice.kim.api.KimApiConstants;
43  import org.kuali.rice.kim.api.KimConstants;
44  import org.kuali.rice.kim.api.common.delegate.DelegateMember;
45  import org.kuali.rice.kim.api.role.Role;
46  import org.kuali.rice.kim.api.role.RoleMember;
47  import org.kuali.rice.kim.api.role.RoleMembership;
48  import org.kuali.rice.kim.api.role.RoleResponsibilityAction;
49  import org.kuali.rice.kim.api.role.RoleService;
50  import org.kuali.rice.kim.impl.common.delegate.DelegateMemberAttributeDataBo;
51  import org.kuali.rice.kim.impl.common.delegate.DelegateMemberBo;
52  import org.kuali.rice.kim.impl.common.delegate.DelegateTypeBo;
53  import org.kuali.rice.kim.impl.role.RoleMemberAttributeDataBo;
54  import org.kuali.rice.kim.impl.role.RoleMemberBo;
55  import org.kuali.rice.kim.test.KIMTestCase;
56  import org.kuali.rice.krad.data.KradDataServiceLocator;
57  import org.kuali.rice.krad.data.PersistenceOption;
58  
59  import com.google.common.collect.Maps;
60  
61  public class RoleServiceImplTest extends KIMTestCase {
62      private RoleService roleService;
63      static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
64      static final String ROLE_MEMBER_ID1 = "45123";
65      static final String ROLE_ID = "100";
66      static final String MEMBER_ID = "1";
67      static final MemberType MEMBER_TYPE_R = MemberType.ROLE;
68      static final String ACTIVE_FROM_STRING = "2011-01-01 12:00:00";
69      static final DateTime ACTIVE_FROM = new DateTime(FORMATTER.parseDateTime(ACTIVE_FROM_STRING));
70      static final String ACTIVE_TO_STRING1 = "2013-01-01 12:00:00";
71      static final String ACTIVE_TO_STRING2 = "2014-01-01 12:00:00";
72      static final DateTime ACTIVE_TO1 = new DateTime(FORMATTER.parseDateTime(ACTIVE_TO_STRING1));
73      static final DateTime ACTIVE_TO2 = new DateTime(FORMATTER.parseDateTime(ACTIVE_TO_STRING2));
74  
75      @Override
76      public void setUp() throws Exception {
77  		super.setUp();
78  		roleService = (RoleService) GlobalResourceLoader.getService(
79                  new QName(KimApiConstants.Namespaces.KIM_NAMESPACE_2_0, KimApiConstants.ServiceNames.ROLE_SERVICE_SOAP));
80  	}
81  
82  	@Test
83  	public void testPrincipaHasRoleOfDirectAssignment() {
84  		List <String>roleIds = new ArrayList<String>();
85  		roleIds.add("r1");
86  		assertTrue( "p1 has direct role r1", roleService.principalHasRole("p1", roleIds,  Collections
87                  .<String, String>emptyMap() ));
88  		//assertFalse( "p4 has no direct/higher level role r1", roleService.principalHasRole("p4", roleIds, null ));
89  		Map<String, String> qualification = new HashMap<String, String>();
90  		qualification.put("Attribute 2", "CHEM");
91  		assertTrue( "p1 has direct role r1 with rp2 attr data", roleService.principalHasRole("p1", roleIds, qualification));
92  		qualification.clear();
93  		//requested qualification rolls up to a higher element in some hierarchy
94  		// method not implemented yet, not quite clear how this works
95  		qualification.put("Attribute 3", "PHYS");
96  		assertTrue( "p1 has direct role r1 with rp2 attr data", roleService.principalHasRole("p1", roleIds, Maps.newHashMap(
97                  qualification)));
98  	}
99  
100 	@Test
101 	public void testPrincipalHasRoleOfHigherLevel() {
102 		// "p3" is in "r2" and "r2 contains "r1"
103 		List <String>roleIds = new ArrayList<String>();
104 		roleIds.add("r2");
105 		assertTrue( "p1 has assigned in higher level role r1", roleService.principalHasRole("p1", roleIds,  Collections.<String, String>emptyMap() ));
106         assertTrue( "p1 has assigned in higher level role r1", roleService.principalHasRole("p1", roleIds,  Collections.<String, String>emptyMap() ));
107 	}
108 
109     @Test
110     public void testDelegateMemberCreateUpdateRemove() {
111 
112         Role r2 = roleService.getRole("r2");
113         RoleMember rm1 = roleService.assignPrincipalToRole("user2", r2.getNamespaceCode(), r2.getName(),
114                 new HashMap<String, String>());
115         String kimTypeId = "1";
116 
117         //Create delegation
118         String id = getNextSequenceStringValue("KRIM_DLGN_MBR_ID_S");
119         DelegateTypeBo delegate = new DelegateTypeBo();
120         delegate.setDelegationId(id);
121         delegate.setDelegationType(DelegationType.PRIMARY);
122         delegate.setRoleId(r2.getId());
123         delegate.setActive(true);
124         delegate.setKimTypeId("" + kimTypeId);
125         delegate = KradDataServiceLocator.getDataObjectService().save(delegate, PersistenceOption.FLUSH);
126 
127         //Create delegate member
128         DelegateMember.Builder delegateMemberInfo = DelegateMember.Builder.create();
129         delegateMemberInfo.setAttributes(Collections.<String, String>emptyMap());
130         delegateMemberInfo.setDelegationId(delegate.getDelegationId());
131         delegateMemberInfo.setMemberId("user4");
132         delegateMemberInfo.setRoleMemberId(rm1.getId());
133         delegateMemberInfo.setType( MemberType.PRINCIPAL );
134         DelegateMember inDelegateMember =  delegateMemberInfo.build();
135         DelegateMember newDelegateMember = roleService.createDelegateMember(inDelegateMember);
136         assertNotNull("delegateMember not created",newDelegateMember);
137 
138         //Update delegate member
139         delegateMemberInfo.setDelegationMemberId(newDelegateMember.getDelegationMemberId());
140         DateTime dateTimeFrom   = DateTime.now().minusDays(3);
141         delegateMemberInfo.setActiveFromDate(dateTimeFrom);
142         DateTime dateTimeTo = DateTime.now().plusDays(3);
143         delegateMemberInfo.setActiveToDate(dateTimeTo);
144         inDelegateMember = delegateMemberInfo.build();
145         roleService.updateDelegateMember(inDelegateMember);
146         DelegateMember updatedDelegateMember = DelegateMember.Builder.create( KradDataServiceLocator.getDataObjectService().find(DelegateMemberBo.class, inDelegateMember.getDelegationMemberId()) ).build();
147 
148         assertEquals("Delegate member was updated",newDelegateMember.getDelegationMemberId(),updatedDelegateMember.getDelegationMemberId());
149         assertNotNull("updateDelegateMember not created",updatedDelegateMember);
150         assertEquals("activeFromDate not updated",dateTimeFrom,updatedDelegateMember.getActiveFromDate());
151         assertEquals("activeToDate not updated",dateTimeTo,updatedDelegateMember.getActiveToDate());
152 
153         //remove (inactivate) delegate member
154         roleService.removeDelegateMembers(Collections.singletonList(updatedDelegateMember));
155         DelegateMemberBo removedDelegateMember = KradDataServiceLocator.getDataObjectService().find(DelegateMemberBo.class, updatedDelegateMember.getDelegationMemberId());
156         //assertEquals("removeDelegateMembers did not remove the existing member",updatedDelegateMember.getDelegationMemberId(), removedDelegateMember.getDelegationMemberId() );
157         assertNotNull("after removal, versionNumber should not be null", removedDelegateMember.getVersionNumber());
158         assertEquals("removeDelegateMembers did not update the existing member", new Long(updatedDelegateMember.getVersionNumber() + 1), removedDelegateMember.getVersionNumber() );
159         assertNotNull("after removal, active to date should not be null", removedDelegateMember.getActiveToDate());
160         assertTrue("removeDelegateMembers did not update activeToDate",removedDelegateMember.getActiveToDate().isBeforeNow());
161     }
162 
163     @Test
164     public void testRoleMemberCreateUpdate() {
165 
166         Role roleId = roleService.getRole(ROLE_ID);
167         List<String> roleIds = new ArrayList<String>();
168         roleIds.add(roleId.getId());
169 
170         Map<String,String> attributes = new HashMap<String,String>();
171         attributes.put("parameterName", "parameterNameBefore");
172         attributes.put("namespaceCode", "namespaceCodeBefore");
173         attributes.put("componentName", "componentNameBefore");
174 
175         RoleMember roleMember =  roleService.createRoleMember(RoleMember.Builder.create(ROLE_ID, ROLE_MEMBER_ID1, MEMBER_ID, MEMBER_TYPE_R, ACTIVE_FROM, ACTIVE_TO1, attributes, "", "").build());
176         RoleMemberBo rmBo = getRoleMemberBo(roleMember.getId());
177 
178         RoleMember.Builder updatedRoleMember = RoleMember.Builder.create(roleMember);
179         updatedRoleMember.setActiveToDate(ACTIVE_TO2);
180         Map<String,String> newAttributes = new HashMap<String,String>();
181         newAttributes.put("parameterName", "parameterNameAfter");
182         newAttributes.put("namespaceCode", "namespaceCodeAfter");
183         newAttributes.put("componentName", "componentNameAfter");
184         updatedRoleMember.setAttributes(newAttributes);
185 
186         roleService.updateRoleMember(updatedRoleMember.build());
187         RoleMemberBo updatedRmBo = getRoleMemberBo(roleMember.getId());
188 
189         assertEquals(3,rmBo.getAttributeDetails().size());
190         assertEquals(3,updatedRmBo.getAttributeDetails().size());
191 
192         for (RoleMemberAttributeDataBo newRoleMemberAttrDataBo :  updatedRmBo.getAttributeDetails()) {
193             for (RoleMemberAttributeDataBo oldRoleMemberAttrDataBo :  rmBo.getAttributeDetails()) {
194                 if (newRoleMemberAttrDataBo.getKimTypeId().equals(oldRoleMemberAttrDataBo.getKimTypeId()) &&
195                     newRoleMemberAttrDataBo.getKimAttributeId().equals(oldRoleMemberAttrDataBo.getKimAttributeId())) {
196                         assertEquals("updated role member version number incorrect", new Long(2), newRoleMemberAttrDataBo.getVersionNumber());
197                 }
198             }
199         }
200     }
201 
202     @Test
203     public void testRoleMemberCreateUpdateNoAttrChange() {
204 
205         Role roleId = roleService.getRole(ROLE_ID);
206         List<String> roleIds = new ArrayList<String>();
207         roleIds.add(roleId.getId());
208 
209         Map<String,String> attributes = new HashMap<String,String>();
210         attributes.put("parameterName", "parameterNameBefore");
211         attributes.put("namespaceCode", "namespaceCodeBefore");
212         attributes.put("componentName", "componentNameBefore");
213 
214         RoleMember roleMember =  roleService.createRoleMember(RoleMember.Builder.create(ROLE_ID, ROLE_MEMBER_ID1, MEMBER_ID, MEMBER_TYPE_R, ACTIVE_FROM, ACTIVE_TO1, attributes, "", "").build());
215         RoleMemberBo rmBo = getRoleMemberBo(roleMember.getId());
216 
217         RoleMember.Builder updatedRoleMember = RoleMember.Builder.create(roleMember);
218         updatedRoleMember.setActiveToDate(ACTIVE_TO2);
219         updatedRoleMember.setAttributes(rmBo.getAttributes());
220 
221         roleService.updateRoleMember(updatedRoleMember.build());
222         RoleMemberBo updatedRmBo = getRoleMemberBo(roleMember.getId());
223 
224         assertEquals(3,rmBo.getAttributeDetails().size());
225         assertEquals(3,updatedRmBo.getAttributeDetails().size());
226 
227         for (RoleMemberAttributeDataBo newRoleMemberAttrDataBo :  updatedRmBo.getAttributeDetails()) {
228             for (RoleMemberAttributeDataBo oldRoleMemberAttrDataBo :  rmBo.getAttributeDetails()) {
229                 if (newRoleMemberAttrDataBo.getKimTypeId().equals(oldRoleMemberAttrDataBo.getKimTypeId()) &&
230                         newRoleMemberAttrDataBo.getKimAttributeId().equals(oldRoleMemberAttrDataBo.getKimAttributeId())) {
231                     assertEquals(oldRoleMemberAttrDataBo.getAttributeValue(), newRoleMemberAttrDataBo.getAttributeValue());
232                     assertEquals("updated role member version number incorrect (since no update - should not have been changed)", new Long(1), newRoleMemberAttrDataBo.getVersionNumber());
233                 }
234             }
235         }
236     }
237 
238     @Test
239     public void testRoleMemberCreateUpdateRemoveOneAttr() {
240 
241         Role roleId = roleService.getRole(ROLE_ID);
242         List<String> roleIds = new ArrayList<String>();
243         roleIds.add(roleId.getId());
244 
245         Map<String,String> attributes = new HashMap<String,String>();
246         attributes.put("parameterName", "parameterNameBefore");
247         attributes.put("namespaceCode", "namespaceCodeBefore");
248         attributes.put("componentName", "componentNameBefore");
249 
250         RoleMember roleMember =  roleService.createRoleMember(RoleMember.Builder.create(ROLE_ID, ROLE_MEMBER_ID1, MEMBER_ID, MEMBER_TYPE_R, ACTIVE_FROM, ACTIVE_TO1, attributes, "", "").build());
251         RoleMemberBo rmBo = getRoleMemberBo(roleMember.getId());
252         assertEquals(3,rmBo.getAttributeDetails().size());
253 
254         RoleMember.Builder updatedRoleMember = RoleMember.Builder.create(roleMember);
255         updatedRoleMember.setActiveToDate(ACTIVE_TO2);
256         Map<String,String> newAttributes = new HashMap<String,String>();
257         newAttributes.put("parameterName", "parameterNameAfter");
258         newAttributes.put("namespaceCode", "namespaceCodeAfter");
259         updatedRoleMember.setAttributes(newAttributes);
260 
261         roleService.updateRoleMember(updatedRoleMember.build());
262         RoleMemberBo updatedRmBo = getRoleMemberBo(roleMember.getId());
263 
264         assertEquals(2, updatedRmBo.getAttributeDetails().size());
265 
266         for (RoleMemberAttributeDataBo newRoleMemberAttrDataBo :  updatedRmBo.getAttributeDetails()) {
267             for (RoleMemberAttributeDataBo oldRoleMemberAttrDataBo :  rmBo.getAttributeDetails()) {
268                 if (newRoleMemberAttrDataBo.getKimTypeId().equals(oldRoleMemberAttrDataBo.getKimTypeId()) &&
269                         newRoleMemberAttrDataBo.getKimAttributeId().equals(oldRoleMemberAttrDataBo.getKimAttributeId())) {
270                     assertEquals(new Long(2), newRoleMemberAttrDataBo.getVersionNumber());
271                 }
272             }
273         }
274     }
275 
276     @Test
277     public void testRoleMemberCreateUpdateAddOneAttr() {
278 
279         Role roleId = roleService.getRole(ROLE_ID);
280         List<String> roleIds = new ArrayList<String>();
281         roleIds.add(roleId.getId());
282 
283         Map<String,String> attributes = new HashMap<String,String>();
284         attributes.put("parameterName", "parameterNameBefore");
285         attributes.put("namespaceCode", "namespaceCodeBefore");
286 
287         RoleMember roleMember =  roleService.createRoleMember(RoleMember.Builder.create(ROLE_ID, ROLE_MEMBER_ID1, MEMBER_ID, MEMBER_TYPE_R, ACTIVE_FROM, ACTIVE_TO1, attributes, "", "").build());
288         RoleMemberBo rmBo = getRoleMemberBo(roleMember.getId());
289         assertEquals("Original role member number of attributes is incorrect", 2,rmBo.getAttributeDetails().size());
290 
291         RoleMember.Builder updatedRoleMember = RoleMember.Builder.create(roleMember);
292         updatedRoleMember.setActiveToDate(ACTIVE_TO2);
293         Map<String,String> newAttributes = new HashMap<String,String>();
294         newAttributes.put("parameterName", "parameterNameAfter");
295         newAttributes.put("namespaceCode", "namespaceCodeAfter");
296         newAttributes.put("componentName", "componentNameAfter");
297 
298         updatedRoleMember.setAttributes(newAttributes);
299 
300         roleService.updateRoleMember(updatedRoleMember.build());
301         RoleMemberBo updatedRmBo = getRoleMemberBo(roleMember.getId());
302 
303         //assertEquals("Original role member number of attributes is incorrect: " + rmBo, 2,rmBo.getAttributeDetails().size());
304         assertEquals("updated role member number of attributes is incorrect", 3,updatedRmBo.getAttributeDetails().size());
305 
306         System.err.println( updatedRmBo );
307 
308         for (RoleMemberAttributeDataBo newRoleMemberAttrDataBo : updatedRmBo.getAttributeDetails() ) {
309             assertEquals( newRoleMemberAttrDataBo.getKimAttribute().getAttributeName() + " value is incorrect", newRoleMemberAttrDataBo.getKimAttribute().getAttributeName() + "After", newRoleMemberAttrDataBo.getAttributeValue() );
310             if (newRoleMemberAttrDataBo.getKimAttribute().getAttributeName().equals("componentName")) {
311                 assertEquals("componentName (new attribute) versionNumber incorrect", new Long(1), newRoleMemberAttrDataBo.getVersionNumber());
312             } else {
313                 assertEquals(newRoleMemberAttrDataBo.getKimAttribute().getAttributeName() + " (updated attribute) versionNumber incorrect", new Long(2), newRoleMemberAttrDataBo.getVersionNumber());
314             }
315         }
316     }
317 
318 
319     @Test
320     public void testDelegateMemberCreateUpdateRemoveWithAttr() {
321 
322         Role r2 = roleService.getRole(ROLE_ID);
323         RoleMember rm1 = roleService.assignPrincipalToRole("user2", r2.getNamespaceCode(), r2.getName(),
324                 new HashMap<String, String>());
325         String kimTypeId = "1";
326 
327         //Create delegation
328         String id = getNextSequenceStringValue("KRIM_DLGN_MBR_ID_S");
329         DelegateTypeBo delegate = new DelegateTypeBo();
330         delegate.setDelegationId(id);
331         delegate.setDelegationType(DelegationType.PRIMARY);
332         delegate.setRoleId(r2.getId());
333         delegate.setActive(true);
334         delegate.setKimTypeId(kimTypeId);
335         delegate = KradDataServiceLocator.getDataObjectService().save(delegate, PersistenceOption.FLUSH);
336 
337         //Create delegate member
338         DelegateMember.Builder delegateMemberInfo = DelegateMember.Builder.create();
339         delegateMemberInfo.setDelegationId(delegate.getDelegationId());
340         delegateMemberInfo.setMemberId("user4");
341         delegateMemberInfo.setRoleMemberId(rm1.getId());
342         delegateMemberInfo.setType( MemberType.PRINCIPAL );
343         Map<String,String> attributes = new HashMap<String,String>();
344         attributes.put("parameterName", "parameterNameBefore");
345         attributes.put("namespaceCode", "namespaceCodeBefore");
346         attributes.put("componentName", "componentNameBefore");
347         delegateMemberInfo.setAttributes(attributes);
348         DelegateMember inDelegateMember =  delegateMemberInfo.build();
349         DelegateMember newDelegateMember = roleService.createDelegateMember(inDelegateMember);
350         assertNotNull("delegateMember not created",newDelegateMember);
351 
352 //        DelegateMemberBo originalDelegateMemberBo = getDelegateMemberBo(newDelegateMember.getDelegationMemberId());
353 
354         //Update delegate member
355         DateTime threeDaysAgo   = DateTime.now().minusDays(3);
356         DateTime threeDaysFromNow = DateTime.now().plusDays(3);
357         delegateMemberInfo.setActiveFromDate(threeDaysAgo);
358         delegateMemberInfo.setActiveToDate(threeDaysFromNow);
359         delegateMemberInfo.setDelegationMemberId(newDelegateMember.getDelegationMemberId());
360         Map<String,String> newAttributes = new HashMap<String,String>();
361         newAttributes.put("parameterName", "parameterNameAfter");
362         newAttributes.put("namespaceCode", "namespaceCodeAfter");
363         newAttributes.put("componentName", "componentNameAfter");
364         delegateMemberInfo.setAttributes(newAttributes);
365         newDelegateMember = delegateMemberInfo.build();
366         DelegateMember updateDelegateMember = roleService.updateDelegateMember(newDelegateMember);
367 
368         assertNotNull("updateDelegateMember not updated", updateDelegateMember);
369         assertEquals("activeFromDate not updated",threeDaysAgo,updateDelegateMember.getActiveFromDate());
370         assertEquals("activeToDate not updated",threeDaysFromNow,updateDelegateMember.getActiveToDate());
371 
372         DelegateMemberBo updatedDelegateMemberBo = getDelegateMemberBo(updateDelegateMember.getDelegationMemberId());
373 
374         for (DelegateMemberAttributeDataBo newRoleMemberAttrDataBo :  updatedDelegateMemberBo.getAttributeDetails()) {
375             for (DelegateMemberAttributeDataBo oldRoleMemberAttrDataBo :  updatedDelegateMemberBo.getAttributeDetails()) {
376                 if (newRoleMemberAttrDataBo.getKimTypeId().equals(oldRoleMemberAttrDataBo.getKimTypeId()) &&
377                         newRoleMemberAttrDataBo.getKimAttributeId().equals(oldRoleMemberAttrDataBo.getKimAttributeId())) {
378                     assertEquals("version number on new role member incorrect", new Long(2), newRoleMemberAttrDataBo.getVersionNumber());
379                 }
380             }
381         }
382 
383         //remove (inactivate) delegate member
384         List<DelegateMember>  removeDelegateMembers = new ArrayList<DelegateMember>();
385         removeDelegateMembers.add(updateDelegateMember);
386         roleService.removeDelegateMembers(removeDelegateMembers);
387         DelegateMember removedDelegateMember = roleService.getDelegationMemberById(updateDelegateMember.getDelegationMemberId()) ;
388         assertTrue("removeDelegateMembers did not remove the existing member",removedDelegateMember.getDelegationMemberId().equals(updateDelegateMember.getDelegationMemberId()));
389         assertNotNull("after removal, versionNumber should not be null", removedDelegateMember.getVersionNumber());
390         assertTrue("removeDelegateMembers did not remove the existing member",removedDelegateMember.getVersionNumber().equals(updateDelegateMember.getVersionNumber() + 1));
391         assertNotNull("after removal, active to date should not be null", removedDelegateMember.getActiveToDate());
392         assertTrue("removeDelegateMembers did not update activeToDate",removedDelegateMember.getActiveToDate().isBeforeNow());
393     }
394 
395     protected RoleMemberBo getRoleMemberBo(String roleMemberId) {
396         if (StringUtils.isBlank(roleMemberId)) {
397             return null;
398         }
399 
400         return KradDataServiceLocator.getDataObjectService().find(RoleMemberBo.class, roleMemberId);
401     }
402 
403     protected DelegateMemberBo getDelegateMemberBo(String delegationMemberId) {
404         if (StringUtils.isBlank(delegationMemberId)) {
405             return null;
406         }
407 
408         return KradDataServiceLocator.getDataObjectService().find(DelegateMemberBo.class, delegationMemberId);
409     }
410 
411     @Test
412 	public void testPrincipalHasRoleContainsGroupAssigned() {
413 		// "p2" is in "g1" and "g1" assigned to "r2"
414 		List <String>roleIds = new ArrayList<String>();
415 		roleIds.add("r2");
416 		assertTrue( "p2 is assigned to g1 and g1 assigned to r2", roleService.principalHasRole("p2", roleIds,  Collections.<String, String>emptyMap() ));
417 	}
418 
419     @Test
420     public void testAddPrincipalToRoleAndRemove() {
421         /*Role r2 = roleService.getRole("r2");
422         roleService.assignPrincipalToRole("user4", r2.getNamespaceCode(), r2.getName(),
423                 new HashMap<String, String>());
424 
425         assertTrue("principal should be assigned to role", roleService.principalHasRole("user4", Collections.singletonList(
426                 r2.getId()), new HashMap<String, String>()));
427 
428         roleService.removePrincipalFromRole("user4", r2.getNamespaceCode(), r2.getName(), new HashMap<String, String>());
429 
430         assertFalse("principal should not be assigned to role", roleService.principalHasRole("user4", Collections.singletonList(
431                 r2.getId()), new HashMap<String, String>()));*/
432 
433         Role r2 = roleService.getRole("r2");
434         RoleMember rm1 = roleService.assignPrincipalToRole("user4", r2.getNamespaceCode(), r2.getName(),
435                 new HashMap<String, String>());
436 
437         assertTrue("principal should be assigned to role", roleService.principalHasRole("user4", Collections.singletonList(
438                 r2.getId()), new HashMap<String, String>()));
439 
440         roleService.removePrincipalFromRole("user4", r2.getNamespaceCode(), r2.getName(), new HashMap<String, String>());
441 
442         RoleMember rm2 = roleService.assignPrincipalToRole("user4", r2.getNamespaceCode(), r2.getName(),
443                 new HashMap<String, String>());
444 
445         assertFalse(rm1.getId().equals(rm2.getId()));
446     }
447 
448     @Test
449     public void testAddMultiplePrincipalsToRole() {
450         Role r2 = roleService.getRole("r2");
451         // Test with empty conditions param
452         Map<String, String> conditions = new HashMap<String, String>();
453 
454         int originalNumberOfPrincipals = roleService.getRoleMemberPrincipalIds(r2.getNamespaceCode(), r2.getName(),
455                 conditions).size();
456 
457         RoleMember rm1 = roleService.assignPrincipalToRole("user3", r2.getNamespaceCode(), r2.getName(), conditions);
458         RoleMember rm2 = roleService.assignPrincipalToRole("user4", r2.getNamespaceCode(), r2.getName(), conditions);
459 
460         assertTrue("principal should be assigned to role", roleService.principalHasRole("user3",
461                 Collections.singletonList(r2.getId()), conditions));
462         assertTrue("principal should be assigned to role", roleService.principalHasRole("user4",
463                 Collections.singletonList(r2.getId()), conditions));
464 
465         int numberOfPrincipals = roleService.getRoleMemberPrincipalIds(r2.getNamespaceCode(), r2.getName(), conditions)
466                 .size();
467 
468         assertEquals("Should have been two Principals added to role", numberOfPrincipals - 2,
469                 originalNumberOfPrincipals);
470 
471         r2 = roleService.getRole("r2");
472         roleService.removePrincipalFromRole("user3", r2.getNamespaceCode(), r2.getName(), conditions);
473         roleService.removePrincipalFromRole("user4", r2.getNamespaceCode(), r2.getName(), conditions);
474 
475         r2 = roleService.getRole("r2");
476         assertFalse("principal should have been removed from role", roleService.principalHasRole("user3",
477                 Collections.singletonList(r2.getId()), conditions));
478         assertFalse("principal should have been removed from role", roleService.principalHasRole("user4",
479                 Collections.singletonList(r2.getId()), conditions));
480         numberOfPrincipals = roleService.getRoleMemberPrincipalIds(r2.getNamespaceCode(), r2.getName(),
481                 new HashMap<String, String>()).size();
482         assertEquals("Should have had the two added Principals removed", numberOfPrincipals,
483                 originalNumberOfPrincipals);
484     }
485 
486     @Test
487     public void testAddMultipleQualifiedPrincipalsToRole() {
488         Role rCampus = roleService.getRole("r-campus");
489         // Test with qualifying conditions
490         Map<String, String> conditions = Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL");
491         int originalNumberOfPrincipals = roleService.getRoleMemberPrincipalIds(rCampus.getNamespaceCode(),
492                 rCampus.getName(), Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL")).size();
493 
494         roleService.assignPrincipalToRole("user3", rCampus.getNamespaceCode(), rCampus.getName(),
495                 conditions);
496         roleService.assignPrincipalToRole("user4", rCampus.getNamespaceCode(), rCampus.getName(),
497                 conditions);
498 
499         assertTrue("principal should be assigned to role", roleService.principalHasRole("user3",
500                 Collections.singletonList(rCampus.getId()), conditions));
501         assertTrue("principal should be assigned to role", roleService.principalHasRole("user4",
502                 Collections.singletonList(rCampus.getId()), conditions));
503 
504         int numberOfPrincipals = roleService.getRoleMemberPrincipalIds(rCampus.getNamespaceCode(), rCampus.getName(),
505                 Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL")).size();
506 
507         assertEquals("Should have been two Principals added to role", numberOfPrincipals,
508                 originalNumberOfPrincipals + 2);
509 
510         rCampus = roleService.getRole("r-campus");
511         roleService.removePrincipalFromRole("user3", rCampus.getNamespaceCode(), rCampus.getName(), conditions);
512         roleService.removePrincipalFromRole("user4", rCampus.getNamespaceCode(), rCampus.getName(), conditions);
513 
514         rCampus = roleService.getRole("r-campus");
515         assertFalse("principal should have been removed from role", roleService.principalHasRole("user3",
516                 Collections.singletonList(rCampus.getId()), conditions));
517         assertFalse("principal should have been removed from role", roleService.principalHasRole("user3",
518                 Collections.singletonList(rCampus.getId()), conditions));
519 
520         numberOfPrincipals = roleService.getRoleMemberPrincipalIds(rCampus.getNamespaceCode(), rCampus.getName(),
521                 Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL")).size();
522         assertEquals("Should have had the two added Principals removed", numberOfPrincipals,
523                 originalNumberOfPrincipals);
524     }
525 
526     @Test
527     public void testAddQualifiedPrincipalToRoleDoesNotReuseWrongRoleMember() {
528         Role rCampus = roleService.getRole("r-campus");
529         // Test with qualifying conditions
530         Map<String, String> campusBLqualifier = Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL");
531         Map<String, String> campusKOqualifier = Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "KO");
532 
533         List<RoleMembership> roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
534         // clean the role out
535         for ( RoleMembership rm : roleMembers ) {
536             roleService.removePrincipalFromRole(rm.getMemberId(), rCampus.getNamespaceCode(), rCampus.getName(), campusBLqualifier);
537         }
538         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
539 
540         // make sure they're gone
541         assertEquals("Pre-check failed - should not be any members with" + campusBLqualifier + ".  Members: " + roleMembers, 0, roleMembers.size());
542 
543         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusKOqualifier);
544         // clean the role out
545         for ( RoleMembership rm : roleMembers ) {
546             roleService.removePrincipalFromRole(rm.getMemberId(), rCampus.getNamespaceCode(), rCampus.getName(), campusKOqualifier);
547         }
548         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusKOqualifier);
549 
550         // make sure they're gone
551         assertEquals("Pre-check failed - should not be any members with" + campusKOqualifier + ".  Members: " + roleMembers, 0, roleMembers.size());
552 
553         RoleMember rm1 = roleService.assignPrincipalToRole("user3", rCampus.getNamespaceCode(), rCampus.getName(),
554                 campusBLqualifier);
555         assertTrue("user3 should be assigned to role", roleService.principalHasRole("user3",
556                 Collections.singletonList(rCampus.getId()), campusBLqualifier));
557         assertNotNull( "Role member ID should have been assigned", rm1.getId() );
558         assertNotNull( "role member missing campus code qualifier", rm1.getAttributes().get(KimConstants.AttributeConstants.CAMPUS_CODE) );
559         assertEquals( "campus code on role member incorrect", "BL", rm1.getAttributes().get(KimConstants.AttributeConstants.CAMPUS_CODE) );
560 
561         // attempt to add the user again, but with campus code KO
562         RoleMember rm2 = roleService.assignPrincipalToRole("user3", rCampus.getNamespaceCode(), rCampus.getName(),
563                 campusKOqualifier);
564         assertNotNull( "role member missing campus code qualifier", rm2.getAttributes().get(KimConstants.AttributeConstants.CAMPUS_CODE) );
565         assertEquals( "campus code on role member incorrect", "KO", rm2.getAttributes().get(KimConstants.AttributeConstants.CAMPUS_CODE) );
566         assertTrue("user3 should be assigned to role for campus code KO", roleService.principalHasRole("user3",
567                 Collections.singletonList(rCampus.getId()), campusKOqualifier));
568         assertNotNull( "Role member ID should have been assigned", rm1.getId() );
569         assertFalse( "Role member ID SHOULD NOT be the same as previous assignment since qualifiers are different",
570                 rm1.getId().equals(rm2.getId()) );
571 
572         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
573         assertEquals("Should only be one principal in role with " + campusBLqualifier + ".  Members: " + roleMembers, 1, roleMembers.size());
574         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusKOqualifier);
575         assertEquals("Should only be one principal in role with " + campusKOqualifier + ".  Members: " + roleMembers, 1, roleMembers.size());
576 
577         roleService.removePrincipalFromRole("user3", rCampus.getNamespaceCode(), rCampus.getName(), campusBLqualifier);
578 
579         assertFalse("principal should have been removed from role", roleService.principalHasRole("user3",
580                 Collections.singletonList(rCampus.getId()), campusBLqualifier));
581     }
582 
583     @Test
584     public void testAddQualifiedPrincipalToRoleTwice() {
585         Role rCampus = roleService.getRole("r-campus");
586         // Test with qualifying conditions
587         Map<String, String> campusBLqualifier = Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL");
588 
589         List<RoleMembership> roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
590         // clean the role out
591         for ( RoleMembership rm : roleMembers ) {
592             roleService.removePrincipalFromRole(rm.getMemberId(), rCampus.getNamespaceCode(), rCampus.getName(), campusBLqualifier);
593         }
594         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
595 
596         // make sure they're gone
597         assertEquals("Pre-check failed - should not be any members with campus code BL.  Members: " + roleMembers, 0, roleMembers.size());
598 
599         RoleMember rm1 = roleService.assignPrincipalToRole("user3", rCampus.getNamespaceCode(), rCampus.getName(),
600                 campusBLqualifier);
601         assertTrue("user3 should be assigned to role", roleService.principalHasRole("user3",
602                 Collections.singletonList(rCampus.getId()), campusBLqualifier));
603         assertNotNull( "Role member ID should have been assigned", rm1.getId() );
604         // attempt to add the user again
605         RoleMember rm2 = roleService.assignPrincipalToRole("user3", rCampus.getNamespaceCode(), rCampus.getName(),
606                 campusBLqualifier);
607         assertTrue("user3 should be still assigned to role", roleService.principalHasRole("user3",
608                 Collections.singletonList(rCampus.getId()), campusBLqualifier));
609         assertNotNull( "Role member ID should have been assigned", rm1.getId() );
610         assertEquals( "Role member ID be the same as previous assignment since user and qualifiers are the same",
611                 rm1.getId(),
612                 rm2.getId() );
613 
614         roleMembers = roleService.getRoleMembers(Collections.singletonList(rCampus.getId()), campusBLqualifier);
615 
616         assertEquals("Should only be one principal in role with campus code BL.  Members: " + roleMembers, 1, roleMembers.size());
617 
618         roleService.removePrincipalFromRole("user3", rCampus.getNamespaceCode(), rCampus.getName(), campusBLqualifier);
619 
620         assertFalse("principal should have been removed from role", roleService.principalHasRole("user3",
621                 Collections.singletonList(rCampus.getId()), campusBLqualifier));
622     }
623 
624 	/**
625 	 * Tests to ensure that a circular role membership cannot be created via the RoleService.
626 	 *
627 	 * @throws Exception
628 	 */
629 	@Test (expected=IllegalArgumentException.class)
630 	public void testCircularRoleAssignment() {
631 		Map<String, String> map = new HashMap<String, String>();
632 		List <String>roleIds = new ArrayList<String>();
633 		roleIds.add("r1");
634 		roleService.assignRoleToRole("r5", "AUTH_SVC_TEST2", "RoleThree", map);
635 	}
636 
637     protected RoleResponsibilityAction createRoleResponsibilityAction() {
638         List<RoleMembership> members = roleService.getRoleMembers(Collections.singletonList("r1"), null);
639         RoleMembership rm = members.get(0);
640 
641         RoleResponsibilityAction.Builder builder = RoleResponsibilityAction.Builder.create();
642         builder.setRoleMemberId(rm.getMemberId());
643         builder.setActionTypeCode(ActionType.APPROVE.getCode());
644 
645         RoleResponsibilityAction saved = roleService.createRoleResponsibilityAction(builder.build());
646         List<RoleResponsibilityAction> rra = roleService.getRoleMemberResponsibilityActions(rm.getMemberId());
647         assertEquals("incorrect number of RoleResponsibilityAction returned", 1, rra.size());
648         assertEquals("saved RoleResponsibilityAction does not match expected", saved, rra.get(0));
649 
650         return rra.get(0);
651     }
652 
653     @Test
654     public void testGetRoleMembers() {
655         List<RoleMembership> members = roleService.getRoleMembers(Collections.singletonList("r1"), null);
656         assertNotNull( "returned member list should not be null", members);
657         assertEquals("Wrong numbers of members in the role", 2, members.size());
658     }
659 
660     @Test
661     public void testGetRoleMembersWithExactMatchRoleTypeEmptyQualifier() {
662         Role rCampus = roleService.getRole("r-campus");
663         assertNotNull( "Campus-based role missing from test data", rCampus );
664         assertEquals( "Campus role type incorrect", "kt-campus", rCampus.getKimTypeId());
665         List<RoleMembership> members = roleService.getRoleMembers(Collections.singletonList("r-campus"), Collections.<String,String>emptyMap());
666         assertNotNull( "returned member list should not be null", members);
667         assertEquals("Wrong numbers of members in the role: " + members, 2, members.size());
668     }
669 
670     @Test
671     public void testGetRoleMembersWithExactMatchRoleType() {
672         Role rCampus = roleService.getRole("r-campus");
673         assertNotNull( "Campus-based role missing from test data", rCampus );
674         assertEquals( "Campus role type incorrect", "kt-campus", rCampus.getKimTypeId());
675         List<RoleMembership> members = roleService.getRoleMembers(Collections.singletonList("r-campus"), Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL"));
676         assertNotNull( "returned member list should not be null", members);
677         assertEquals("Wrong numbers of members returned from role: " + members, 1, members.size());
678     }
679 
680     @Test
681     public void testRemoveRoleFromRoleWithExactQualification() {
682         Role rCampus = roleService.getRole("r-campus-2");
683         assertNotNull( "Campus-based role missing from test data", rCampus );
684         assertEquals( "Campus role type incorrect", "kt-campus", rCampus.getKimTypeId());
685 
686         List<RoleMembership> firstLevelRoleMembers = roleService.getFirstLevelRoleMembers(Collections.singletonList("r-campus-2"));
687         assertEquals("wrong number of role members: " + firstLevelRoleMembers, 2, firstLevelRoleMembers.size());
688 
689         // Find the role member for BL and run some sanity checks on the data
690         RoleMembership blRoleMember = null;
691         RoleMembership nonBlRoleMember = null;
692         for ( RoleMembership rm : firstLevelRoleMembers ) {
693             if ( StringUtils.equals( rm.getQualifier().get(KimConstants.AttributeConstants.CAMPUS_CODE), "BL" ) ) {
694                 blRoleMember = rm;
695             } else {
696                 nonBlRoleMember = rm;
697             }
698         }
699         assertNotNull( "Both role members have qualifer BL, the test can not function", nonBlRoleMember);
700         assertNotNull( "Neither role member has qualifer BL, the test can not function", blRoleMember);
701         assertEquals( "The BL role member needs to be a role", MemberType.ROLE, blRoleMember.getType() );
702         Role blMemberRole = roleService.getRole( blRoleMember.getMemberId() );
703         assertNotNull( "role specified on BL role member does not exist", blMemberRole );
704 
705         roleService.removeRoleFromRole(blRoleMember.getMemberId(), rCampus.getNamespaceCode(), rCampus.getName(), Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL"));
706 
707         firstLevelRoleMembers = roleService.getFirstLevelRoleMembers(Collections.singletonList("r-campus-2"));
708         assertEquals("wrong number of role members after removal: " + firstLevelRoleMembers, 1, firstLevelRoleMembers.size());
709 
710         assertEquals("Wrong role member remains", "r1", firstLevelRoleMembers.get(0).getMemberId() );
711     }
712 
713     @Test
714     public void testGetRoleQualifersForPrincipalByNamespaceAndRolenameWithoutQualifier() {
715         Role rCampus = roleService.getRoleByNamespaceCodeAndName("AUTH_SVC_TEST2", "Campus Reviewer");
716         assertNotNull( "Campus-based role missing from test data", rCampus );
717         assertEquals( "Campus role type incorrect", "kt-campus", rCampus.getKimTypeId());
718 
719         List<Map<String, String>> qualifiers = roleService.getRoleQualifersForPrincipalByNamespaceAndRolename("p9", "AUTH_SVC_TEST2", "Campus Reviewer", Collections.<String,String>emptyMap() );
720         assertNotNull( "Returned qualifier list should not be null", qualifiers );
721         assertEquals( "Qualifier list should have one entry", 1, qualifiers.size() );
722         assertTrue( "campus code qualifier missing", qualifiers.get(0).containsKey(KimConstants.AttributeConstants.CAMPUS_CODE) );
723         assertEquals( "campus code qualifier incorrect", "BL", qualifiers.get(0).get(KimConstants.AttributeConstants.CAMPUS_CODE) );
724     }
725 
726     @Test
727     public void testGetRoleQualifersForPrincipalByNamespaceAndRolenameWithQualifier() {
728         Role rCampus = roleService.getRoleByNamespaceCodeAndName("AUTH_SVC_TEST2", "Campus Reviewer");
729         assertNotNull( "Campus-based role missing from test data", rCampus );
730         assertEquals( "Campus role type incorrect", "kt-campus", rCampus.getKimTypeId());
731 
732         List<Map<String, String>> qualifiers = roleService.getRoleQualifersForPrincipalByNamespaceAndRolename("p9", "AUTH_SVC_TEST2", "Campus Reviewer", Collections.singletonMap(KimConstants.AttributeConstants.CAMPUS_CODE, "BL") );
733         assertNotNull( "Returned qualifier list should not be null", qualifiers );
734         assertEquals( "Qualifier list should have one entry", 1, qualifiers.size() );
735         assertTrue( "campus code qualifier missing", qualifiers.get(0).containsKey(KimConstants.AttributeConstants.CAMPUS_CODE) );
736         assertEquals( "campus code qualifier incorrect", "BL", qualifiers.get(0).get(KimConstants.AttributeConstants.CAMPUS_CODE) );
737     }
738 
739     @Test
740     public void testCreateRoleResponsibilityAction() {
741         createRoleResponsibilityAction();
742     }
743 
744     @Test
745     public void testUpdateRoleResponsibilityAction() {
746         RoleResponsibilityAction rra = createRoleResponsibilityAction();
747         RoleResponsibilityAction.Builder builder = RoleResponsibilityAction.Builder.create(rra);
748         assertFalse(builder.isForceAction());
749         builder.setForceAction(true);
750         builder.setActionTypeCode(ActionType.ACKNOWLEDGE.getCode());
751 
752         RoleResponsibilityAction updated = roleService.updateRoleResponsibilityAction(builder.build());
753         builder.setVersionNumber(updated.getVersionNumber());
754         assertEquals(builder.build(), updated);
755 
756         // test that the value for rolemember is updated and not cached
757         List<RoleResponsibilityAction> rras = roleService.getRoleMemberResponsibilityActions(rra.getRoleMemberId());
758         assertEquals("incorrect number of RoleResponsibilityAction returned", 1, rras.size());
759         assertEquals("updated RoleResponsibilityAction does not match expected", updated, rras.get(0));
760     }
761 
762     @Test
763     public void testDeleteRoleResponsibilityAction() {
764         RoleResponsibilityAction rra = createRoleResponsibilityAction();
765 
766         roleService.deleteRoleResponsibilityAction(rra.getId());
767 
768         List<RoleResponsibilityAction> rras = roleService.getRoleMemberResponsibilityActions(rra.getRoleMemberId());
769         assertEquals(0, rras.size());
770 
771         try {
772             roleService.deleteRoleResponsibilityAction(rra.getId());
773             fail("Expected to throw RiceIllegalStateException due to missing RuleResponsibilityAction");
774         } catch (RiceIllegalStateException rise) {
775             // expected
776         }
777     }
778 }