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