View Javadoc

1   /*
2    * Copyright 2006-2011 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  
17  package org.kuali.rice.kim.service.impl;
18  
19  import org.apache.commons.collections.CollectionUtils;
20  import org.apache.commons.lang.StringUtils;
21  import org.apache.log4j.Logger;
22  import org.kuali.rice.core.api.config.property.ConfigContext;
23  import org.kuali.rice.core.api.parameter.Parameter;
24  import org.kuali.rice.core.framework.parameter.ParameterService;
25  import org.kuali.rice.core.framework.services.CoreFrameworkServiceLocator;
26  import org.kuali.rice.kim.api.group.Group;
27  import org.kuali.rice.kim.api.group.GroupMember;
28  import org.kuali.rice.kim.api.group.GroupService;
29  import org.kuali.rice.kim.api.identity.address.EntityAddress;
30  import org.kuali.rice.kim.api.identity.address.EntityAddressContract;
31  import org.kuali.rice.kim.api.identity.affiliation.EntityAffiliation;
32  import org.kuali.rice.kim.api.identity.email.EntityEmail;
33  import org.kuali.rice.kim.api.identity.email.EntityEmailContract;
34  import org.kuali.rice.kim.api.identity.employment.EntityEmployment;
35  import org.kuali.rice.kim.api.identity.entity.Entity;
36  import org.kuali.rice.kim.api.identity.name.EntityName;
37  import org.kuali.rice.kim.api.identity.phone.EntityPhone;
38  import org.kuali.rice.kim.api.identity.phone.EntityPhoneContract;
39  import org.kuali.rice.kim.api.identity.principal.Principal;
40  import org.kuali.rice.kim.api.identity.privacy.EntityPrivacyPreferences;
41  import org.kuali.rice.kim.api.identity.type.EntityTypeData;
42  import org.kuali.rice.kim.api.responsibility.ResponsibilityService;
43  import org.kuali.rice.kim.api.role.Role;
44  import org.kuali.rice.kim.api.role.RoleMember;
45  import org.kuali.rice.kim.api.role.RoleService;
46  import org.kuali.rice.kim.api.services.IdentityService;
47  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
48  import org.kuali.rice.kim.api.type.KimType;
49  import org.kuali.rice.kim.api.type.KimTypeAttribute;
50  import org.kuali.rice.kim.api.type.KimTypeInfoService;
51  import org.kuali.rice.kim.api.type.KimTypeService;
52  import org.kuali.rice.kim.bo.Person;
53  import org.kuali.rice.kim.bo.types.dto.AttributeDefinitionMap;
54  import org.kuali.rice.kim.bo.ui.GroupDocumentMember;
55  import org.kuali.rice.kim.bo.ui.GroupDocumentQualifier;
56  import org.kuali.rice.kim.bo.ui.KimDocumentRoleMember;
57  import org.kuali.rice.kim.bo.ui.KimDocumentRolePermission;
58  import org.kuali.rice.kim.bo.ui.KimDocumentRoleQualifier;
59  import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibility;
60  import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibilityAction;
61  import org.kuali.rice.kim.bo.ui.PersonDocumentAddress;
62  import org.kuali.rice.kim.bo.ui.PersonDocumentAffiliation;
63  import org.kuali.rice.kim.bo.ui.PersonDocumentEmail;
64  import org.kuali.rice.kim.bo.ui.PersonDocumentEmploymentInfo;
65  import org.kuali.rice.kim.bo.ui.PersonDocumentGroup;
66  import org.kuali.rice.kim.bo.ui.PersonDocumentName;
67  import org.kuali.rice.kim.bo.ui.PersonDocumentPhone;
68  import org.kuali.rice.kim.bo.ui.PersonDocumentPrivacy;
69  import org.kuali.rice.kim.bo.ui.PersonDocumentRole;
70  import org.kuali.rice.kim.bo.ui.RoleDocumentDelegation;
71  import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMember;
72  import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMemberQualifier;
73  import org.kuali.rice.kim.document.IdentityManagementGroupDocument;
74  import org.kuali.rice.kim.document.IdentityManagementPersonDocument;
75  import org.kuali.rice.kim.document.IdentityManagementRoleDocument;
76  import org.kuali.rice.kim.impl.common.attribute.KimAttributeDataBo;
77  import org.kuali.rice.kim.impl.common.delegate.DelegateBo;
78  import org.kuali.rice.kim.impl.common.delegate.DelegateMemberAttributeDataBo;
79  import org.kuali.rice.kim.impl.common.delegate.DelegateMemberBo;
80  import org.kuali.rice.kim.impl.group.GroupAttributeBo;
81  import org.kuali.rice.kim.impl.group.GroupBo;
82  import org.kuali.rice.kim.impl.group.GroupMemberBo;
83  import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
84  import org.kuali.rice.kim.impl.identity.affiliation.EntityAffiliationBo;
85  import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
86  import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentBo;
87  import org.kuali.rice.kim.impl.identity.entity.EntityBo;
88  import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
89  import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
90  import org.kuali.rice.kim.impl.identity.principal.PrincipalBo;
91  import org.kuali.rice.kim.impl.identity.privacy.EntityPrivacyPreferencesBo;
92  import org.kuali.rice.kim.impl.identity.type.EntityTypeDataBo;
93  import org.kuali.rice.kim.impl.permission.PermissionBo;
94  import org.kuali.rice.kim.impl.responsibility.ResponsibilityInternalService;
95  import org.kuali.rice.kim.impl.role.RoleBo;
96  import org.kuali.rice.kim.impl.role.RoleMemberAttributeDataBo;
97  import org.kuali.rice.kim.impl.role.RoleMemberBo;
98  import org.kuali.rice.kim.impl.role.RolePermissionBo;
99  import org.kuali.rice.kim.impl.role.RoleResponsibilityActionBo;
100 import org.kuali.rice.kim.impl.role.RoleResponsibilityBo;
101 import org.kuali.rice.kim.impl.services.KIMServiceLocatorInternal;
102 import org.kuali.rice.kim.impl.type.KimTypeBo;
103 import org.kuali.rice.kim.service.IdentityManagementNotificationService;
104 import org.kuali.rice.kim.service.KIMServiceLocatorWeb;
105 import org.kuali.rice.kim.service.PermissionService;
106 import org.kuali.rice.kim.service.UiDocumentService;
107 import org.kuali.rice.kim.util.KIMPropertyConstants;
108 import org.kuali.rice.kim.util.KimCommonUtilsInternal;
109 import org.kuali.rice.kim.util.KimConstants;
110 import org.kuali.rice.kim.util.KimConstants.KimGroupMemberTypes;
111 import org.kuali.rice.kns.datadictionary.control.TextControlDefinition;
112 import org.kuali.rice.krad.bo.BusinessObject;
113 import org.kuali.rice.krad.bo.PersistableBusinessObject;
114 import org.kuali.rice.krad.datadictionary.AttributeDefinition;
115 import org.kuali.rice.krad.datadictionary.KimAttributeDefinition;
116 import org.kuali.rice.krad.datadictionary.KimDataDictionaryAttributeDefinition;
117 import org.kuali.rice.krad.datadictionary.control.ControlDefinition;
118 import org.kuali.rice.krad.document.Document;
119 import org.kuali.rice.krad.service.BusinessObjectService;
120 import org.kuali.rice.krad.service.DocumentHelperService;
121 import org.kuali.rice.krad.service.KRADServiceLocator;
122 import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
123 import org.kuali.rice.krad.util.KRADConstants;
124 import org.kuali.rice.krad.util.ObjectUtils;
125 import org.kuali.rice.ksb.api.KsbApiServiceLocator;
126 
127 import javax.xml.namespace.QName;
128 import java.sql.Timestamp;
129 import java.util.ArrayList;
130 import java.util.Collection;
131 import java.util.Collections;
132 import java.util.Comparator;
133 import java.util.HashMap;
134 import java.util.HashSet;
135 import java.util.List;
136 import java.util.Map;
137 import java.util.Set;
138 
139 /**
140  * This is a description of what this class does - shyu don't forget to fill this in.
141  *
142  * @author Kuali Rice Team (rice.collab@kuali.org)
143  *
144  */
145 public class UiDocumentServiceImpl implements UiDocumentService {
146 	private static final Logger LOG = Logger.getLogger(UiDocumentServiceImpl.class);
147 	private static final String SHOW_BLANK_QUALIFIERS = "kim.show.blank.qualifiers";
148 	
149 	private RoleService roleService;
150 	private BusinessObjectService businessObjectService;
151 	private IdentityService identityService;
152     private PermissionService permissionService;
153 	private GroupService groupService;
154 	private ResponsibilityService responsibilityService;
155     private ResponsibilityInternalService responsibilityInternalService;
156 	private KimTypeInfoService kimTypeInfoService;
157     private DocumentHelperService documentHelperService;
158     private ParameterService parameterService;
159 
160 
161 	/**
162 	 * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
163 	 */
164 	public void saveEntityPerson(
165 	    IdentityManagementPersonDocument identityManagementPersonDocument) {
166 		EntityBo kimEntity = new EntityBo();
167 		EntityBo origEntity = getEntityBo(identityManagementPersonDocument.getEntityId());
168 		boolean creatingNew = true;
169 		if (origEntity == null) {
170 			origEntity = new EntityBo();
171 			kimEntity.setActive(true);
172 		} else {
173 			// TODO : in order to resolve optimistic locking issue. has to get identity and set the version number if identity records matched
174 			// Need to look into this.
175 			//kimEntity = origEntity;
176 			kimEntity.setActive(origEntity.isActive());
177 			kimEntity.setVersionNumber(origEntity.getVersionNumber());
178 			creatingNew = false;
179 		}
180 
181 		kimEntity.setId(identityManagementPersonDocument.getEntityId());
182 		String initiatorPrincipalId = getInitiatorPrincipalId(identityManagementPersonDocument);
183 		boolean inactivatingPrincipal = false;
184 		if(canModifyEntity(initiatorPrincipalId, identityManagementPersonDocument.getPrincipalId())){
185 			inactivatingPrincipal = setupPrincipal(identityManagementPersonDocument, kimEntity, origEntity.getPrincipals());
186 			setupAffiliation(identityManagementPersonDocument, kimEntity, origEntity.getAffiliations(), origEntity.getEmploymentInformation());
187 			setupName(identityManagementPersonDocument, kimEntity, origEntity.getNames());
188 		// entitytype
189 			List<EntityTypeDataBo> entityTypes = new ArrayList<EntityTypeDataBo>();
190 			EntityTypeDataBo entityType = new EntityTypeDataBo();
191 			entityType.setEntityId(identityManagementPersonDocument.getEntityId());
192 			entityType.setEntityTypeCode(KimConstants.EntityTypes.PERSON);
193 			entityType.setActive(true);
194 			entityTypes.add(entityType);
195 			EntityTypeDataBo origEntityType = new EntityTypeDataBo();
196 			for (EntityTypeDataBo type : origEntity.getEntityTypes()) {
197 				// should check identity.entitytypeid, but it's not persist in persondoc yet
198 				if (type.getEntityTypeCode()!=null && StringUtils.equals(type.getEntityTypeCode(), entityType.getEntityTypeCode())) {
199 					origEntityType = type;
200 					entityType.setVersionNumber(type.getVersionNumber());
201 					entityType.setActive(type.isActive());
202 				}
203 			}
204 			setupPhone(identityManagementPersonDocument, entityType, origEntityType.getPhoneNumbers());
205 			setupEmail(identityManagementPersonDocument, entityType, origEntityType.getEmailAddresses());
206 			setupAddress(identityManagementPersonDocument, entityType, origEntityType.getAddresses());
207             kimEntity.setEntityTypes(entityTypes);
208 		} else{
209 			if(ObjectUtils.isNotNull(origEntity.getExternalIdentifiers())) {
210                 kimEntity.setExternalIdentifiers(origEntity.getExternalIdentifiers());
211             }
212 			if(ObjectUtils.isNotNull(origEntity.getEmploymentInformation())) {
213                 kimEntity.setEmploymentInformation(origEntity.getEmploymentInformation());
214             }
215 			if(ObjectUtils.isNotNull(origEntity.getAffiliations())) {
216                 kimEntity.setAffiliations(origEntity.getAffiliations());
217             }
218 			if(ObjectUtils.isNotNull(origEntity.getNames())) {
219                 kimEntity.setNames(origEntity.getNames());
220             }
221 			if(ObjectUtils.isNotNull(origEntity.getEntityTypes())) {
222                 kimEntity.setEntityTypes(origEntity.getEntityTypes());
223             }
224 		}
225 		if(creatingNew || canOverrideEntityPrivacyPreferences(getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId())) {
226 			setupPrivacy(identityManagementPersonDocument, kimEntity, origEntity.getPrivacyPreferences());
227 		} else {
228 			if(ObjectUtils.isNotNull(origEntity.getPrivacyPreferences())) {
229 				kimEntity.setPrivacyPreferences(origEntity.getPrivacyPreferences());
230 			}
231 		}
232 		List <GroupMemberBo>  groupPrincipals = populateGroupMembers(identityManagementPersonDocument);
233 		List <RoleMemberBo>  rolePrincipals = populateRoleMembers(identityManagementPersonDocument);
234 		List <DelegateBo> personDelegations = populateDelegations(identityManagementPersonDocument);
235 		List <PersistableBusinessObject> bos = new ArrayList<PersistableBusinessObject>();
236 		List <RoleResponsibilityActionBo> roleRspActions = populateRoleRspActions(identityManagementPersonDocument);
237 		List <RoleMemberAttributeDataBo> blankRoleMemberAttrs = getBlankRoleMemberAttrs(rolePrincipals);
238 		bos.add(kimEntity);
239 		//if(ObjectUtils.isNotNull(kimEntity.getPrivacyPreferences()))
240 		//	bos.add(kimEntity.getPrivacyPreferences());
241 		bos.addAll(groupPrincipals);
242 		bos.addAll(rolePrincipals);
243 		bos.addAll(roleRspActions);
244 		bos.addAll(personDelegations);
245 		// boservice.save(bos) does not handle deleteawarelist
246 		getBusinessObjectService().save(bos);
247 
248 		//KimApiServiceLocator.getIdentityService().flushEntityPrincipalCaches();
249 		IdentityManagementNotificationService service = (IdentityManagementNotificationService) KsbApiServiceLocator.getMessageHelper().getServiceAsynchronously(new QName("KIM", "kimIdentityManagementNotificationService"));
250 		service.principalUpdated();
251 
252 		if (!blankRoleMemberAttrs.isEmpty()) {
253 			getBusinessObjectService().delete(blankRoleMemberAttrs);
254 		}
255 		if ( inactivatingPrincipal ) {
256 			//when a person is inactivated, inactivate their group, role, and delegation memberships
257 			KimApiServiceLocator.getRoleService().principalInactivated(identityManagementPersonDocument.getPrincipalId());
258 		}
259 	}
260 
261 	private String getInitiatorPrincipalId(Document document){
262 		try{
263 			return document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
264 		} catch(Exception ex){
265 			return null;
266 		}
267 	}
268 	/**
269 	 *
270 	 * @see org.kuali.rice.kim.service.UiDocumentService#getAttributeEntries(AttributeDefinitionMap)
271 	 */
272 	public Map<String,Object> getAttributeEntries( AttributeDefinitionMap definitions ) {
273 		Map<String,Object> attributeEntries = new HashMap<String,Object>();
274 		if(definitions!=null){
275 	        for (String key : definitions.keySet()) {
276 				AttributeDefinition definition = definitions.get(key);
277 				Map<String,Object> attribute = new HashMap<String,Object>();
278 				if (definition instanceof KimDataDictionaryAttributeDefinition) {
279 	//				AttributeDefinition definition = ((KimDataDictionaryAttributeDefinition) attrDefinition)
280 	//						.getDataDictionaryAttributeDefinition();
281 					ControlDefinition control = definition.getControl();
282 					if (control.isSelect() 
283 							|| control.isRadio()) {
284 						Map<String,Object> controlMap = new HashMap<String,Object>();
285 			            if (control.isSelect()) {
286 			            	controlMap.put("select", "true");
287 			            } else {
288 			            	controlMap.put("radio", "true");
289 			            }
290 			            controlMap.put("valuesFinder", control.getValuesFinderClass());
291 			            if (control.getBusinessObjectClass() != null) {
292 			                controlMap.put("businessObject", control.getBusinessObjectClass());
293 			            }
294 			            if (StringUtils.isNotEmpty(control.getKeyAttribute())) {
295 			                controlMap.put("keyAttribute", control.getKeyAttribute());
296 			            }
297 			            if (StringUtils.isNotEmpty(control.getLabelAttribute())) {
298 			                controlMap.put("labelAttribute", control.getLabelAttribute());
299 			            }
300 			            if (control.getIncludeKeyInLabel() != null) {
301 			                controlMap.put("includeKeyInLabel", control.getIncludeKeyInLabel().toString());
302 			            }
303 						attribute.put("control", controlMap);
304 					} else {
305 			        	// FIXME: Huh!?!?, control is a Map in the above code but a ControlDefinition here?!?!?
306 			        	// Maybe this should use the AttributesMapBuilder code to create this
307 			        	attribute.put("control", definition.getControl());
308 			        }
309 					attribute.put("name", definition.getName());
310 					attribute.put("label", definition.getLabel());
311 					attribute.put("shortLabel", definition.getShortLabel());
312 					attribute.put("maxLength", definition.getMaxLength());
313 					attribute.put("required", definition.isRequired());
314 					attributeEntries.put(definition.getName(),attribute);
315 				} else {
316 					TextControlDefinition control = new TextControlDefinition();
317 					control.setSize(10);
318 					attribute.put("name", definition.getName());
319 					attribute.put("control", control);
320 					attribute.put("label", definition.getLabel());
321 					attribute.put("maxLength", 20);
322 					attribute.put("required", true);
323 					attribute.put("shortLabel", definition.getLabel());
324 					attributeEntries.put(definition.getName(),attribute);
325 				}
326 			}
327 		}
328         return attributeEntries;
329 	}
330 
331 
332 	/**
333 	 *
334 	 * @see org.kuali.rice.kim.service.UiDocumentService#loadEntityToPersonDoc(IdentityManagementPersonDocument, String)
335 	 */
336 	public void loadEntityToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument, String principalId) {
337 		Principal principal = this.getIdentityService().getPrincipal(principalId);
338         if(principal==null) {
339         	throw new RuntimeException("Principal does not exist for principal id:"+principalId);
340         }
341 
342         identityManagementPersonDocument.setPrincipalId(principal.getPrincipalId());
343         identityManagementPersonDocument.setPrincipalName(principal.getPrincipalName());
344         identityManagementPersonDocument.setPassword(principal.getPassword());
345         identityManagementPersonDocument.setActive(principal.isActive());
346         Entity kimEntity = this.getIdentityService().getEntity(principal.getEntityId());
347 		identityManagementPersonDocument.setEntityId(kimEntity.getId());
348 		if ( ObjectUtils.isNotNull( kimEntity.getPrivacyPreferences() ) ) {
349 			identityManagementPersonDocument.setPrivacy(loadPrivacyReferences(kimEntity.getPrivacyPreferences()));
350 		}
351 		//identityManagementPersonDocument.setActive(kimEntity.isActive());
352 		identityManagementPersonDocument.setAffiliations(loadAffiliations(kimEntity.getAffiliations(),kimEntity.getEmploymentInformation()));
353 		identityManagementPersonDocument.setNames(loadNames( identityManagementPersonDocument, principalId, kimEntity.getNames(), identityManagementPersonDocument.getPrivacy().isSuppressName() ));
354 		EntityTypeData entityType = null;
355 		for (EntityTypeData type : kimEntity.getEntityTypes()) {
356 			if (KimConstants.EntityTypes.PERSON.equals(type.getEntityTypeCode())) {
357 				entityType = EntityTypeData.Builder.create(type).build();
358 			}
359 		}
360 
361 		if(entityType!=null){
362 			identityManagementPersonDocument.setEmails(loadEmails(identityManagementPersonDocument, principalId, entityType.getEmailAddresses(), identityManagementPersonDocument.getPrivacy().isSuppressEmail()));
363 			identityManagementPersonDocument.setPhones(loadPhones(identityManagementPersonDocument, principalId, entityType.getPhoneNumbers(), identityManagementPersonDocument.getPrivacy().isSuppressPhone()));
364 			identityManagementPersonDocument.setAddrs(loadAddresses(identityManagementPersonDocument, principalId, entityType.getAddresses(), identityManagementPersonDocument.getPrivacy().isSuppressAddress()));
365 		}
366 
367 		List<Group> groups = getGroupService().getGroups(getGroupService().getDirectGroupIdsForPrincipal(identityManagementPersonDocument.getPrincipalId()));
368 		loadGroupToPersonDoc(identityManagementPersonDocument, groups);
369 		loadRoleToPersonDoc(identityManagementPersonDocument);
370 		loadDelegationsToPersonDoc(identityManagementPersonDocument);
371 	}
372 
373     @SuppressWarnings("unchecked")
374 	public List<DelegateBo> getPersonDelegations(String principalId){
375 		if(principalId==null) {
376 			return new ArrayList<DelegateBo>();
377         }
378 		Map<String,String> criteria = new HashMap<String,String>(1);
379 		criteria.put(KimConstants.PrimaryKeyConstants.MEMBER_ID, principalId);
380 		criteria.put( KIMPropertyConstants.DelegationMember.MEMBER_TYPE_CODE, Role.PRINCIPAL_MEMBER_TYPE );
381 		List<DelegateMemberBo> delegationMembers = (List<DelegateMemberBo>)getBusinessObjectService().findMatching(DelegateMemberBo.class, criteria);
382 		List<DelegateBo> delegations = new ArrayList<DelegateBo>();
383 		List<String> delegationIds = new ArrayList<String>();
384 		if(ObjectUtils.isNotNull(delegationMembers)){
385 			for(DelegateMemberBo delegationMember: delegationMembers){
386 				if(!delegationIds.contains(delegationMember.getDelegationId())){
387 					delegationIds.add(delegationMember.getDelegationId());
388 					criteria = new HashMap<String,String>(1);
389 					criteria.put(KimConstants.PrimaryKeyConstants.DELEGATION_ID, delegationMember.getDelegationId());
390 					delegations.add(getBusinessObjectService().findByPrimaryKey(DelegateBo.class, criteria));
391 				}
392 			}
393 		}
394 		return delegations;
395 	}
396 
397 
398     protected void loadDelegationsToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument){
399 		List<RoleDocumentDelegation> delList = new ArrayList<RoleDocumentDelegation>();
400 		RoleDocumentDelegation documentDelegation;
401 		List<DelegateBo> origDelegations = getPersonDelegations(identityManagementPersonDocument.getPrincipalId());
402 		if(ObjectUtils.isNotNull(origDelegations)){
403 			for(DelegateBo del: origDelegations){
404 				if(del.isActive()){
405 					documentDelegation = new RoleDocumentDelegation();
406 					documentDelegation.setActive(del.isActive());
407 					documentDelegation.setDelegationId(del.getDelegationId());
408 					documentDelegation.setDelegationTypeCode(del.getDelegationTypeCode());
409 					documentDelegation.setKimTypeId(del.getKimTypeId());
410 					documentDelegation.setMembers(
411 							loadDelegationMembers(identityManagementPersonDocument,
412 									del.getMembers(), (RoleBo)getMember(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE, del.getRoleId())));
413 					documentDelegation.setRoleId(del.getRoleId());
414 					documentDelegation.setEdit(true);
415 					delList.add(documentDelegation);
416 				}
417 			}
418 		}
419 		identityManagementPersonDocument.setDelegations(delList);
420 		setDelegationMembersInDocument(identityManagementPersonDocument);
421 	}
422 
423 	public void setDelegationMembersInDocument(IdentityManagementPersonDocument identityManagementPersonDocument){
424 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getDelegations())){
425 			for(RoleDocumentDelegation delegation: identityManagementPersonDocument.getDelegations()){
426 				if(CollectionUtils.isNotEmpty(delegation.getMembers())){
427 					for(RoleDocumentDelegationMember member: delegation.getMembers()){
428 						if (StringUtils.equals(member.getMemberId(), identityManagementPersonDocument.getPrincipalId()))
429 						{
430 							member.setDelegationTypeCode(delegation.getDelegationTypeCode());
431 							identityManagementPersonDocument.getDelegationMembers().add(member);
432 						}
433 					}
434 				}
435 			}
436 		}
437 	}
438 
439     protected List<RoleDocumentDelegationMember> loadDelegationMembers(
440     		IdentityManagementPersonDocument identityManagementPersonDocument, List<DelegateMemberBo> members, RoleBo roleImpl){
441 		List<RoleDocumentDelegationMember> pndMembers = new ArrayList<RoleDocumentDelegationMember>();
442 		RoleDocumentDelegationMember pndMember;
443 		RoleMemberBo roleMember;
444 		if(ObjectUtils.isNotNull(members)){
445 			for(DelegateMemberBo member: members){
446 				pndMember = new RoleDocumentDelegationMember();
447 				pndMember.setActiveFromDate(member.getActiveFromDate());
448 				pndMember.setActiveToDate(member.getActiveToDate());
449 				pndMember.setActive(member.isActive(new Timestamp(System.currentTimeMillis())));
450 				pndMember.setRoleBo(roleImpl);
451 				if(pndMember.isActive()){
452 					KimCommonUtilsInternal.copyProperties(pndMember, member);
453 					pndMember.setRoleMemberId(member.getRoleMemberId());
454 					roleMember = getRoleMemberForRoleMemberId(member.getRoleMemberId());
455 					if(roleMember!=null){
456 						pndMember.setRoleMemberName(getMemberName(roleMember.getMemberTypeCode(), roleMember.getMemberId()));
457 						pndMember.setRoleMemberNamespaceCode(getMemberNamespaceCode(roleMember.getMemberTypeCode(), roleMember.getMemberId()));
458 					}
459 					pndMember.setMemberNamespaceCode(getMemberNamespaceCode(member.getTypeCode(), member.getMemberId()));
460 					pndMember.setMemberName(getMemberName(member.getTypeCode(), member.getMemberId()));
461 					pndMember.setEdit(true);
462 					pndMember.setQualifiers(loadDelegationMemberQualifiers(identityManagementPersonDocument, pndMember.getAttributesHelper().getDefinitions(), member.getAttributes()));
463 					pndMembers.add(pndMember);
464 				}
465 			}
466 		}
467 		return pndMembers;
468 	}
469 
470     protected List<RoleDocumentDelegationMemberQualifier> loadDelegationMemberQualifiers(IdentityManagementPersonDocument identityManagementPersonDocument,
471     		AttributeDefinitionMap origAttributeDefinitions, List<DelegateMemberAttributeDataBo> attributeDataList){
472 		List<RoleDocumentDelegationMemberQualifier> pndMemberRoleQualifiers = new ArrayList<RoleDocumentDelegationMemberQualifier>();
473 		RoleDocumentDelegationMemberQualifier pndMemberRoleQualifier;
474 		boolean attributePresent = false;
475 		String origAttributeId;
476 		if(origAttributeDefinitions!=null){
477 			for(String key: origAttributeDefinitions.keySet()) {
478 				origAttributeId = identityManagementPersonDocument.getKimAttributeDefnId(origAttributeDefinitions.get(key));
479 				if(ObjectUtils.isNotNull(attributeDataList)){
480 					for(DelegateMemberAttributeDataBo memberRoleQualifier: attributeDataList){
481 						if(StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
482 							pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
483 							pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
484 							pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
485 							pndMemberRoleQualifier.setDelegationMemberId(memberRoleQualifier.getAssignedToId());
486 							pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
487 							pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
488 							pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
489 							pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
490 							attributePresent = true;
491 						}
492 					}
493 				}
494 				if(!attributePresent){
495 					pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
496 					pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
497 					pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
498 				}
499 				attributePresent = false;
500 			}
501 		}
502 		return pndMemberRoleQualifiers;
503 	}
504 
505 	/**
506 	 *
507 	 * This method load related group data to pending document when usert initiate the 'edit'.
508 	 *
509 	 * @param identityManagementPersonDocument
510 	 * @param groups
511 	 */
512     protected void loadGroupToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument, List<? extends Group> groups) {
513         List <PersonDocumentGroup> docGroups = new ArrayList <PersonDocumentGroup>();
514         if(ObjectUtils.isNotNull(groups)){
515             List<String> directMemberPrincipalIds;
516             Collection<GroupMember> groupMemberships;
517             for (Group group: groups) {
518                 directMemberPrincipalIds = getGroupService().getDirectMemberPrincipalIds(group.getId());
519                 if(ObjectUtils.isNotNull(directMemberPrincipalIds)){
520                     directMemberPrincipalIds = new ArrayList<String>(new HashSet<String>(directMemberPrincipalIds));
521                     for (String memberId: directMemberPrincipalIds) {
522                         // other more direct methods for this ?
523                         // can't cast group to 'GroupImpl' because list is GroupInfo type
524                         if (StringUtils.equals(memberId, identityManagementPersonDocument.getPrincipalId())) {
525                             List<String> groupIds = new ArrayList<String>();
526                             groupIds.add(group.getId());
527                             groupMemberships = getGroupService().getMembers(groupIds);
528                             if(ObjectUtils.isNotNull(groupMemberships)){
529                                 for (GroupMember groupMember: groupMemberships) {
530                                     if (groupMember.isActive(new Timestamp(System.currentTimeMillis())) && StringUtils.equals(groupMember.getMemberId(), identityManagementPersonDocument.getPrincipalId()) &&
531                                         StringUtils.equals(groupMember.getTypeCode(), KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE)) {
532                                         // create one PersonDocumentGroup per GroupMembershipInfo **
533                                         PersonDocumentGroup docGroup = new PersonDocumentGroup();
534                                         docGroup.setGroupId(group.getId());
535                                         docGroup.setGroupName(group.getName());
536                                         docGroup.setNamespaceCode(group.getNamespaceCode());
537                                         docGroup.setPrincipalId(memberId);
538                                         docGroup.setGroupMemberId(groupMember.getId());
539                                         if (groupMember.getActiveFromDate() != null) {
540                                         	docGroup.setActiveFromDate(new Timestamp(groupMember.getActiveFromDate().getTime()));
541                                         }
542                                         if (groupMember.getActiveToDate() != null) {
543                                         	docGroup.setActiveToDate(new Timestamp(groupMember.getActiveToDate().getTime()));
544                                         }
545                                         docGroup.setEdit(true);
546                                         docGroups.add(docGroup);
547                                     }
548                                 }
549                             }
550                         }
551                     }
552                 }
553             }
554         }
555         identityManagementPersonDocument.setGroups(docGroups);
556     }
557 
558 	protected void loadRoleToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument) {
559 		List <PersonDocumentRole> docRoles = new ArrayList <PersonDocumentRole>();
560 		List<RoleBo> roles = getRolesForPrincipal(identityManagementPersonDocument.getPrincipalId());
561 		List<String> roleIds = new ArrayList<String>();
562 		if(ObjectUtils.isNotNull(roles)){
563 	        for (RoleBo role : roles) {
564 	        	if (!roleIds.contains(role.getId())) {
565 		        	PersonDocumentRole docRole = new PersonDocumentRole();
566 		        	docRole.setKimTypeId(role.getKimTypeId());
567 		        	docRole.setActive(role.isActive());
568 		        	docRole.setNamespaceCode(role.getNamespaceCode());
569 		        	docRole.setEdit(true);
570 		        	docRole.setRoleId(role.getId());
571 		        	docRole.setRoleName(role.getName());
572 		        	docRole.setRolePrncpls(populateDocRolePrncpl(role.getNamespaceCode(), role.getMembers(), identityManagementPersonDocument.getPrincipalId(), getAttributeDefinitionsForRole(docRole)));
573 		        	docRole.refreshReferenceObject("assignedResponsibilities");
574 		        	if(docRole.getRolePrncpls()!=null && !docRole.getRolePrncpls().isEmpty()){
575 		        		docRoles.add(docRole);
576 		        		roleIds.add(role.getId());
577 		        	}
578 	        	}
579 	        }
580 		}
581 		for (PersonDocumentRole role : docRoles) {
582 			role.setDefinitions(getAttributeDefinitionsForRole(role));
583         	// when post again, it will need this during populate
584             role.setNewRolePrncpl(new KimDocumentRoleMember());
585             if(role.getDefinitions()!=null){
586 	            for (String key : role.getDefinitions().keySet()) {
587 	            	KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
588 	            	//qualifier.setQualifierKey(key);
589 	            	setAttrDefnIdForQualifier(qualifier,role.getDefinitions().get(key));
590 	            	role.getNewRolePrncpl().getQualifiers().add(qualifier);
591 	            }
592             }
593             loadRoleRstAction(role);
594             role.setAttributeEntry( getAttributeEntries( role.getDefinitions() ) );
595 		}
596         //
597 
598         identityManagementPersonDocument.setRoles(docRoles);
599 	}
600 
601 	protected AttributeDefinitionMap getAttributeDefinitionsForRole(PersonDocumentRole role) {
602     	KimTypeService kimTypeService = KIMServiceLocatorWeb.getKimTypeService(KimTypeBo.to(role.getKimRoleType()));
603     	//it is possible that the the kimTypeService is coming from a remote application
604         // and therefore it can't be guarenteed that it is up and working, so using a try/catch to catch this possibility.
605         try {
606         	if ( kimTypeService != null ) {
607         		return kimTypeService.getAttributeDefinitions(role.getKimTypeId());
608         	}
609         } catch (Exception ex) {
610             LOG.warn("Not able to retrieve KimTypeService from remote system for KIM Role Type: " + role.getKimRoleType(), ex);
611         }
612     	return new AttributeDefinitionMap();
613 	}
614 
615 	protected void loadRoleRstAction(PersonDocumentRole role) {
616 		if(role!=null && CollectionUtils.isNotEmpty(role.getRolePrncpls())){
617 			for (KimDocumentRoleMember roleMbr : role.getRolePrncpls()) {
618 				List<RoleResponsibilityActionBo> actions = getRoleRspActions( roleMbr.getRoleMemberId());
619 				if(ObjectUtils.isNotNull(actions)){
620 					for (RoleResponsibilityActionBo entRoleRspAction :actions) {
621 						KimDocumentRoleResponsibilityAction roleRspAction = new KimDocumentRoleResponsibilityAction();
622 						roleRspAction.setRoleResponsibilityId(entRoleRspAction.getRoleResponsibilityId());
623 						roleRspAction.setActionTypeCode(entRoleRspAction.getActionTypeCode());
624 						roleRspAction.setActionPolicyCode(entRoleRspAction.getActionPolicyCode());
625 						roleRspAction.setPriorityNumber(entRoleRspAction.getPriorityNumber());
626 						roleRspAction.setRoleResponsibilityActionId(entRoleRspAction.getId());
627 						roleRspAction.refreshReferenceObject("roleResponsibility");
628 						roleMbr.getRoleRspActions().add(roleRspAction);
629 					}
630 				}
631 			}
632 		}
633 	}
634 
635 	protected void setAttrDefnIdForQualifier(KimDocumentRoleQualifier qualifier, AttributeDefinition definition) {
636     	qualifier.setKimAttrDefnId(getAttributeDefnId(definition));
637     	qualifier.refreshReferenceObject("kimAttribute");
638     }
639 
640 	protected String getAttributeDefnId(AttributeDefinition definition) {
641     	return ((KimAttributeDefinition)definition).getKimAttrDefnId();
642     }
643 
644 	private PrincipalBo getPrincipalImpl(String principalId) {
645 		Map<String,String> criteria = new HashMap<String,String>(1);
646         criteria.put(KIMPropertyConstants.Principal.PRINCIPAL_ID, principalId);
647 		return (PrincipalBo)getBusinessObjectService().findByPrimaryKey(PrincipalBo.class, criteria);
648 	}
649 
650 	public List<EntityEmployment> getEntityEmploymentInformationInfo(String entityId) {
651         EntityBo entityImpl = getEntityBo(entityId);
652         List<EntityEmployment> empInfos = new ArrayList<EntityEmployment>();
653         EntityEmployment empInfo;
654         if(ObjectUtils.isNotNull(entityImpl) && CollectionUtils.isNotEmpty(entityImpl.getEmploymentInformation())){
655         	for(EntityEmploymentBo empImpl: entityImpl.getEmploymentInformation()){
656             	empInfos.add(EntityEmploymentBo.to(empImpl));
657         	}
658         }
659         return empInfos;
660 	}
661 
662 	private EntityBo getEntityBo(String entityId) {
663 		EntityBo entityImpl = getBusinessObjectService().findBySinglePrimaryKey(EntityBo.class, entityId);
664         //TODO - remove this hack... This is here because currently jpa only seems to be going 2 levels deep on the eager fetching.
665 		if(entityImpl!=null  && entityImpl.getEntityTypes() != null) {
666         	for (EntityTypeDataBo et : entityImpl.getEntityTypes()) {
667         		et.refresh();
668         	}
669         }
670 		return entityImpl;
671 	}
672 
673     @SuppressWarnings("unchecked")
674 	protected List<RoleBo> getRolesForPrincipal(String principalId) {
675 		if ( principalId == null ) {
676 			return new ArrayList<RoleBo>();
677 		}
678 		Map<String,String> criteria = new HashMap<String,String>( 2 );
679 		criteria.put("members.memberId", principalId);
680 		criteria.put("members.memberTypeCode", Role.PRINCIPAL_MEMBER_TYPE);
681 		return (List<RoleBo>)getBusinessObjectService().findMatching(RoleBo.class, criteria);
682 	}
683 
684 	@SuppressWarnings("unchecked")
685 	protected List<RoleMemberBo> getRoleMembersForPrincipal(String principalId) {
686 		if ( principalId == null ) {
687 			return new ArrayList<RoleMemberBo>();
688 		}
689 		Map<String,String> criteria = new HashMap<String,String>( 2 );
690 		criteria.put("memberId", principalId);
691 		criteria.put("memberTypeCode", Role.PRINCIPAL_MEMBER_TYPE);
692 		return (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, criteria);
693 	}
694 
695 	public RoleMemberBo getRoleMember(String roleMemberId) {
696 		if ( roleMemberId == null ) {
697 			return null;
698 		}
699 		Map<String,String> criteria = new HashMap<String,String>( 2 );
700 		criteria.put("roleMemberId", roleMemberId);
701 		return getBusinessObjectService().findByPrimaryKey(RoleMemberBo.class, criteria);
702 	}
703 
704     @SuppressWarnings("unchecked")
705 	protected List<RoleResponsibilityActionBo> getRoleRspActions(String roleMemberId) {
706 		Map<String,String> criteria = new HashMap<String,String>( 1 );
707 		criteria.put(KIMPropertyConstants.RoleMember.ROLE_MEMBER_ID, roleMemberId);
708 		return (List<RoleResponsibilityActionBo>)getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
709 	}
710 
711     protected List<KimDocumentRoleMember> populateDocRolePrncpl(String namespaceCode, List <RoleMemberBo> roleMembers, String principalId, AttributeDefinitionMap definitions) {
712 		List <KimDocumentRoleMember> docRoleMembers = new ArrayList <KimDocumentRoleMember>();
713 		if(ObjectUtils.isNotNull(roleMembers)){
714 	    	for (RoleMemberBo rolePrincipal : roleMembers) {
715 	    		if (rolePrincipal.isActive(new Timestamp(System.currentTimeMillis())) && Role.PRINCIPAL_MEMBER_TYPE.equals(rolePrincipal.getMemberTypeCode()) &&
716 	    				StringUtils.equals(rolePrincipal.getMemberId(), principalId)) {
717 	        		KimDocumentRoleMember docRolePrncpl = new KimDocumentRoleMember();
718 	        		docRolePrncpl.setMemberId(rolePrincipal.getMemberId());
719 	        		docRolePrncpl.setRoleMemberId(rolePrincipal.getRoleMemberId());
720 	        		docRolePrncpl.setActive(rolePrincipal.isActive(new Timestamp(System.currentTimeMillis())));
721 	        		docRolePrncpl.setRoleId(rolePrincipal.getRoleId());
722 	        		docRolePrncpl.setActiveFromDate(rolePrincipal.getActiveFromDate());
723 	        		docRolePrncpl.setActiveToDate(rolePrincipal.getActiveToDate());
724 	         		docRolePrncpl.setQualifiers(populateDocRoleQualifier(namespaceCode, rolePrincipal.getAttributeDetails(), definitions));
725 	         		docRolePrncpl.setEdit(true);
726 	        		docRoleMembers.add(docRolePrncpl);
727 	    		 }
728 	    	}
729 		}
730     	return docRoleMembers;
731     }
732 
733     // UI layout for rolequalifier is a little different from kimroleattribute set up.
734     // each principal may have member with same role multiple times with different qualifier, but the role
735     // only displayed once, and the qualifier displayed multiple times.
736     protected List<KimDocumentRoleQualifier> populateDocRoleQualifier(String namespaceCode, List <RoleMemberAttributeDataBo> qualifiers, AttributeDefinitionMap definitions) {
737 
738 		List <KimDocumentRoleQualifier> docRoleQualifiers = new ArrayList <KimDocumentRoleQualifier>();
739 		if(definitions!=null){
740 			for (String key : definitions.keySet()) {
741 				AttributeDefinition definition = definitions.get(key);
742 				String attrDefId=((KimAttributeDefinition)definition).getKimAttrDefnId();
743 				boolean qualifierFound = false;
744 				if(ObjectUtils.isNotNull(qualifiers)){
745 					for (RoleMemberAttributeDataBo qualifier : qualifiers) {
746 						if (attrDefId!=null && StringUtils.equals(attrDefId, qualifier.getKimAttributeId())) {
747 				    		KimDocumentRoleQualifier docRoleQualifier = new KimDocumentRoleQualifier();
748 				    		docRoleQualifier.setAttrDataId(qualifier.getId());
749 				    		docRoleQualifier.setAttrVal(qualifier.getAttributeValue());
750 				    		docRoleQualifier.setKimAttrDefnId(qualifier.getKimAttributeId());
751 				    		docRoleQualifier.setKimAttribute(qualifier.getKimAttribute());
752 				    		docRoleQualifier.setKimTypId(qualifier.getKimTypeId());
753 				    		docRoleQualifier.setRoleMemberId(qualifier.getAssignedToId());
754 				    		docRoleQualifier.setEdit(true);
755 				    		formatAttrValIfNecessary(docRoleQualifier);
756 				    		docRoleQualifiers.add(docRoleQualifier);
757 				    		qualifierFound = true;
758 				    		break;
759 						}
760 					}
761 				}
762 				if (!qualifierFound) {
763 		    		KimDocumentRoleQualifier docRoleQualifier = new KimDocumentRoleQualifier();
764 		    		docRoleQualifier.setAttrVal("");
765 		    		docRoleQualifier.setKimAttrDefnId(attrDefId);
766 		    		docRoleQualifier.refreshReferenceObject("kimAttribute");
767 		    		docRoleQualifiers.add(docRoleQualifier);
768 				}
769 			}
770 			// If all of the qualifiers are empty, return an empty list
771 			// This is to prevent dynamic qualifiers from appearing in the
772 			// person maintenance roles tab.  see KULRICE-3989 for more detail
773 			// and KULRICE-5071 for detail on switching from config value to 
774 			// application-scoped parameter
775 			if (!isBlankRoleQualifierVisible(namespaceCode)) {
776 				int qualCount = 0;
777 				for (KimDocumentRoleQualifier qual : docRoleQualifiers){
778 					if (StringUtils.isEmpty(qual.getAttrVal())){
779 						qualCount++;
780 					}
781 				}
782 				if (qualCount == docRoleQualifiers.size()){
783 					return new ArrayList <KimDocumentRoleQualifier>();
784 				}
785 			}
786 		}
787     	return docRoleQualifiers;
788     }
789 
790     protected List<PersonDocumentName> loadNames( IdentityManagementPersonDocument personDoc, String principalId, List <EntityName> names, boolean suppressDisplay ) {
791 		List<PersonDocumentName> docNames = new ArrayList<PersonDocumentName>();
792 		if(ObjectUtils.isNotNull(names)){
793 			for (EntityName name: names) {
794 				if(name.isActive()){
795 					PersonDocumentName docName = new PersonDocumentName();
796                     if (name.getNameType() != null) {
797 					    docName.setNameTypeCode(name.getNameType().getCode());
798                     }
799 
800 					//We do not need to check the privacy setting here - The UI should care of it
801 					docName.setFirstName(name.getFirstNameUnmasked());
802 					docName.setLastName(name.getLastNameUnmasked());
803 					docName.setMiddleName(name.getMiddleNameUnmasked());
804 					docName.setTitle(name.getTitleUnmasked());
805 					docName.setSuffix(name.getSuffixUnmasked());
806 
807 					docName.setActive(name.isActive());
808 					docName.setDflt(name.isDefaultValue());
809 					docName.setEdit(true);
810 					docName.setEntityNameId(name.getId());
811 					docNames.add(docName);
812 				}
813 			}
814 		}
815 		return docNames;
816 	}
817 
818 	public boolean canModifyEntity( String currentUserPrincipalId, String toModifyPrincipalId ){
819 		return (StringUtils.isNotBlank(currentUserPrincipalId) && StringUtils.isNotBlank(toModifyPrincipalId) &&
820 				currentUserPrincipalId.equals(toModifyPrincipalId)) ||
821 				getPermissionService().isAuthorized(
822 						currentUserPrincipalId,
823 						KimConstants.NAMESPACE_CODE,
824 						KimConstants.PermissionNames.MODIFY_ENTITY,
825 						null,
826 						Collections.singletonMap(KimConstants.AttributeConstants.PRINCIPAL_ID, currentUserPrincipalId));
827 	}
828 
829 	public boolean canOverrideEntityPrivacyPreferences( String currentUserPrincipalId, String toModifyPrincipalId ){
830 		return (StringUtils.isNotBlank(currentUserPrincipalId) && StringUtils.isNotBlank(toModifyPrincipalId) &&
831 				currentUserPrincipalId.equals(toModifyPrincipalId)) ||
832 				getPermissionService().isAuthorized(
833 						currentUserPrincipalId,
834 						KimConstants.NAMESPACE_CODE,
835 						KimConstants.PermissionNames.OVERRIDE_ENTITY_PRIVACY_PREFERENCES,
836 						null,
837 						Collections.singletonMap(KimConstants.AttributeConstants.PRINCIPAL_ID, currentUserPrincipalId) );
838 	}
839 
840 	protected boolean canAssignToRole(IdentityManagementRoleDocument document, String initiatorPrincipalId){
841         boolean rulePassed = true;
842         Map<String,String> additionalPermissionDetails = new HashMap<String,String>();
843         additionalPermissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, document.getRoleNamespace());
844         additionalPermissionDetails.put(KimConstants.AttributeConstants.ROLE_NAME, document.getRoleName());
845 		if(!getDocumentHelperService().getDocumentAuthorizer(document).isAuthorizedByTemplate(
846 				document, KimConstants.NAMESPACE_CODE, KimConstants.PermissionTemplateNames.ASSIGN_ROLE,
847 				initiatorPrincipalId, additionalPermissionDetails, null)){
848             rulePassed = false;
849 		}
850 		return rulePassed;
851 	}
852 
853 	protected List<PersonDocumentAffiliation> loadAffiliations(List <EntityAffiliation> affiliations, List<EntityEmployment> empInfos) {
854 		List<PersonDocumentAffiliation> docAffiliations = new ArrayList<PersonDocumentAffiliation>();
855 		if(ObjectUtils.isNotNull(affiliations)){
856 			for (EntityAffiliation affiliation: affiliations) {
857 				if(affiliation.isActive()){
858 					PersonDocumentAffiliation docAffiliation = new PersonDocumentAffiliation();
859 					docAffiliation.setAffiliationTypeCode(affiliation.getAffiliationType().getCode());
860 					docAffiliation.setCampusCode(affiliation.getCampusCode());
861 					docAffiliation.setActive(affiliation.isActive());
862 					docAffiliation.setDflt(affiliation.isDefaultValue());
863 					docAffiliation.setEntityAffiliationId(affiliation.getId());
864 					docAffiliation.refreshReferenceObject("affiliationType");
865 					// EntityAffiliationImpl does not define empinfos as collection
866 					docAffiliations.add(docAffiliation);
867 					docAffiliation.setEdit(true);
868 					// employment informations
869 					List<PersonDocumentEmploymentInfo> docEmploymentInformations = new ArrayList<PersonDocumentEmploymentInfo>();
870 					if(ObjectUtils.isNotNull(empInfos)){
871 						for (EntityEmployment empInfo: empInfos) {
872 							if (empInfo.isActive()
873                                     && StringUtils.equals(docAffiliation.getEntityAffiliationId(),
874                                                           (empInfo.getEntityAffiliation() != null ? empInfo.getEntityAffiliation().getId() : null))) {
875 								PersonDocumentEmploymentInfo docEmpInfo = new PersonDocumentEmploymentInfo();
876 								docEmpInfo.setEntityEmploymentId(empInfo.getEmployeeId());
877 								docEmpInfo.setEmployeeId(empInfo.getEmployeeId());
878 								docEmpInfo.setEmploymentRecordId(empInfo.getEmploymentRecordId());
879 								docEmpInfo.setBaseSalaryAmount(empInfo.getBaseSalaryAmount());
880 								docEmpInfo.setPrimaryDepartmentCode(empInfo.getPrimaryDepartmentCode());
881 								docEmpInfo.setEmploymentStatusCode(empInfo.getEmployeeStatus() != null ? empInfo.getEmployeeStatus().getCode() : null);
882 								docEmpInfo.setEmploymentTypeCode(empInfo.getEmployeeType() != null ? empInfo.getEmployeeType().getCode() : null);
883 								docEmpInfo.setActive(empInfo.isActive());
884 								docEmpInfo.setPrimary(empInfo.isPrimary());
885 								docEmpInfo.setEntityAffiliationId(empInfo.getEntityAffiliation() != null ? empInfo.getEntityAffiliation().getId() : null);
886 								// there is no version number on KimEntityEmploymentInformationInfo
887 								//docEmpInfo.setVersionNumber(empInfo.getVersionNumber());
888 								docEmpInfo.setEdit(true);
889 								docEmpInfo.refreshReferenceObject("employmentType");
890 								docEmploymentInformations.add(docEmpInfo);
891 							}
892 						}
893 					}
894 					docAffiliation.setEmpInfos(docEmploymentInformations);
895 				}
896 			}
897 		}
898 		return docAffiliations;
899 
900 	}
901 
902     protected boolean setupPrincipal(IdentityManagementPersonDocument identityManagementPersonDocument, EntityBo kimEntity, List<PrincipalBo> origPrincipals) {
903     	boolean inactivatingPrincipal = false;
904 		List<PrincipalBo> principals = new ArrayList<PrincipalBo>();
905 		Principal.Builder principal = Principal.Builder.create(identityManagementPersonDocument.getPrincipalName());
906 		principal.setPrincipalId(identityManagementPersonDocument.getPrincipalId());
907 		principal.setPassword(identityManagementPersonDocument.getPassword());
908 		principal.setActive(identityManagementPersonDocument.isActive());
909 		principal.setEntityId(identityManagementPersonDocument.getEntityId());
910 		if(ObjectUtils.isNotNull(origPrincipals)){
911 			for (PrincipalBo prncpl : origPrincipals) {
912 				if (prncpl.getPrincipalId()!=null && StringUtils.equals(prncpl.getPrincipalId(), principal.getPrincipalId())) {
913 					principal.setVersionNumber(prncpl.getVersionNumber());
914                     principal.setObjectId(prncpl.getObjectId());
915 					// check if inactivating the principal
916 					if ( prncpl.isActive() && !principal.isActive() ) {
917 						inactivatingPrincipal = true;
918 					}
919 				}
920 			}
921 		}
922 		principals.add(PrincipalBo.from(principal.build()));
923 
924 		kimEntity.setPrincipals(principals);
925 		return inactivatingPrincipal;
926 	}
927 
928     protected void setupPrivacy(IdentityManagementPersonDocument identityManagementPersonDocument, EntityBo kimEntity, EntityPrivacyPreferencesBo origPrivacy) {
929 		EntityPrivacyPreferencesBo privacyPreferences = new EntityPrivacyPreferencesBo();
930 		privacyPreferences.setEntityId(identityManagementPersonDocument.getEntityId());
931 		privacyPreferences.setSuppressAddress(identityManagementPersonDocument.getPrivacy().isSuppressAddress());
932 		privacyPreferences.setSuppressEmail(identityManagementPersonDocument.getPrivacy().isSuppressEmail());
933 		privacyPreferences.setSuppressName(identityManagementPersonDocument.getPrivacy().isSuppressName());
934 		privacyPreferences.setSuppressPhone(identityManagementPersonDocument.getPrivacy().isSuppressPhone());
935 		privacyPreferences.setSuppressPersonal(identityManagementPersonDocument.getPrivacy().isSuppressPersonal());
936 		if (ObjectUtils.isNotNull(origPrivacy)) {
937 			privacyPreferences.setVersionNumber(origPrivacy.getVersionNumber());
938             privacyPreferences.setObjectId(origPrivacy.getObjectId());
939 		}
940 		kimEntity.setPrivacyPreferences(privacyPreferences);
941 	}
942     protected PersonDocumentPrivacy loadPrivacyReferences(EntityPrivacyPreferences privacyPreferences) {
943 		PersonDocumentPrivacy docPrivacy = new PersonDocumentPrivacy();
944 		docPrivacy.setSuppressAddress(privacyPreferences.isSuppressAddress());
945 		docPrivacy.setSuppressEmail(privacyPreferences.isSuppressEmail());
946 		docPrivacy.setSuppressName(privacyPreferences.isSuppressName());
947 		docPrivacy.setSuppressPhone(privacyPreferences.isSuppressPhone());
948 		docPrivacy.setSuppressPersonal(privacyPreferences.isSuppressPersonal());
949 		docPrivacy.setEdit(true);
950 		return docPrivacy;
951 	}
952 
953     protected void setupName(IdentityManagementPersonDocument identityManagementPersonDocument, EntityBo kimEntity, List<EntityNameBo> origNames) {
954     	if ( !identityManagementPersonDocument.getPrivacy().isSuppressName() ||
955     			canOverrideEntityPrivacyPreferences( getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId() ) ) {
956 	    	List<EntityNameBo> entityNames = new ArrayList<EntityNameBo>();
957 			if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getNames())){
958 				for (PersonDocumentName name : identityManagementPersonDocument.getNames()) {
959 				    EntityNameBo entityName = new EntityNameBo();
960 					entityName.setNameTypeCode(name.getNameTypeCode());
961 					entityName.setFirstName(name.getFirstName());
962 					entityName.setLastName(name.getLastName());
963 					entityName.setMiddleName(name.getMiddleName());
964 					entityName.setTitle(name.getTitle());
965 					entityName.setSuffix(name.getSuffix());
966 					entityName.setActive(name.isActive());
967 					entityName.setDefaultValue(name.isDflt());
968 					entityName.setId(name.getEntityNameId());
969 					entityName.setEntityId(identityManagementPersonDocument.getEntityId());
970 					if(ObjectUtils.isNotNull(origNames)){
971 						for (EntityNameBo origName : origNames) {
972 							if (origName.getId()!=null && StringUtils.equals(origName.getId(), entityName.getId())) {
973 								entityName.setVersionNumber(origName.getVersionNumber());
974 							}
975 
976 						}
977 					}
978 					entityNames.add(entityName);
979 				}
980 			}
981 			kimEntity.setNames(entityNames);
982     	}
983 	}
984 
985     protected void setupAffiliation(IdentityManagementPersonDocument identityManagementPersonDocument, EntityBo kimEntity,List<EntityAffiliationBo> origAffiliations, List<EntityEmploymentBo> origEmpInfos) {
986 		List<EntityAffiliationBo> entityAffiliations = new ArrayList<EntityAffiliationBo>();
987 		// employment informations
988 		List<EntityEmploymentBo> entityEmploymentInformations = new ArrayList<EntityEmploymentBo>();
989 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getAffiliations())){
990 			for (PersonDocumentAffiliation affiliation : identityManagementPersonDocument.getAffiliations()) {
991 				EntityAffiliationBo entityAffiliation = new EntityAffiliationBo();
992 				entityAffiliation.setAffiliationTypeCode(affiliation.getAffiliationTypeCode());
993 				entityAffiliation.setCampusCode(affiliation.getCampusCode());
994 				entityAffiliation.setActive(affiliation.isActive());
995 				entityAffiliation.setDefaultValue(affiliation.isDflt());
996 				entityAffiliation.setEntityId(identityManagementPersonDocument.getEntityId());
997 				entityAffiliation.setId(affiliation.getEntityAffiliationId());
998 				if(ObjectUtils.isNotNull(origAffiliations)){
999 				// EntityAffiliationImpl does not define empinfos as collection
1000 					for (EntityAffiliationBo origAffiliation : origAffiliations) {
1001 						if(isSameAffiliation(origAffiliation, entityAffiliation)){
1002 							entityAffiliation.setId(origAffiliation.getId());
1003 						}
1004 						if (origAffiliation.getId()!=null && StringUtils.equals(origAffiliation.getId(), entityAffiliation.getId())) {
1005 							entityAffiliation.setVersionNumber(origAffiliation.getVersionNumber());
1006 						}
1007 					}
1008 				}
1009 				entityAffiliations.add(entityAffiliation);
1010 				int employeeRecordCounter = origEmpInfos==null?0:origEmpInfos.size();
1011 				if(CollectionUtils.isNotEmpty(affiliation.getEmpInfos())){
1012 					for (PersonDocumentEmploymentInfo empInfo : affiliation.getEmpInfos()) {
1013 						EntityEmploymentBo entityEmpInfo = new EntityEmploymentBo();
1014 						entityEmpInfo.setId(empInfo.getEntityEmploymentId());
1015 						entityEmpInfo.setEmployeeId(empInfo.getEmployeeId());
1016 						entityEmpInfo.setEmploymentRecordId(empInfo.getEmploymentRecordId());
1017 						entityEmpInfo.setBaseSalaryAmount(empInfo.getBaseSalaryAmount());
1018 						entityEmpInfo.setPrimaryDepartmentCode(empInfo.getPrimaryDepartmentCode());
1019 						entityEmpInfo.setEmployeeStatusCode(empInfo.getEmploymentStatusCode());
1020 						entityEmpInfo.setEmployeeTypeCode(empInfo.getEmploymentTypeCode());
1021 						entityEmpInfo.setActive(empInfo.isActive());
1022 						entityEmpInfo.setPrimary(empInfo.isPrimary());
1023 						entityEmpInfo.setEntityId(identityManagementPersonDocument.getEntityId());
1024 						entityEmpInfo.setEntityAffiliationId(empInfo.getEntityAffiliationId());
1025 						if(ObjectUtils.isNotNull(origEmpInfos)){
1026 							for (EntityEmploymentBo origEmpInfo : origEmpInfos) {
1027 								if(isSameEmpInfo(origEmpInfo, entityEmpInfo)){
1028 									entityEmpInfo.setId(entityEmpInfo.getEntityId());
1029 								}
1030 
1031 								if (origEmpInfo.getId()!=null && StringUtils.equals(origEmpInfo.getId(), entityEmpInfo.getId())) {
1032 									entityEmpInfo.setVersionNumber(origEmpInfo.getVersionNumber());
1033 									entityEmpInfo.setEmploymentRecordId(empInfo.getEmploymentRecordId());
1034 								}
1035 							}
1036 						}
1037 						if(StringUtils.isEmpty(entityEmpInfo.getEmploymentRecordId())){
1038 							employeeRecordCounter++;
1039 							entityEmpInfo.setEmploymentRecordId(employeeRecordCounter+"");
1040 						}
1041 						entityEmploymentInformations.add(entityEmpInfo);
1042 					}
1043 				}
1044 			}
1045 		}
1046 		kimEntity.setEmploymentInformation(entityEmploymentInformations);
1047 		kimEntity.setAffiliations(entityAffiliations);
1048 	}
1049 
1050     /*
1051      * Added to address KULRICE-5071 : "Move the 'show blank qualifier' kim toggle from a Config param to a System param"
1052      * 
1053      * This method first checks for a namespace specific parameter with a detailTypeCode of "All" and parameterName of "KIM_SHOW_BLANK_QUALIFIERS". 
1054      * If no parameter is found, it checks for the config property "kim.show.blank.qualifiers", and defaults to true if no config property exists. 
1055      *
1056      */
1057     private boolean isBlankRoleQualifierVisible(String namespaceCode) {
1058     	boolean showBlankQualifiers = true;
1059 		
1060 		Parameter param = getParameterService().getParameter(namespaceCode, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, KimConstants.ParameterKey.SHOW_BLANK_QUALIFIERS);
1061 	    if (param != null) {
1062 	    	showBlankQualifiers = "Y".equals(param.getValue());
1063 	    } else {
1064 	    	String configProperty = ConfigContext.getCurrentContextConfig().getProperty(SHOW_BLANK_QUALIFIERS);
1065 	    	if (configProperty != null) {
1066 	    		showBlankQualifiers = Boolean.valueOf(configProperty);
1067             }
1068 	    }
1069 	    
1070 	    return showBlankQualifiers;
1071     }
1072     
1073    private boolean isSameAffiliation(EntityAffiliationBo origAffiliation, EntityAffiliationBo entityAffiliation){
1074     	//entityId
1075     	//affiliationTypeCode
1076     	//campusCode
1077     	return (origAffiliation!=null && entityAffiliation!=null) &&
1078     	(StringUtils.isNotEmpty(origAffiliation.getCampusCode()) && StringUtils.equals(origAffiliation.getCampusCode(), entityAffiliation.getCampusCode()))
1079     	&&
1080     	(StringUtils.isNotEmpty(origAffiliation.getAffiliationTypeCode()) && StringUtils.equals(origAffiliation.getAffiliationTypeCode(), entityAffiliation.getAffiliationTypeCode()))
1081  		&&
1082  		(StringUtils.isNotEmpty(origAffiliation.getEntityId()) && StringUtils.equals(origAffiliation.getEntityId(), entityAffiliation.getEntityId()));
1083     }
1084 
1085     private boolean isSameEmpInfo(EntityEmploymentBo origEmpInfo, EntityEmploymentBo entityEmpInfo){
1086     	//emp_info:
1087     		//employmentRecordId
1088     		//entityId
1089     		//These should be unique - add a business rule
1090     	return (origEmpInfo!=null && entityEmpInfo!=null)
1091     			&& (StringUtils.isNotEmpty(origEmpInfo.getEmploymentRecordId())
1092     					&& StringUtils.equals(origEmpInfo.getEmploymentRecordId(), entityEmpInfo.getEmploymentRecordId() )
1093     				)
1094     			&& StringUtils.equals( origEmpInfo.getEntityId(),entityEmpInfo.getEntityId());
1095     }
1096 
1097     protected void setupPhone(IdentityManagementPersonDocument identityManagementPersonDocument, EntityTypeDataBo entityType, List<EntityPhoneBo> origPhones) {
1098     	if ( !identityManagementPersonDocument.getPrivacy().isSuppressPhone() || canOverrideEntityPrivacyPreferences(getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId()) ) {
1099 			List<EntityPhoneBo> entityPhones = new ArrayList<EntityPhoneBo>();
1100 			if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getPhones())){
1101 				for (PersonDocumentPhone phone : identityManagementPersonDocument.getPhones()) {
1102 					EntityPhoneBo entityPhone = new EntityPhoneBo();
1103 					entityPhone.setPhoneTypeCode(phone.getPhoneTypeCode());
1104 					entityPhone.setEntityId(identityManagementPersonDocument.getEntityId());
1105 					entityPhone.setId(phone.getEntityPhoneId());
1106 					entityPhone.setEntityTypeCode(entityType.getEntityTypeCode());
1107 					entityPhone.setPhoneNumber(phone.getPhoneNumber());
1108 					entityPhone.setCountryCode(phone.getCountryCode());
1109 					entityPhone.setExtension(phone.getExtension());
1110 					entityPhone.setExtensionNumber(phone.getExtensionNumber());
1111 					entityPhone.setActive(phone.isActive());
1112 					entityPhone.setDefaultValue(phone.isDflt());
1113 					if(ObjectUtils.isNotNull(origPhones)){
1114 						for (EntityPhoneContract origPhone : origPhones) {
1115 							if (origPhone.getId()!=null && StringUtils.equals(origPhone.getId(), entityPhone.getId())) {
1116 								entityPhone.setVersionNumber(origPhone.getVersionNumber());
1117 							}
1118 						}
1119 					}
1120 					entityPhone.setId(phone.getEntityPhoneId());
1121 					entityPhones.add(entityPhone);
1122 				}
1123 			}
1124 			entityType.setPhoneNumbers(entityPhones);
1125     	}
1126 	}
1127 
1128     protected List<PersonDocumentPhone> loadPhones(IdentityManagementPersonDocument identityManagementPersonDocument, String principalId, List<EntityPhone> entityPhones, boolean suppressDisplay ) {
1129 		List<PersonDocumentPhone> docPhones = new ArrayList<PersonDocumentPhone>();
1130 		if(ObjectUtils.isNotNull(entityPhones)){
1131 			for (EntityPhone phone: entityPhones) {
1132 				if(phone.isActive()){
1133 					PersonDocumentPhone docPhone = new PersonDocumentPhone();
1134                     if (phone.getPhoneType() != null) {
1135 					    docPhone.setPhoneTypeCode(phone.getPhoneType().getCode());
1136                     }
1137 					//docPhone.setPhoneType(((KimEntityPhoneImpl)phone).getPhoneType());
1138 					docPhone.setEntityTypeCode(phone.getEntityTypeCode());
1139 					//We do not need to check the privacy setting here - The UI should care of it
1140 					docPhone.setPhoneNumber(phone.getPhoneNumberUnmasked());
1141 					docPhone.setCountryCode(phone.getCountryCodeUnmasked());
1142 					docPhone.setExtensionNumber(phone.getExtensionNumberUnmasked());
1143 
1144 					docPhone.setActive(phone.isActive());
1145 					docPhone.setDflt(phone.isDefaultValue());
1146 					docPhone.setEntityPhoneId(phone.getId());
1147 					docPhone.setEdit(true);
1148 					docPhones.add(docPhone);
1149 				}
1150 			}
1151 		}
1152 		return docPhones;
1153 
1154 	}
1155 
1156     protected void setupEmail(
1157 			IdentityManagementPersonDocument identityManagementPersonDocument,
1158 			EntityTypeDataBo entityType, List<EntityEmailBo> origEmails) {
1159     	if ( !identityManagementPersonDocument.getPrivacy().isSuppressEmail() || canOverrideEntityPrivacyPreferences(getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId()) ) {
1160 			List<EntityEmailBo> entityEmails = new ArrayList<EntityEmailBo>();
1161 			if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getEmails())){
1162 				for (PersonDocumentEmail email : identityManagementPersonDocument.getEmails()) {
1163 					EntityEmailBo entityEmail = new EntityEmailBo();
1164 					entityEmail.setEntityId(identityManagementPersonDocument.getEntityId());
1165 					entityEmail.setEntityTypeCode(entityType.getEntityTypeCode());
1166 					entityEmail.setEmailTypeCode(email.getEmailTypeCode());
1167 					entityEmail.setEmailAddress(email.getEmailAddress());
1168 					entityEmail.setActive(email.isActive());
1169 					entityEmail.setDefaultValue(email.isDflt());
1170 					entityEmail.setId(email.getEntityEmailId());
1171 					if(ObjectUtils.isNotNull(origEmails)){
1172 						for (EntityEmailContract origEmail : origEmails) {
1173 							if (origEmail.getId()!=null && StringUtils.equals(origEmail.getId(), entityEmail.getId())) {
1174 								entityEmail.setVersionNumber(origEmail.getVersionNumber());
1175 							}
1176 						}
1177 					}
1178 					entityEmails.add(entityEmail);
1179 				}
1180 			}
1181 			entityType.setEmailAddresses(entityEmails);
1182     	}
1183 	}
1184     protected List<PersonDocumentEmail> loadEmails(IdentityManagementPersonDocument identityManagementPersonDocument, String principalId, List<EntityEmail> entityEmails, boolean suppressDisplay ) {
1185 		List<PersonDocumentEmail> emails = new ArrayList<PersonDocumentEmail>();
1186 		if(ObjectUtils.isNotNull(entityEmails)){
1187 			for (EntityEmail email: entityEmails) {
1188 				if(email.isActive()){
1189 					PersonDocumentEmail docEmail = new PersonDocumentEmail();
1190 					//docEmail.setEntityId(email.getEntityId());
1191 					docEmail.setEntityTypeCode(email.getEntityTypeCode());
1192                     if (email.getEmailType() != null) {
1193 					    docEmail.setEmailTypeCode(email.getEmailType().getCode());
1194                     }
1195 					// EmailType not on info object.
1196 					//docEmail.setEmailType(((KimEntityEmailImpl)email).getEmailType());
1197 					//We do not need to check the privacy setting here - The UI should care of it
1198 					docEmail.setEmailAddress(email.getEmailAddressUnmasked());
1199 
1200 					docEmail.setActive(email.isActive());
1201 					docEmail.setDflt(email.isDefaultValue());
1202 					docEmail.setEntityEmailId(email.getId());
1203 					docEmail.setEdit(true);
1204 					emails.add(docEmail);
1205 				}
1206 			}
1207 		}
1208 		return emails;
1209 	}
1210 
1211     protected void setupAddress(
1212 			IdentityManagementPersonDocument identityManagementPersonDocument,
1213 			EntityTypeDataBo entityType, List<EntityAddressBo> origAddresses) {
1214     	if ( !identityManagementPersonDocument.getPrivacy().isSuppressAddress() || canOverrideEntityPrivacyPreferences(getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId()) ) {
1215 			List<EntityAddressBo> entityAddresses = new ArrayList<EntityAddressBo>();
1216 			if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getAddrs())){
1217 				for (PersonDocumentAddress address : identityManagementPersonDocument.getAddrs()) {
1218 					EntityAddressBo entityAddress = new EntityAddressBo();
1219 					entityAddress.setEntityId(identityManagementPersonDocument.getEntityId());
1220 					entityAddress.setEntityTypeCode(entityType.getEntityTypeCode());
1221 					entityAddress.setAddressTypeCode(address.getAddressTypeCode());
1222 					entityAddress.setLine1(address.getLine1());
1223 					entityAddress.setLine2(address.getLine2());
1224 					entityAddress.setLine3(address.getLine3());
1225 					entityAddress.setStateCode(address.getStateCode());
1226 					entityAddress.setPostalCode(address.getPostalCode());
1227 					entityAddress.setCountryCode(address.getCountryCode());
1228 					entityAddress.setCityName(address.getCityName());
1229 					entityAddress.setActive(address.isActive());
1230 					entityAddress.setDefaultValue(address.isDflt());
1231 					entityAddress.setId(address.getEntityAddressId());
1232 					if(ObjectUtils.isNotNull(origAddresses)){
1233 						for (EntityAddressContract origAddress : origAddresses) {
1234 							if (origAddress.getId()!=null && StringUtils.equals(origAddress.getId(), entityAddress.getId())) {
1235 								entityAddress.setVersionNumber(origAddress.getVersionNumber());
1236 							}
1237 						}
1238 					}
1239 					entityAddresses.add(entityAddress);
1240 				}
1241 			}
1242 			entityType.setAddresses(entityAddresses);
1243     	}
1244 	}
1245 
1246     protected List<PersonDocumentAddress> loadAddresses(IdentityManagementPersonDocument identityManagementPersonDocument, String principalId, List<EntityAddress> entityAddresses, boolean suppressDisplay ) {
1247 		List<PersonDocumentAddress> docAddresses = new ArrayList<PersonDocumentAddress>();
1248 		if(ObjectUtils.isNotNull(entityAddresses)){
1249 			for (EntityAddress address: entityAddresses) {
1250 				if(address.isActive()){
1251 					PersonDocumentAddress docAddress = new PersonDocumentAddress();
1252 					docAddress.setEntityTypeCode(address.getEntityTypeCode());
1253 					docAddress.setAddressTypeCode(address.getAddressType().getCode());
1254 
1255 					//We do not need to check the privacy setting here - The UI should care of it
1256 					docAddress.setLine1(address.getLine1Unmasked());
1257 					docAddress.setLine2(address.getLine2Unmasked());
1258 					docAddress.setLine3(address.getLine3Unmasked());
1259 					docAddress.setStateCode(address.getStateCodeUnmasked());
1260 					docAddress.setPostalCode(address.getPostalCodeUnmasked());
1261 					docAddress.setCountryCode(address.getCountryCodeUnmasked());
1262 					docAddress.setCityName(address.getCityNameUnmasked());
1263 
1264 					docAddress.setActive(address.isActive());
1265 					docAddress.setDflt(address.isDefaultValue());
1266 					docAddress.setEntityAddressId(address.getId());
1267 					docAddress.setEdit(true);
1268 					docAddresses.add(docAddress);
1269 				}
1270 			}
1271 		}
1272 		return docAddresses;
1273 	}
1274 
1275 
1276     protected List <GroupMemberBo> populateGroupMembers(IdentityManagementPersonDocument identityManagementPersonDocument) {
1277 		List <GroupMemberBo>  groupPrincipals = new ArrayList<GroupMemberBo>();
1278 //		List<? extends Group> origGroups = getGroupService().getGroupsForPrincipal(identityManagementPersonDocument.getPrincipalId());
1279 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getGroups())){
1280 			for (PersonDocumentGroup group : identityManagementPersonDocument.getGroups()) {
1281 				GroupMember.Builder groupPrincipalImpl = GroupMember.Builder.create(group.getGroupId(), identityManagementPersonDocument.getPrincipalId(), KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE);
1282 				if (group.getActiveFromDate() != null) {
1283 					groupPrincipalImpl.setActiveFromDate(new java.sql.Timestamp(group.getActiveFromDate().getTime()));
1284 				}
1285 				if (group.getActiveToDate() != null) {
1286 					groupPrincipalImpl.setActiveToDate(new java.sql.Timestamp(group.getActiveToDate().getTime()));
1287 				}
1288 				groupPrincipalImpl.setId(group.getGroupMemberId());
1289 
1290 
1291                 //groupPrincipalImpl.setVersionNumber(group.getVersionNumber());
1292 				// get the ORM-layer optimisic locking value
1293 				// TODO: this should be replaced with the retrieval and storage of that value
1294 				// in the document tables and not re-retrieved here
1295 				Collection<GroupMember> currGroupMembers = getGroupService().getMembers(Collections.singletonList(group.getGroupId()));
1296 				if(ObjectUtils.isNotNull(currGroupMembers)){
1297 					for (GroupMember origGroupMember: currGroupMembers) {
1298                         if (origGroupMember.isActive(new Timestamp(System.currentTimeMillis()))
1299                             && origGroupMember.getTypeCode().equals(KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE)) {
1300                             if(origGroupMember.getId()!=null && StringUtils.equals(origGroupMember.getId(), group.getGroupMemberId())){
1301                                 groupPrincipalImpl.setObjectId(origGroupMember.getObjectId());
1302                                 groupPrincipalImpl.setVersionNumber(origGroupMember.getVersionNumber());
1303                             }
1304                         }
1305 					}
1306 				}
1307 
1308 				groupPrincipals.add(GroupMemberBo.from(groupPrincipalImpl.build()));
1309 
1310 			}
1311 		}
1312 		return groupPrincipals;
1313 	}
1314 
1315     protected List<RoleMemberBo> populateRoleMembers(IdentityManagementPersonDocument identityManagementPersonDocument) {
1316 		List<RoleBo> origRoles = getRolesForPrincipal(identityManagementPersonDocument.getPrincipalId());
1317 
1318 		List <RoleMemberBo> roleMembers = new ArrayList<RoleMemberBo>();
1319 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getRoles())){
1320 			for (PersonDocumentRole role : identityManagementPersonDocument.getRoles()) {
1321 				//if(role.isEditable()){
1322 					List<RoleMemberBo> origRoleMembers = new ArrayList<RoleMemberBo>();
1323 					if(ObjectUtils.isNotNull(origRoles)){
1324 						for (RoleBo origRole : origRoles) {
1325 							if (origRole.getId()!=null && StringUtils.equals(origRole.getId(), role.getRoleId())) {
1326 								origRoleMembers = origRole.getMembers();
1327 								break;
1328 							}
1329 						}
1330 					}
1331 					if (role.getRolePrncpls().isEmpty()) {
1332 						if (!role.getDefinitions().isEmpty()) {
1333 							RoleMemberBo roleMemberImpl = new RoleMemberBo();
1334 							roleMemberImpl.setRoleId(role.getRoleId());
1335 							roleMemberImpl.setMemberId(identityManagementPersonDocument.getPrincipalId());
1336 							roleMemberImpl.setMemberTypeCode(Role.PRINCIPAL_MEMBER_TYPE);
1337 							roleMembers.add(roleMemberImpl);
1338 						}
1339 					} else {
1340 						for (KimDocumentRoleMember roleMember : role.getRolePrncpls()) {
1341 							RoleMemberBo roleMemberImpl = new RoleMemberBo();
1342 							roleMemberImpl.setRoleId(role.getRoleId());
1343 							// TODO : principalId is not ready here yet ?
1344 							roleMemberImpl.setMemberId(identityManagementPersonDocument.getPrincipalId());
1345 							roleMemberImpl.setMemberTypeCode(Role.PRINCIPAL_MEMBER_TYPE);
1346 							roleMemberImpl.setRoleMemberId(roleMember.getRoleMemberId());
1347 							if (roleMember.getActiveFromDate() != null) {
1348 								roleMemberImpl.setActiveFromDate(new java.sql.Timestamp(roleMember.getActiveFromDate().getTime()));
1349 							}
1350 							if (roleMember.getActiveToDate() != null) {
1351 								roleMemberImpl.setActiveToDate(new java.sql.Timestamp(roleMember.getActiveToDate().getTime()));
1352 							}
1353 							List<RoleMemberAttributeDataBo> origAttributes = new ArrayList<RoleMemberAttributeDataBo>();
1354 							if(ObjectUtils.isNotNull(origRoleMembers)){
1355 								for (RoleMemberBo origMember : origRoleMembers) {
1356 									if (origMember.getRoleMemberId()!=null && StringUtils.equals(origMember.getRoleMemberId(), roleMember.getRoleMemberId())) {
1357 										origAttributes = origMember.getAttributeDetails();
1358 										roleMemberImpl.setVersionNumber(origMember.getVersionNumber());
1359 									}
1360 								}
1361 							}
1362 							List<RoleMemberAttributeDataBo> attributes = new ArrayList<RoleMemberAttributeDataBo>();
1363 							if(CollectionUtils.isNotEmpty(roleMember.getQualifiers())){
1364 								for (KimDocumentRoleQualifier qualifier : roleMember.getQualifiers()) {
1365 									//if (StringUtils.isNotBlank(qualifier.getAttrVal())) {
1366 										RoleMemberAttributeDataBo attribute = new RoleMemberAttributeDataBo();
1367 										attribute.setId(qualifier.getAttrDataId());
1368 										attribute.setAttributeValue(qualifier.getAttrVal());
1369 										attribute.setKimAttributeId(qualifier.getKimAttrDefnId());
1370 										attribute.setAssignedToId(qualifier.getRoleMemberId());
1371 										attribute.setKimTypeId(qualifier.getKimTypId());
1372 
1373 										updateAttrValIfNecessary(attribute);
1374 
1375 										if(ObjectUtils.isNotNull(origAttributes)){
1376 											for (RoleMemberAttributeDataBo origAttribute : origAttributes) {
1377 												if (origAttribute.getId()!=null && StringUtils.equals(origAttribute.getId(), qualifier.getAttrDataId())) {
1378 													attribute.setVersionNumber(origAttribute.getVersionNumber());
1379 												}
1380 											}
1381 										}
1382 										if (attribute.getVersionNumber() != null || StringUtils.isNotBlank(qualifier.getAttrVal())) {
1383 											attributes.add(attribute);
1384 										}
1385 									//}
1386 								}
1387 							}
1388 							roleMemberImpl.setAttributeDetails(attributes);
1389 							roleMembers.add(roleMemberImpl);
1390 						}
1391 					}
1392 				//}
1393 			}
1394 		}
1395 		return roleMembers;
1396 	}
1397 
1398 	protected List<DelegateBo> populateDelegations(IdentityManagementPersonDocument identityManagementPersonDocument){
1399 		List<DelegateBo> origDelegations = getPersonDelegations(identityManagementPersonDocument.getPrincipalId());
1400 		List<DelegateBo> kimDelegations = new ArrayList<DelegateBo>();
1401 		DelegateBo newKimDelegation;
1402 		DelegateBo origDelegationImplTemp = null;
1403 		List<DelegateMemberBo> origMembers;
1404 		boolean activatingInactive = false;
1405 		String newDelegationIdAssigned = "";
1406 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getDelegations())){
1407 			for(RoleDocumentDelegation roleDocumentDelegation: identityManagementPersonDocument.getDelegations()){
1408 				newKimDelegation = new DelegateBo();
1409 				KimCommonUtilsInternal.copyProperties(newKimDelegation, roleDocumentDelegation);
1410 				newKimDelegation.setRoleId(roleDocumentDelegation.getRoleId());
1411 				if(ObjectUtils.isNotNull(origDelegations)){
1412 					for(DelegateBo origDelegationImpl: origDelegations){
1413 						if((origDelegationImpl.getRoleId()!=null && StringUtils.equals(origDelegationImpl.getRoleId(), newKimDelegation.getRoleId())) &&
1414 								(origDelegationImpl.getDelegationId()!=null && StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId()))){
1415 							//TODO: verify if you want to add  && newRoleMember.isActive() condition to if...
1416 							newDelegationIdAssigned = newKimDelegation.getDelegationId();
1417 							newKimDelegation.setDelegationId(origDelegationImpl.getDelegationId());
1418 							activatingInactive = true;
1419 						}
1420 						if(origDelegationImpl.getDelegationId()!=null && StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId())){
1421 							newKimDelegation.setVersionNumber(origDelegationImpl.getVersionNumber());
1422 							origDelegationImplTemp = origDelegationImpl;
1423 						}
1424 					}
1425 				}
1426 				origMembers = (origDelegationImplTemp==null || origDelegationImplTemp.getMembers()==null)?
1427 									new ArrayList<DelegateMemberBo>():origDelegationImplTemp.getMembers();
1428 				newKimDelegation.setMembers(getDelegationMembers(roleDocumentDelegation.getMembers(), origMembers, activatingInactive, newDelegationIdAssigned));
1429 				kimDelegations.add(newKimDelegation);
1430 				activatingInactive = false;
1431 			}
1432 		}
1433 		return kimDelegations;
1434 	}
1435 
1436     protected List <RoleMemberAttributeDataBo> getBlankRoleMemberAttrs(List <RoleMemberBo> rolePrncpls) {
1437 
1438 		List <RoleMemberAttributeDataBo>  blankRoleMemberAttrs = new ArrayList<RoleMemberAttributeDataBo>();
1439 		if(ObjectUtils.isNotNull(rolePrncpls)){
1440 			for (RoleMemberBo roleMbr : rolePrncpls) {
1441 				List <RoleMemberAttributeDataBo>  roleMemberAttrs = new ArrayList<RoleMemberAttributeDataBo>();
1442 				if (CollectionUtils.isNotEmpty(roleMbr.getAttributeDetails())) {
1443 					for (RoleMemberAttributeDataBo attr : roleMbr.getAttributeDetails()) {
1444 						if (StringUtils.isBlank(attr.getAttributeValue())) {
1445 							roleMemberAttrs.add(attr);
1446 						}
1447 					}
1448 					if (!roleMemberAttrs.isEmpty()) {
1449 						roleMbr.getAttributeDetails().removeAll(roleMemberAttrs);
1450 						blankRoleMemberAttrs.addAll(roleMemberAttrs);
1451 					}
1452 
1453 				}
1454 			}
1455 		}
1456 
1457 		return blankRoleMemberAttrs;
1458 
1459 	}
1460 
1461     protected List <RoleResponsibilityActionBo> populateRoleRspActions(IdentityManagementPersonDocument identityManagementPersonDocument) {
1462 //		List<RoleImpl> origRoles = getRolesForPrincipal(identityManagementPersonDocument.getPrincipalId());
1463 
1464 		List <RoleResponsibilityActionBo>  roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
1465 		if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getRoles())){
1466 			for (PersonDocumentRole role : identityManagementPersonDocument.getRoles()) {
1467 				if(CollectionUtils.isNotEmpty(role.getRolePrncpls())){
1468 					for (KimDocumentRoleMember roleMbr : role.getRolePrncpls()) {
1469 						if(CollectionUtils.isNotEmpty(roleMbr.getRoleRspActions())){
1470 							for (KimDocumentRoleResponsibilityAction roleRspAction : roleMbr.getRoleRspActions()) {
1471 								RoleResponsibilityActionBo entRoleRspAction = new RoleResponsibilityActionBo();
1472 								entRoleRspAction.setId(roleRspAction.getRoleResponsibilityActionId());
1473 								entRoleRspAction.setActionPolicyCode(roleRspAction.getActionPolicyCode());
1474 								entRoleRspAction.setActionTypeCode(roleRspAction.getActionTypeCode());
1475 								entRoleRspAction.setPriorityNumber(roleRspAction.getPriorityNumber());
1476 								entRoleRspAction.setRoleMemberId(roleRspAction.getRoleMemberId());
1477 								entRoleRspAction.setRoleResponsibilityId(roleRspAction.getRoleResponsibilityId());
1478 								List<RoleResponsibilityActionBo> actions = getRoleRspActions( roleMbr.getRoleMemberId());
1479 								if(ObjectUtils.isNotNull(actions)){
1480 									for(RoleResponsibilityActionBo orgRspAction : actions) {
1481 										if (orgRspAction.getId()!=null && StringUtils.equals(orgRspAction.getId(), roleRspAction.getRoleResponsibilityActionId())) {
1482 											entRoleRspAction.setVersionNumber(orgRspAction.getVersionNumber());
1483 										}
1484 									}
1485 								}
1486 								roleRspActions.add(entRoleRspAction);
1487 							}
1488 						}
1489 					}
1490 				}
1491 			}
1492 		}
1493 		return roleRspActions;
1494 
1495 	}
1496 
1497 	protected BusinessObjectService getBusinessObjectService() {
1498 		if ( businessObjectService == null ) {
1499 			businessObjectService = KRADServiceLocator.getBusinessObjectService();
1500 		}
1501 		return businessObjectService;
1502 	}
1503 
1504 	protected IdentityService getIdentityService() {
1505 		if ( identityService == null ) {
1506 			identityService = KimApiServiceLocator.getIdentityService();
1507 		}
1508 		return identityService;
1509 	}
1510 
1511 	protected GroupService getGroupService() {
1512 		if ( groupService == null ) {
1513 			groupService = KimApiServiceLocator.getGroupService();
1514 		}
1515 		return groupService;
1516 	}
1517 
1518 	protected DocumentHelperService getDocumentHelperService() {
1519 	    if ( documentHelperService == null ) {
1520 	        documentHelperService = KRADServiceLocatorWeb.getDocumentHelperService();
1521 		}
1522 	    return this.documentHelperService;
1523 	}
1524 
1525 	protected RoleService getRoleService() {
1526 	   	if(roleService == null){
1527 	   		roleService = KimApiServiceLocator.getRoleService();
1528     	}
1529 		return roleService;
1530 	}
1531 
1532 	public void setRoleService(RoleService roleService) {
1533 		this.roleService = roleService;
1534 	}
1535 
1536 	protected ResponsibilityService getResponsibilityService() {
1537 	   	if ( responsibilityService == null ) {
1538     		responsibilityService = KimApiServiceLocator.getResponsibilityService();
1539     	}
1540 		return responsibilityService;
1541 	}
1542 
1543 	public void setResponsibilityService(ResponsibilityService responsibilityService) {
1544 		this.responsibilityService = responsibilityService;
1545 	}
1546 
1547 
1548 	/* Role document methods */
1549 	@SuppressWarnings("unchecked")
1550 	public void loadRoleDoc(IdentityManagementRoleDocument identityManagementRoleDocument, Role role){
1551 		Map<String, String> criteria = new HashMap<String, String>();
1552 		criteria.put(KimConstants.PrimaryKeyConstants.ROLE_ID, role.getId());
1553 		RoleBo roleBo = getBusinessObjectService().findByPrimaryKey(RoleBo.class, criteria);
1554 
1555         Map<String, String> subClassCriteria = new HashMap<String, String>();
1556 		criteria.put(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, role.getId());
1557 
1558 		identityManagementRoleDocument.setRoleId(roleBo.getId());
1559 		identityManagementRoleDocument.setKimType(KimTypeBo.to(roleBo.getKimRoleType()));
1560 		identityManagementRoleDocument.setRoleTypeName(roleBo.getKimRoleType().getName());
1561 		identityManagementRoleDocument.setRoleTypeId(roleBo.getKimTypeId());
1562 		identityManagementRoleDocument.setRoleName(roleBo.getName());
1563 		identityManagementRoleDocument.setRoleDescription(roleBo.getDescription());
1564 		identityManagementRoleDocument.setActive(roleBo.isActive());
1565 		identityManagementRoleDocument.setRoleNamespace(roleBo.getNamespaceCode());
1566 		identityManagementRoleDocument.setEditing(true);
1567 
1568 		identityManagementRoleDocument.setPermissions(loadPermissions((List<RolePermissionBo>)getBusinessObjectService().findMatching(RolePermissionBo.class, subClassCriteria)));
1569 		identityManagementRoleDocument.setResponsibilities(loadResponsibilities((List<RoleResponsibilityBo>)getBusinessObjectService().findMatching(RoleResponsibilityBo.class, subClassCriteria)));
1570 		loadResponsibilityRoleRspActions(identityManagementRoleDocument);
1571 		identityManagementRoleDocument.setMembers(loadRoleMembers(identityManagementRoleDocument, roleBo.getMembers()));
1572 		loadMemberRoleRspActions(identityManagementRoleDocument);
1573 		identityManagementRoleDocument.setDelegations(loadRoleDocumentDelegations(identityManagementRoleDocument, getRoleDelegations(roleBo.getId())));
1574 		//Since delegation members are flattened out on the UI...
1575 		setDelegationMembersInDocument(identityManagementRoleDocument);
1576 		identityManagementRoleDocument.setKimType(KimTypeBo.to(roleBo.getKimRoleType()));
1577 	}
1578 
1579 	public void setDelegationMembersInDocument(IdentityManagementRoleDocument identityManagementRoleDocument){
1580 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getDelegations())){
1581 			for(RoleDocumentDelegation delegation: identityManagementRoleDocument.getDelegations()){
1582 				if(CollectionUtils.isNotEmpty(delegation.getMembers())){
1583 					for(RoleDocumentDelegationMember member: delegation.getMembers()){
1584 						member.setDelegationTypeCode(delegation.getDelegationTypeCode());
1585 						identityManagementRoleDocument.getDelegationMembers().add(member);
1586 					}
1587 				}
1588 			}
1589 		}
1590 	}
1591 
1592 	protected List<KimDocumentRoleResponsibility> loadResponsibilities(List<RoleResponsibilityBo> roleResponsibilities){
1593 		List<KimDocumentRoleResponsibility> documentRoleResponsibilities = new ArrayList<KimDocumentRoleResponsibility>();
1594 		if(ObjectUtils.isNotNull(roleResponsibilities)){
1595 			for(RoleResponsibilityBo roleResponsibility: roleResponsibilities){
1596 				if(roleResponsibility.isActive()) {
1597 					KimDocumentRoleResponsibility roleResponsibilityCopy = new KimDocumentRoleResponsibility();
1598 					KimCommonUtilsInternal.copyProperties(roleResponsibilityCopy, roleResponsibility);
1599 					roleResponsibilityCopy.setEdit(true);
1600 					documentRoleResponsibilities.add(roleResponsibilityCopy);
1601 				}
1602 			}
1603 		}
1604 		return documentRoleResponsibilities;
1605 	}
1606 
1607 	protected List<KimDocumentRolePermission> loadPermissions(List<RolePermissionBo> rolePermissions){
1608 		List<KimDocumentRolePermission> documentRolePermissions = new ArrayList<KimDocumentRolePermission>();
1609 		KimDocumentRolePermission rolePermissionCopy;
1610 		if(ObjectUtils.isNotNull(rolePermissions)){
1611 			for(RolePermissionBo rolePermission: rolePermissions){
1612 				if ( rolePermission.isActive() ) {
1613 					rolePermissionCopy = new KimDocumentRolePermission();
1614 					rolePermissionCopy.setRolePermissionId(rolePermission.getId());
1615 					rolePermissionCopy.setRoleId(rolePermission.getRoleId());
1616 					rolePermissionCopy.setPermissionId(rolePermission.getPermissionId());
1617 					rolePermissionCopy.setPermission(PermissionBo.to(rolePermission.getPermission()));
1618 					rolePermissionCopy.setEdit(true);
1619 					documentRolePermissions.add(rolePermissionCopy);
1620 				}
1621 			}
1622 		}
1623 		return documentRolePermissions;
1624 	}
1625 
1626 	protected List<KimDocumentRoleMember> loadRoleMembers(
1627 			IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleMemberBo> members){
1628 		List<KimDocumentRoleMember> pndMembers = new ArrayList<KimDocumentRoleMember>();
1629 		KimDocumentRoleMember pndMember;
1630 		if(ObjectUtils.isNotNull(members)){
1631 			for(RoleMemberBo member: members){
1632 				pndMember = new KimDocumentRoleMember();
1633 				pndMember.setActiveFromDate(member.getActiveFromDate());
1634 				pndMember.setActiveToDate(member.getActiveToDate());
1635 				pndMember.setActive(member.isActive(new Timestamp(System.currentTimeMillis())));
1636 				if(pndMember.isActive()){
1637 					pndMember.setRoleMemberId(member.getRoleMemberId());
1638 					pndMember.setRoleId(member.getRoleId());
1639 					pndMember.setMemberId(member.getMemberId());
1640 					pndMember.setMemberNamespaceCode(getMemberNamespaceCode(member.getMemberTypeCode(), member.getMemberId()));
1641 					pndMember.setMemberName(getMemberName(member.getMemberTypeCode(), member.getMemberId()));
1642 					pndMember.setMemberFullName(getMemberFullName(member.getMemberTypeCode(), member.getMemberId()));
1643 					pndMember.setMemberTypeCode(member.getMemberTypeCode());
1644 					pndMember.setQualifiers(loadRoleMemberQualifiers(identityManagementRoleDocument, member.getAttributeDetails()));
1645 					pndMember.setEdit(true);
1646 					pndMembers.add(pndMember);
1647 				}
1648 			}
1649 		}
1650             Collections.sort(pndMembers, identityManagementRoleDocument.getMemberMetaDataType());
1651 		return pndMembers;
1652 	}
1653 
1654 	protected void loadResponsibilityRoleRspActions(IdentityManagementRoleDocument identityManagementRoleDocument){
1655 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
1656 			for(KimDocumentRoleResponsibility responsibility: identityManagementRoleDocument.getResponsibilities()){
1657 				responsibility.getRoleRspActions().addAll(loadKimDocumentRoleRespActions(
1658 						getRoleResponsibilityActionImpls(responsibility.getRoleResponsibilityId())));
1659 			}
1660 		}
1661 	}
1662 
1663 	@SuppressWarnings("unchecked")
1664 	protected List<RoleResponsibilityActionBo> getRoleResponsibilityActionImpls(String roleResponsibilityId){
1665 		Map<String, String> criteria = new HashMap<String, String>();
1666 		criteria.put(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID, "*");
1667 		criteria.put(KimConstants.PrimaryKeyConstants.ROLE_RESPONSIBILITY_ID, roleResponsibilityId);
1668 		return (List<RoleResponsibilityActionBo>)
1669 			getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
1670 	}
1671 
1672 	@SuppressWarnings("unchecked")
1673 	public List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActionImpls(String roleMemberId){
1674 		Map<String, String> criteria = new HashMap<String, String>(1);
1675 		criteria.put(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID, roleMemberId);
1676 		return (List<RoleResponsibilityActionBo>)
1677 			getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
1678 	}
1679 
1680 	protected void loadMemberRoleRspActions(IdentityManagementRoleDocument identityManagementRoleDocument){
1681 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
1682 			for(KimDocumentRoleMember member: identityManagementRoleDocument.getMembers()){
1683 				member.getRoleRspActions().addAll(loadKimDocumentRoleRespActions(
1684 						getRoleMemberResponsibilityActionImpls(member.getRoleMemberId()) ) );
1685 			}
1686 		}
1687 	}
1688 
1689 	protected List<KimDocumentRoleResponsibilityAction> loadKimDocumentRoleRespActions(
1690 			List<RoleResponsibilityActionBo> roleRespActionImpls){
1691 		List<KimDocumentRoleResponsibilityAction> documentRoleRespActions = new ArrayList<KimDocumentRoleResponsibilityAction>();
1692 		KimDocumentRoleResponsibilityAction documentRoleRespAction;
1693 		if(ObjectUtils.isNotNull(roleRespActionImpls)){
1694 			for(RoleResponsibilityActionBo roleRespActionImpl: roleRespActionImpls){
1695 				documentRoleRespAction = new KimDocumentRoleResponsibilityAction();
1696 				KimCommonUtilsInternal.copyProperties(documentRoleRespAction, roleRespActionImpl);
1697 				// handle the roleResponsibility object being null since not all may be defined when ID value is "*"
1698 				if ( ObjectUtils.isNotNull(roleRespActionImpl.getRoleResponsibility()) ) {
1699 					documentRoleRespAction.setKimResponsibility(roleRespActionImpl.getRoleResponsibility().getKimResponsibility());
1700 				}
1701 				documentRoleRespActions.add(documentRoleRespAction);
1702 			}
1703 		}
1704 		return documentRoleRespActions;
1705 	}
1706 
1707     public BusinessObject getMember(String memberTypeCode, String memberId){
1708         Class<? extends BusinessObject> roleMemberTypeClass = null;
1709         String roleMemberIdName = "";
1710     	if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1711         	roleMemberTypeClass = PrincipalBo.class;
1712         	roleMemberIdName = KimConstants.PrimaryKeyConstants.PRINCIPAL_ID;
1713 	 	 	Principal principalInfo = getIdentityService().getPrincipal(memberId);
1714 	 	 	if (principalInfo != null) {
1715 	 	 		
1716 	 	 	}
1717         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1718         	roleMemberTypeClass = GroupBo.class;
1719         	roleMemberIdName = KimConstants.PrimaryKeyConstants.GROUP_ID;
1720         	Group groupInfo = null;
1721 	 	 	groupInfo = getGroupService().getGroup(memberId);
1722 	 	 	if (groupInfo != null) {
1723 	 	 		
1724 	 	 	}
1725         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1726         	roleMemberTypeClass = RoleBo.class;
1727         	roleMemberIdName = KimConstants.PrimaryKeyConstants.ROLE_ID;
1728 	 	 	Role role = getRoleService().getRole(memberId);
1729 	 	 	if (role != null) {
1730 	 	 		
1731 	 	 	}
1732         }
1733         Map<String, String> criteria = new HashMap<String, String>();
1734         criteria.put(roleMemberIdName, memberId);
1735         return getBusinessObjectService().findByPrimaryKey(roleMemberTypeClass, criteria);
1736     }
1737 
1738 	public String getMemberName(String memberTypeCode, String memberId){
1739 		if (StringUtils.isEmpty(memberTypeCode) || StringUtils.isEmpty(memberId)) { return "";}
1740 		BusinessObject member = getMember(memberTypeCode, memberId);
1741 		if (member == null) { //not a REAL principal, try to fake the name
1742 			String fakeName = "";
1743 			Principal kp = KimApiServiceLocator.getIdentityService().getPrincipal(memberId);
1744 			if(kp != null && kp.getPrincipalName() != null && !"".equals(kp.getPrincipalName())){
1745 				fakeName = kp.getPrincipalName();
1746 			}
1747 
1748 			return fakeName;
1749 		}
1750 		return getMemberName(memberTypeCode, member);
1751 	}
1752 
1753 	public String getMemberFullName(String memberTypeCode, String memberId){
1754 		if(StringUtils.isEmpty(memberTypeCode) || StringUtils.isEmpty(memberId)) {return "";}
1755 	   	String memberFullName = "";
1756         if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1757         	Principal principalInfo = null;
1758         	principalInfo = getIdentityService().getPrincipal(memberId);
1759         	if (principalInfo != null) {
1760         		String principalName = principalInfo.getPrincipalName();
1761         		Person psn = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(principalName);
1762         		memberFullName = psn.getFirstName() + " " + psn.getLastName();
1763         	}        	        	
1764         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1765         	Group group = null;
1766         	group = getGroupService().getGroup(memberId);
1767         	if (group != null) {
1768         		memberFullName = group.getName();
1769         	}
1770         	
1771         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1772         	Role role = getRoleService().getRole(memberId);
1773         	memberFullName = role.getName();
1774         }
1775         return memberFullName;
1776 	}
1777 
1778 	public String getMemberNamespaceCode(String memberTypeCode, String memberId){
1779 		if(StringUtils.isEmpty(memberTypeCode) || StringUtils.isEmpty(memberId)) {return "";}
1780     	String roleMemberNamespaceCode = "";
1781         if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1782         	roleMemberNamespaceCode = "";
1783         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1784         	Group groupInfo = getGroupService().getGroup(memberId);
1785         	if (groupInfo!= null) {
1786         		roleMemberNamespaceCode = groupInfo.getNamespaceCode();
1787         	}
1788         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1789         	Role role = getRoleService().getRole(memberId);
1790         	if (role != null) {
1791         		roleMemberNamespaceCode = role.getNamespaceCode();
1792         	}        	
1793         }
1794         return roleMemberNamespaceCode;
1795 	}
1796 
1797     public String getMemberIdByName(String memberTypeCode, String memberNamespaceCode, String memberName){
1798     	String memberId = "";
1799         if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1800             Principal principal = getIdentityService().getPrincipalByPrincipalName(memberName);
1801             if(principal!=null) {
1802                 memberId = principal.getPrincipalId();
1803             }
1804 
1805        } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1806         	Group groupInfo = getGroupService().getGroupByName(memberNamespaceCode, memberName);
1807         	if (groupInfo!=null) {
1808                 memberId = groupInfo.getId();
1809             }
1810 
1811         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1812         	memberId = getRoleService().getRoleIdByName(memberNamespaceCode, memberName);
1813         }
1814         return memberId;
1815     }
1816 
1817     public String getMemberName(String memberTypeCode, BusinessObject member){
1818     	String roleMemberName = "";
1819         if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1820         	roleMemberName = ((PrincipalBo)member).getPrincipalName();
1821         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1822         	roleMemberName = ((GroupBo)member).getName();
1823         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1824         	roleMemberName = ((RoleBo)member).getName();
1825         }
1826         return roleMemberName;
1827     }
1828 
1829     public String getMemberNamespaceCode(String memberTypeCode, BusinessObject member){
1830     	String roleMemberNamespaceCode = "";
1831         if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
1832         	roleMemberNamespaceCode = "";
1833         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
1834         	roleMemberNamespaceCode = ((GroupBo)member).getNamespaceCode();
1835         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
1836         	roleMemberNamespaceCode = ((RoleBo)member).getNamespaceCode();
1837         }
1838         return roleMemberNamespaceCode;
1839     }
1840 
1841     protected List<KimDocumentRoleQualifier> loadRoleMemberQualifiers(IdentityManagementRoleDocument identityManagementRoleDocument,
1842 			List<RoleMemberAttributeDataBo> attributeDataList){
1843 		List<KimDocumentRoleQualifier> pndMemberRoleQualifiers = new ArrayList<KimDocumentRoleQualifier>();
1844 		KimDocumentRoleQualifier pndMemberRoleQualifier;
1845 
1846 		// add all attributes from attributeDataList
1847 		if(attributeDataList!=null){
1848 			for(RoleMemberAttributeDataBo memberRoleQualifier: attributeDataList){
1849 				pndMemberRoleQualifier = new KimDocumentRoleQualifier();
1850 				pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
1851 				pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
1852 				pndMemberRoleQualifier.setRoleMemberId(memberRoleQualifier.getAssignedToId());
1853 				pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
1854 				pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
1855 				pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
1856 				formatAttrValIfNecessary(pndMemberRoleQualifier);
1857 				pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
1858 			}
1859 		}
1860 		// also add any attributes already in the document that are not in the attributeDataList
1861 		int countOfOriginalAttributesNotPresent = 0;
1862 		List<KimDocumentRoleQualifier> fillerRoleQualifiers = new ArrayList<KimDocumentRoleQualifier>();
1863 
1864 		AttributeDefinitionMap origAttributes = identityManagementRoleDocument.getDefinitions();
1865 		if ( origAttributes != null ) {
1866 			for(String key: origAttributes.keySet()) {
1867 				boolean attributePresent = false;
1868 				String origAttributeId = identityManagementRoleDocument.getKimAttributeDefnId(origAttributes.get(key));
1869 				if(attributeDataList!=null){
1870 					for(RoleMemberAttributeDataBo memberRoleQualifier: attributeDataList){
1871 						if(origAttributeId!=null && StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
1872 							attributePresent = true;
1873 							break;
1874 						}
1875 					}
1876 				}
1877 				if(!attributePresent){
1878 					countOfOriginalAttributesNotPresent++;
1879 					pndMemberRoleQualifier = new KimDocumentRoleQualifier();
1880 					pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
1881 					pndMemberRoleQualifier.refreshReferenceObject("kimAttribute");
1882 					fillerRoleQualifiers.add(pndMemberRoleQualifier);
1883 				}
1884 			}
1885 
1886 			if(countOfOriginalAttributesNotPresent != origAttributes.size()) {
1887 				pndMemberRoleQualifiers.addAll(fillerRoleQualifiers);
1888 			}
1889 		}
1890 		return pndMemberRoleQualifiers;
1891 	}
1892 
1893     @SuppressWarnings("unchecked")
1894 	public List<DelegateBo> getRoleDelegations(String roleId){
1895 		if(roleId==null) {
1896 			return new ArrayList<DelegateBo>();
1897         }
1898 		Map<String,String> criteria = new HashMap<String,String>(1);
1899 		criteria.put("roleId", roleId);
1900 		return (List<DelegateBo>)getBusinessObjectService().findMatching(DelegateBo.class, criteria);
1901 	}
1902 
1903     protected List<RoleDocumentDelegation> loadRoleDocumentDelegations(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateBo> delegations){
1904 		List<RoleDocumentDelegation> delList = new ArrayList<RoleDocumentDelegation>();
1905 		RoleDocumentDelegation documentDelegation;
1906 		if(ObjectUtils.isNotNull(delegations)){
1907 			for(DelegateBo del: delegations){
1908 				documentDelegation = new RoleDocumentDelegation();
1909 				documentDelegation.setActive(del.isActive());
1910 				if(documentDelegation.isActive()){
1911 					documentDelegation.setDelegationId(del.getDelegationId());
1912 					documentDelegation.setDelegationTypeCode(del.getDelegationTypeCode());
1913 					documentDelegation.setKimTypeId(del.getKimTypeId());
1914 					documentDelegation.setMembers(loadDelegationMembers(identityManagementRoleDocument, del.getMembers()));
1915 					documentDelegation.setRoleId(del.getRoleId());
1916 					documentDelegation.setEdit(true);
1917 					delList.add(documentDelegation);
1918 				}
1919 			}
1920 		}
1921 		return delList;
1922 	}
1923 
1924     protected List<RoleDocumentDelegationMember> loadDelegationMembers(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateMemberBo> members){
1925 		List<RoleDocumentDelegationMember> pndMembers = new ArrayList<RoleDocumentDelegationMember>();
1926 		RoleDocumentDelegationMember pndMember;
1927 		RoleMemberBo roleMember;
1928 		if(ObjectUtils.isNotNull(members)){
1929 			for(DelegateMemberBo member: members){
1930 				pndMember = new RoleDocumentDelegationMember();
1931 				pndMember.setActiveFromDate(member.getActiveFromDate());
1932 				pndMember.setActiveToDate(member.getActiveToDate());
1933 				pndMember.setActive(member.isActive(new Timestamp(System.currentTimeMillis())));
1934 				if(pndMember.isActive()){
1935 					KimCommonUtilsInternal.copyProperties(pndMember, member);
1936 					pndMember.setRoleMemberId(member.getRoleMemberId());
1937 					roleMember = getRoleMemberForRoleMemberId(member.getRoleMemberId());
1938 					if(roleMember!=null){
1939 						pndMember.setRoleMemberName(getMemberName(roleMember.getMemberTypeCode(), roleMember.getMemberId()));
1940 						pndMember.setRoleMemberNamespaceCode(getMemberNamespaceCode(roleMember.getMemberTypeCode(), roleMember.getMemberId()));
1941 					}
1942 					pndMember.setMemberNamespaceCode(getMemberNamespaceCode(member.getTypeCode(), member.getMemberId()));
1943 					pndMember.setMemberName(getMemberName(member.getTypeCode(), member.getMemberId()));
1944 					pndMember.setEdit(true);
1945 					pndMember.setQualifiers(loadDelegationMemberQualifiers(identityManagementRoleDocument, member.getAttributes()));
1946 					pndMembers.add(pndMember);
1947 				}
1948 			}
1949 		}
1950 		return pndMembers;
1951 	}
1952 
1953     protected RoleMemberBo getRoleMemberForRoleMemberId(String roleMemberId){
1954 		Map<String,String> criteria = new HashMap<String,String>( 2 );
1955 		criteria.put(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID, roleMemberId);
1956 		return getBusinessObjectService().findByPrimaryKey(RoleMemberBo.class, criteria);
1957     }
1958 
1959     protected List<RoleDocumentDelegationMemberQualifier> loadDelegationMemberQualifiers(IdentityManagementRoleDocument identityManagementRoleDocument,
1960 			List<DelegateMemberAttributeDataBo> attributeDataList){
1961 		List<RoleDocumentDelegationMemberQualifier> pndMemberRoleQualifiers = new ArrayList<RoleDocumentDelegationMemberQualifier>();
1962 		RoleDocumentDelegationMemberQualifier pndMemberRoleQualifier;
1963 		AttributeDefinitionMap origAttributes = identityManagementRoleDocument.getDefinitions();
1964 		boolean attributePresent = false;
1965 		String origAttributeId;
1966 		if(origAttributes!=null){
1967 			for(String key: origAttributes.keySet()) {
1968 				origAttributeId = identityManagementRoleDocument.getKimAttributeDefnId(origAttributes.get(key));
1969 				if(attributeDataList!=null){
1970 					for(DelegateMemberAttributeDataBo memberRoleQualifier: attributeDataList){
1971 						if(origAttributeId!=null && StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
1972 							pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
1973 							pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
1974 							pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
1975 							pndMemberRoleQualifier.setDelegationMemberId(memberRoleQualifier.getAssignedToId());
1976 							pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
1977 							pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
1978 							pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
1979 							pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
1980 							attributePresent = true;
1981 						}
1982 					}
1983 				}
1984 				if(!attributePresent){
1985 					pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
1986 					pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
1987 					pndMemberRoleQualifier.refreshReferenceObject("kimAttribute");
1988 					pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
1989 				}
1990 				attributePresent = false;
1991 			}
1992 		}
1993 		return pndMemberRoleQualifiers;
1994 	}
1995 
1996 	/**
1997 	 * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
1998 	 */
1999 	@SuppressWarnings("unchecked")
2000 	public void saveRole(IdentityManagementRoleDocument identityManagementRoleDocument) {
2001 		RoleBo roleBo = new RoleBo();
2002 		Map<String, String> criteria = new HashMap<String, String>();
2003 		String roleId = identityManagementRoleDocument.getRoleId();
2004 		criteria.put(KimConstants.PrimaryKeyConstants.ID, roleId);
2005 		RoleBo origRole = getBusinessObjectService().findByPrimaryKey(RoleBo.class, criteria);
2006 
2007 		List<RolePermissionBo> origRolePermissions = new ArrayList<RolePermissionBo>();
2008 		List<RoleResponsibilityBo> origRoleResponsibilities = new ArrayList<RoleResponsibilityBo>();
2009 		List<RoleMemberBo> origRoleMembers = new ArrayList<RoleMemberBo>();
2010 		List<DelegateBo> origRoleDelegations = new ArrayList<DelegateBo>();
2011 
2012 		roleBo.setId(identityManagementRoleDocument.getRoleId());
2013 		roleBo.setKimTypeId(identityManagementRoleDocument.getRoleTypeId());
2014 		roleBo.setNamespaceCode(identityManagementRoleDocument.getRoleNamespace());
2015 		roleBo.setName(identityManagementRoleDocument.getRoleName());
2016 		roleBo.setDescription(identityManagementRoleDocument.getRoleDescription());
2017 
2018 		if (origRole == null) {
2019 			origRole = new RoleBo();
2020 			roleBo.setActive(true);
2021 		} else {
2022 			roleBo.setActive(identityManagementRoleDocument.isActive());
2023 			roleBo.setVersionNumber(origRole.getVersionNumber());
2024 			origRolePermissions = new ArrayList<RolePermissionBo>(getBusinessObjectService().findMatching(RolePermissionBo.class, criteria));
2025 			origRoleResponsibilities = (List<RoleResponsibilityBo>)getBusinessObjectService().findMatching(RoleResponsibilityBo.class, criteria);
2026 			origRoleMembers = (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, criteria);
2027 			origRoleDelegations = (List<DelegateBo>)getBusinessObjectService().findMatching(DelegateBo.class, criteria);
2028 		}
2029 
2030 		if( getKimTypeInfoService().getKimType(identityManagementRoleDocument.getRoleTypeId()) == null ) {
2031 			LOG.error( "Kim type not found for:"+identityManagementRoleDocument.getRoleTypeId(), new Throwable() );
2032 		}
2033 
2034 		List<PersistableBusinessObject> bos = new ArrayList<PersistableBusinessObject>();
2035 
2036 		bos.add(roleBo);
2037 		bos.addAll(getRolePermissions(identityManagementRoleDocument, origRolePermissions));
2038 		bos.addAll(getRoleResponsibilities(identityManagementRoleDocument, origRoleResponsibilities));
2039 		bos.addAll(getRoleResponsibilitiesActions(identityManagementRoleDocument));
2040 		String initiatorPrincipalId = getInitiatorPrincipalId(identityManagementRoleDocument);
2041 		if(canAssignToRole(identityManagementRoleDocument, initiatorPrincipalId)){
2042 			List<RoleMemberBo> newRoleMembersList = getRoleMembers(identityManagementRoleDocument, origRoleMembers);
2043 			bos.addAll(newRoleMembersList);
2044 			bos.addAll(getRoleMemberResponsibilityActions(newRoleMembersList));
2045 			//bos.addAll(getRoleMemberResponsibilityActions(identityManagementRoleDocument));
2046 			bos.addAll(getRoleDelegations(identityManagementRoleDocument, origRoleDelegations));
2047 		}
2048 		getBusinessObjectService().save(bos);
2049 		IdentityManagementNotificationService service = (IdentityManagementNotificationService) KsbApiServiceLocator.getMessageHelper().getServiceAsynchronously(new QName("KIM", "kimIdentityManagementNotificationService"));
2050         service.roleUpdated();
2051 		org.kuali.rice.kim.impl.services.KIMServiceLocatorInternal.getResponsibilityInternalService().updateActionRequestsForResponsibilityChange(getChangedRoleResponsibilityIds(identityManagementRoleDocument, origRoleResponsibilities));
2052 		if(!roleBo.isActive()){
2053 			// when a role is inactivated, inactivate the memberships of principals, groups, and roles in
2054 			// that role, delegations, and delegation members, and that roles memberships in other roles
2055 			KimApiServiceLocator.getRoleService().roleInactivated(identityManagementRoleDocument.getRoleId());
2056 		}
2057 	}
2058 
2059 	protected List<RolePermissionBo> getRolePermissions(
2060 			IdentityManagementRoleDocument identityManagementRoleDocument, List<RolePermissionBo> origRolePermissions){
2061 		List<RolePermissionBo> rolePermissions = new ArrayList<RolePermissionBo>();
2062 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getPermissions())){
2063 			for(KimDocumentRolePermission documentRolePermission: identityManagementRoleDocument.getPermissions()){
2064 				RolePermissionBo newRolePermission = new RolePermissionBo();
2065 				newRolePermission.setId(documentRolePermission.getRolePermissionId());
2066 				newRolePermission.setRoleId(identityManagementRoleDocument.getRoleId());
2067 				newRolePermission.setPermissionId(documentRolePermission.getPermissionId());
2068 				newRolePermission.setActive( documentRolePermission.isActive() );
2069 
2070 				newRolePermission.setActive(documentRolePermission.isActive());
2071 				if(ObjectUtils.isNotNull(origRolePermissions)){
2072 					for(RolePermissionBo origPermissionImpl: origRolePermissions){
2073 						if(!StringUtils.equals(origPermissionImpl.getRoleId(), newRolePermission.getRoleId()) &&
2074 								StringUtils.equals(origPermissionImpl.getPermissionId(), newRolePermission.getPermissionId()) &&
2075 								!origPermissionImpl.isActive() && newRolePermission.isActive()){
2076 							newRolePermission.setId(origPermissionImpl.getId());
2077 						}
2078 						if(origPermissionImpl.getId()!=null && StringUtils.equals(origPermissionImpl.getId(), newRolePermission.getId())){
2079 							newRolePermission.setVersionNumber(origPermissionImpl.getVersionNumber());
2080 						}
2081 					}
2082 				}
2083 				rolePermissions.add(newRolePermission);
2084 			}
2085 		}
2086 		return rolePermissions;
2087 	}
2088 
2089 	protected List<RoleResponsibilityBo> getRoleResponsibilities(
2090 			IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleResponsibilityBo> origRoleResponsibilities){
2091 		List<RoleResponsibilityBo> roleResponsibilities = new ArrayList<RoleResponsibilityBo>();
2092 		RoleResponsibilityBo newRoleResponsibility;
2093 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2094 			for(KimDocumentRoleResponsibility documentRoleResponsibility: identityManagementRoleDocument.getResponsibilities()){
2095 				newRoleResponsibility = new RoleResponsibilityBo();
2096 				KimCommonUtilsInternal.copyProperties(newRoleResponsibility, documentRoleResponsibility);
2097 				newRoleResponsibility.setActive(documentRoleResponsibility.isActive());
2098 				newRoleResponsibility.setRoleId(identityManagementRoleDocument.getRoleId());
2099 				if(ObjectUtils.isNotNull(origRoleResponsibilities)){
2100 					for(RoleResponsibilityBo origResponsibilityImpl: origRoleResponsibilities){
2101 						if(!StringUtils.equals(origResponsibilityImpl.getRoleId(), newRoleResponsibility.getRoleId()) &&
2102 								StringUtils.equals(origResponsibilityImpl.getResponsibilityId(), newRoleResponsibility.getResponsibilityId()) &&
2103 								!origResponsibilityImpl.isActive() && newRoleResponsibility.isActive()){
2104 							newRoleResponsibility.setRoleResponsibilityId(origResponsibilityImpl.getRoleResponsibilityId());
2105 						}
2106 						if(origResponsibilityImpl.getRoleResponsibilityId()!=null && StringUtils.equals(origResponsibilityImpl.getRoleResponsibilityId(), newRoleResponsibility.getRoleResponsibilityId())) {
2107                             newRoleResponsibility.setVersionNumber(origResponsibilityImpl.getVersionNumber());
2108                         }
2109 					}
2110 				}
2111 				roleResponsibilities.add(newRoleResponsibility);
2112 			}
2113 		}
2114 		return roleResponsibilities;
2115 	}
2116 
2117 
2118 	protected List <RoleResponsibilityActionBo> getRoleResponsibilitiesActions(
2119 			IdentityManagementRoleDocument identityManagementRoleDocument){
2120 		List <RoleResponsibilityActionBo>  roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2121 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2122 		// loop over the responsibilities assigned to the role
2123 			for(KimDocumentRoleResponsibility roleResponsibility : identityManagementRoleDocument.getResponsibilities()){
2124 				// only process if the actions are not assigned at the role member level
2125 				if(!getResponsibilityInternalService().areActionsAtAssignmentLevelById(roleResponsibility.getResponsibilityId())){
2126 					List<KimDocumentRoleResponsibilityAction> documentRoleResponsibilityActions = roleResponsibility.getRoleRspActions();
2127 					if( ObjectUtils.isNotNull(documentRoleResponsibilityActions)
2128 							&& !documentRoleResponsibilityActions.isEmpty()
2129 							&& StringUtils.isNotBlank(documentRoleResponsibilityActions.get(0).getRoleResponsibilityActionId() ) ) {
2130 						RoleResponsibilityActionBo roleRspAction = new RoleResponsibilityActionBo();
2131 						roleRspAction.setId(documentRoleResponsibilityActions.get(0).getRoleResponsibilityActionId());
2132 						roleRspAction.setActionPolicyCode(documentRoleResponsibilityActions.get(0).getActionPolicyCode());
2133 						roleRspAction.setActionTypeCode(documentRoleResponsibilityActions.get(0).getActionTypeCode());
2134 						roleRspAction.setPriorityNumber(documentRoleResponsibilityActions.get(0).getPriorityNumber());
2135 						roleRspAction.setForceAction(documentRoleResponsibilityActions.get(0).isForceAction());
2136 						roleRspAction.setRoleMemberId("*");
2137 						roleRspAction.setRoleResponsibilityId(documentRoleResponsibilityActions.get(0).getRoleResponsibilityId());
2138 						updateResponsibilityActionVersionNumber(roleRspAction, getRoleResponsibilityActionImpls(roleResponsibility.getRoleResponsibilityId()));
2139 						roleRspActions.add(roleRspAction);
2140 					}
2141 				}
2142 			}
2143 		}
2144 		return roleRspActions;
2145 	}
2146 
2147 	// FIXME: This should be pulling by the PK, not using another method which pulls multiple records and then finds
2148 	// the right one here!
2149 	protected void updateResponsibilityActionVersionNumber(RoleResponsibilityActionBo newRoleRspAction,
2150 			List<RoleResponsibilityActionBo> origRoleRespActionImpls){
2151 		if(ObjectUtils.isNotNull(origRoleRespActionImpls)){
2152 			for(RoleResponsibilityActionBo origRoleResponsibilityActionImpl: origRoleRespActionImpls){
2153 				if(origRoleResponsibilityActionImpl.getId()!=null && StringUtils.equals(origRoleResponsibilityActionImpl.getId(),
2154 						newRoleRspAction.getId())) {
2155 					newRoleRspAction.setVersionNumber(origRoleResponsibilityActionImpl.getVersionNumber());
2156 					break;
2157 				}
2158 			}
2159 		}
2160 	}
2161 
2162 	protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(List<RoleMemberBo> newRoleMembersList){
2163 		List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2164 		if(ObjectUtils.isNotNull(newRoleMembersList)){
2165 			for(RoleMemberBo roleMember: newRoleMembersList){
2166 				roleRspActions.addAll(roleMember.getRoleRspActions());
2167 			}
2168 		}
2169 		return roleRspActions;
2170 	}
2171 
2172 	protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(IdentityManagementRoleDocument identityManagementRoleDocument){
2173 		List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2174 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
2175 			for(KimDocumentRoleMember roleMember: identityManagementRoleDocument.getMembers()){
2176 				for(KimDocumentRoleResponsibilityAction roleRspAction : roleMember.getRoleRspActions()){
2177 					RoleResponsibilityActionBo entRoleRspAction = new RoleResponsibilityActionBo();
2178 					entRoleRspAction.setId(roleRspAction.getRoleResponsibilityActionId());
2179 					entRoleRspAction.setActionPolicyCode(roleRspAction.getActionPolicyCode());
2180 					entRoleRspAction.setActionTypeCode(roleRspAction.getActionTypeCode());
2181 					entRoleRspAction.setPriorityNumber(roleRspAction.getPriorityNumber());
2182 					entRoleRspAction.setRoleMemberId(roleRspAction.getRoleMemberId());
2183 					entRoleRspAction.setForceAction(roleRspAction.isForceAction());
2184 					entRoleRspAction.setRoleResponsibilityId(roleRspAction.getRoleResponsibilityId());
2185 					List<RoleResponsibilityActionBo> actions = getRoleRspActions(roleMember.getRoleMemberId());
2186 					if(ObjectUtils.isNotNull(actions)){
2187 						for(RoleResponsibilityActionBo orgRspAction : actions) {
2188 							if (orgRspAction.getId()!=null && StringUtils.equals(orgRspAction.getId(), roleRspAction.getRoleResponsibilityActionId())) {
2189 								entRoleRspAction.setVersionNumber(orgRspAction.getVersionNumber());
2190 							}
2191 						}
2192 					}
2193 					roleRspActions.add(entRoleRspAction);
2194 				}
2195 			}
2196 		}
2197 		return roleRspActions;
2198 	}
2199 
2200     protected List<RoleMemberBo> getRoleMembers(IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleMemberBo> origRoleMembers){
2201         List<RoleMemberBo> roleMembers = new ArrayList<RoleMemberBo>();
2202         RoleMemberBo newRoleMember;
2203         RoleMemberBo origRoleMemberImplTemp;
2204         List<RoleMemberAttributeDataBo> origAttributes;
2205         boolean activatingInactive = false;
2206         String newRoleMemberIdAssigned = "";
2207 
2208         identityManagementRoleDocument.setKimType(KimApiServiceLocator.getKimTypeInfoService().getKimType(identityManagementRoleDocument.getRoleTypeId()));
2209         KimTypeService kimTypeService = KIMServiceLocatorWeb.getKimTypeService(identityManagementRoleDocument.getKimType());
2210 
2211         if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
2212             for(KimDocumentRoleMember documentRoleMember: identityManagementRoleDocument.getMembers()){
2213                 origRoleMemberImplTemp = null;
2214 
2215                 newRoleMember = new RoleMemberBo();
2216                 KimCommonUtilsInternal.copyProperties(newRoleMember, documentRoleMember);
2217                 newRoleMember.setRoleId(identityManagementRoleDocument.getRoleId());
2218                 if(ObjectUtils.isNotNull(origRoleMembers)){
2219                     for(RoleMemberBo origRoleMemberImpl: origRoleMembers){
2220                         if((origRoleMemberImpl.getRoleId()!=null && StringUtils.equals(origRoleMemberImpl.getRoleId(), newRoleMember.getRoleId())) &&
2221                             (origRoleMemberImpl.getMemberId()!=null && StringUtils.equals(origRoleMemberImpl.getMemberId(), newRoleMember.getMemberId())) &&
2222                             (origRoleMemberImpl.getMemberTypeCode()!=null && StringUtils.equals(origRoleMemberImpl.getMemberTypeCode(), newRoleMember.getMemberTypeCode())) &&
2223                             !origRoleMemberImpl.isActive(new Timestamp(System.currentTimeMillis())) &&
2224                             !kimTypeService.validateUniqueAttributes(identityManagementRoleDocument.getKimType().getId(),
2225                                     documentRoleMember.getQualifierAsMap(), origRoleMemberImpl.getAttributes())) {
2226 
2227                             //TODO: verify if you want to add  && newRoleMember.isActive() condition to if...
2228 
2229                             newRoleMemberIdAssigned = newRoleMember.getRoleMemberId();
2230                             newRoleMember.setRoleMemberId(origRoleMemberImpl.getRoleMemberId());
2231                             activatingInactive = true;
2232                         }
2233                         if(origRoleMemberImpl.getRoleMemberId()!=null && StringUtils.equals(origRoleMemberImpl.getRoleMemberId(), newRoleMember.getRoleMemberId())){
2234                             newRoleMember.setVersionNumber(origRoleMemberImpl.getVersionNumber());
2235                             origRoleMemberImplTemp = origRoleMemberImpl;
2236                         }
2237                     }
2238                 }
2239                 origAttributes = (origRoleMemberImplTemp==null || origRoleMemberImplTemp.getAttributes()==null)?
2240                                     new ArrayList<RoleMemberAttributeDataBo>():origRoleMemberImplTemp.getAttributeDetails();
2241                 newRoleMember.setAttributeDetails(getRoleMemberAttributeData(documentRoleMember.getQualifiers(), origAttributes, activatingInactive, newRoleMemberIdAssigned));
2242                 newRoleMember.setRoleRspActions(getRoleMemberResponsibilityActions(documentRoleMember, origRoleMemberImplTemp, activatingInactive, newRoleMemberIdAssigned));
2243                 roleMembers.add(newRoleMember);
2244                 activatingInactive = false;
2245             }
2246         }
2247         return roleMembers;
2248     }
2249 
2250 	protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(
2251 			KimDocumentRoleMember documentRoleMember, RoleMemberBo origRoleMemberImplTemp, boolean activatingInactive, String newRoleMemberIdAssigned){
2252 		List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2253 		List<RoleResponsibilityActionBo> origActions = new ArrayList<RoleResponsibilityActionBo>();
2254 		if(origRoleMemberImplTemp!=null) {
2255 			origActions = getRoleRspActions(origRoleMemberImplTemp.getRoleMemberId());
2256 		}
2257 		if(CollectionUtils.isNotEmpty(documentRoleMember.getRoleRspActions())){
2258 			for(KimDocumentRoleResponsibilityAction roleRspAction : documentRoleMember.getRoleRspActions()){
2259 				RoleResponsibilityActionBo newRoleRspAction = new RoleResponsibilityActionBo();
2260 				newRoleRspAction.setId(roleRspAction.getRoleResponsibilityActionId());
2261 				newRoleRspAction.setActionPolicyCode(roleRspAction.getActionPolicyCode());
2262 				newRoleRspAction.setActionTypeCode(roleRspAction.getActionTypeCode());
2263 				newRoleRspAction.setPriorityNumber(roleRspAction.getPriorityNumber());
2264 				newRoleRspAction.setRoleMemberId(roleRspAction.getRoleMemberId());
2265 				newRoleRspAction.setForceAction(roleRspAction.isForceAction());
2266 				newRoleRspAction.setRoleResponsibilityId("*");
2267 				if(ObjectUtils.isNotNull(origActions)){
2268 					for(RoleResponsibilityActionBo origRspAction: origActions) {
2269 						if(activatingInactive && StringUtils.equals(origRspAction.getRoleResponsibilityId(), newRoleRspAction.getRoleResponsibilityId()) &&
2270 								StringUtils.equals(newRoleRspAction.getRoleMemberId(), newRoleMemberIdAssigned)){
2271 							newRoleRspAction.setRoleMemberId(origRspAction.getRoleMemberId());
2272 							newRoleRspAction.setId(origRspAction.getId());
2273 						}
2274 						if (origRspAction.getId()!=null && StringUtils.equals(origRspAction.getId(), newRoleRspAction.getId())) {
2275 							newRoleRspAction.setVersionNumber(origRspAction.getVersionNumber());
2276 						}
2277 					}
2278 				}
2279 				roleRspActions.add(newRoleRspAction);
2280 			}
2281 		}
2282 		return roleRspActions;
2283 	}
2284 
2285 	protected List<RoleMemberAttributeDataBo> getRoleMemberAttributeData(List<KimDocumentRoleQualifier> qualifiers,
2286 			List<RoleMemberAttributeDataBo> origAttributes, boolean activatingInactive, String newRoleMemberIdAssigned){
2287 		List<RoleMemberAttributeDataBo> roleMemberAttributeDataList = new ArrayList<RoleMemberAttributeDataBo>();
2288 		RoleMemberAttributeDataBo newRoleMemberAttributeData;
2289 		if(CollectionUtils.isNotEmpty(qualifiers)){
2290 			for(KimDocumentRoleQualifier memberRoleQualifier: qualifiers){
2291 				if(StringUtils.isNotBlank(memberRoleQualifier.getAttrVal())){
2292 					newRoleMemberAttributeData = new RoleMemberAttributeDataBo();
2293 					newRoleMemberAttributeData.setId(memberRoleQualifier.getAttrDataId());
2294 					newRoleMemberAttributeData.setAttributeValue(memberRoleQualifier.getAttrVal());
2295 					newRoleMemberAttributeData.setAssignedToId(memberRoleQualifier.getRoleMemberId());
2296 					newRoleMemberAttributeData.setKimTypeId(memberRoleQualifier.getKimTypId());
2297 					newRoleMemberAttributeData.setKimAttributeId(memberRoleQualifier.getKimAttrDefnId());
2298 
2299 					updateAttrValIfNecessary(newRoleMemberAttributeData);
2300 
2301 					if(ObjectUtils.isNotNull(origAttributes)){
2302 						for(RoleMemberAttributeDataBo origAttribute: origAttributes){
2303 							if(activatingInactive && StringUtils.equals(origAttribute.getKimAttributeId(), newRoleMemberAttributeData.getKimAttributeId()) &&
2304 									StringUtils.equals(newRoleMemberAttributeData.getAssignedToId(), newRoleMemberIdAssigned)){
2305 								newRoleMemberAttributeData.setAssignedToId(origAttribute.getAssignedToId());
2306 								newRoleMemberAttributeData.setId(origAttribute.getId());
2307 							}
2308 							if(origAttribute.getId()!=null && StringUtils.equals(origAttribute.getId(), newRoleMemberAttributeData.getId())){
2309 								newRoleMemberAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2310 							}
2311 						}
2312 					}
2313 					roleMemberAttributeDataList.add(newRoleMemberAttributeData);
2314 				}
2315 			}
2316 		}
2317 		return roleMemberAttributeDataList;
2318 	}
2319 
2320 	/**
2321 	 * Determines if the attribute value on the attribute data should be updated; if so, it performs some attribute value formatting.
2322 	 * In the default implementation, this method formats checkbox controls
2323 	 *
2324 	 * @param roleMemberAttributeData a role member qualifier attribute to update
2325 	 */
2326 	protected void updateAttrValIfNecessary(RoleMemberAttributeDataBo roleMemberAttributeData) {
2327 		final AttributeDefinition attributeDefinition = getAttributeDefinition(roleMemberAttributeData.getKimTypeId(),
2328                 roleMemberAttributeData.getKimAttributeId());
2329 		if (attributeDefinition != null) {
2330 			if (attributeDefinition.getControl() != null && attributeDefinition.getControl().isCheckbox()) {
2331 				convertCheckboxAttributeData(roleMemberAttributeData);
2332 			}
2333 		}
2334 	}
2335 
2336 	protected void formatAttrValIfNecessary(KimDocumentRoleQualifier roleQualifier) {
2337 		final AttributeDefinition attributeDefinition = getAttributeDefinition(roleQualifier.getKimTypId(),
2338                 roleQualifier.getKimAttrDefnId());
2339 		if (attributeDefinition != null) {
2340 			if (attributeDefinition.getControl() != null && attributeDefinition.getControl().isCheckbox()) {
2341 				formatCheckboxAttributeData(roleQualifier);
2342 			}
2343 		}
2344 	}
2345 
2346 	protected void formatCheckboxAttributeData(KimDocumentRoleQualifier roleQualifier) {
2347 		if (roleQualifier.getAttrVal().equals(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE)) {
2348 			roleQualifier.setAttrVal(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY);
2349 		} else if (roleQualifier.getAttrVal().equals(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE)) {
2350 			roleQualifier.setAttrVal(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY);
2351 		}
2352 	}
2353 
2354 	/**
2355 	 * Finds the KNS attribute used to render the given KimAttributeData
2356 	 *
2357      * @return the KNS attribute used to render that qualifier, or null if the AttributeDefinition cannot be determined
2358 	 */
2359 	protected AttributeDefinition getAttributeDefinition(String kimTypId, String attrDefnId) {
2360 		final KimType type = getKimTypeInfoService().getKimType(kimTypId);
2361 		if (type != null) {
2362 			final KimTypeService typeService = (KimTypeService) KIMServiceLocatorInternal.getBean(type.getServiceName());
2363 			if (typeService != null) {
2364 				final KimTypeAttribute attributeInfo = type.getAttributeDefinitionById(attrDefnId);
2365 				if (attributeInfo != null) {
2366 					final AttributeDefinitionMap attributeMap = typeService.getAttributeDefinitions(type.getId());
2367 					if (attributeMap != null) {
2368 						return attributeMap.getByAttributeName(attributeInfo.getKimAttribute().getAttributeName());
2369 					}
2370 				}
2371 			}
2372 		}
2373 		return null;
2374 	}
2375 
2376 	/**
2377 	 * Formats the attribute value on this checkbox attribute, changing "on" to "Y" and "off" to "N"
2378 	 *
2379 	 * @param roleMemberAttributeData the attribute data to format the attribute value of
2380 	 */
2381 	protected void convertCheckboxAttributeData(RoleMemberAttributeDataBo roleMemberAttributeData) {
2382 		if (roleMemberAttributeData.getAttributeValue().equalsIgnoreCase(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY)) {
2383 			roleMemberAttributeData.setAttributeValue(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE);
2384 		} else if (roleMemberAttributeData.getAttributeValue().equalsIgnoreCase(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY)) {
2385 			roleMemberAttributeData.setAttributeValue(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE);
2386 		}
2387 	}
2388 
2389 	protected List<DelegateBo> getRoleDelegations(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateBo> origDelegations){
2390 		List<DelegateBo> kimDelegations = new ArrayList<DelegateBo>();
2391 		DelegateBo newKimDelegation;
2392 		DelegateBo origDelegationImplTemp = null;
2393 		List<DelegateMemberBo> origMembers;
2394 		boolean activatingInactive = false;
2395 		String newDelegationIdAssigned = "";
2396 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getDelegations())){
2397 			for(RoleDocumentDelegation roleDocumentDelegation: identityManagementRoleDocument.getDelegations()){
2398 				newKimDelegation = new DelegateBo();
2399 				KimCommonUtilsInternal.copyProperties(newKimDelegation, roleDocumentDelegation);
2400 				newKimDelegation.setRoleId(identityManagementRoleDocument.getRoleId());
2401 				if(ObjectUtils.isNotNull(origDelegations)){
2402 					for(DelegateBo origDelegationImpl: origDelegations){
2403 						if(StringUtils.equals(origDelegationImpl.getRoleId(), newKimDelegation.getRoleId()) &&
2404 								StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId())){
2405 							//TODO: verify if you want to add  && newRoleMember.isActive() condition to if...
2406 							newDelegationIdAssigned = newKimDelegation.getDelegationId();
2407 							newKimDelegation.setDelegationId(origDelegationImpl.getDelegationId());
2408 							activatingInactive = true;
2409 						}
2410 						if(origDelegationImpl.getDelegationId()!=null && StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId())){
2411 							newKimDelegation.setVersionNumber(origDelegationImpl.getVersionNumber());
2412 							origDelegationImplTemp = origDelegationImpl;
2413 						}
2414 					}
2415 				}
2416 				origMembers = (origDelegationImplTemp == null || origDelegationImplTemp.getMembers()==null)?
2417 									new ArrayList<DelegateMemberBo>():origDelegationImplTemp.getMembers();
2418 				newKimDelegation.setMembers(getDelegationMembers(roleDocumentDelegation.getMembers(), origMembers, activatingInactive, newDelegationIdAssigned));
2419 				kimDelegations.add(newKimDelegation);
2420 				activatingInactive = false;
2421 			}
2422 		}
2423 		return kimDelegations;
2424 	}
2425 
2426 	protected List<DelegateMemberBo> getDelegationMembers(List<RoleDocumentDelegationMember> delegationMembers,
2427 			List<DelegateMemberBo> origDelegationMembers, boolean activatingInactive, String newDelegationIdAssigned){
2428 		List<DelegateMemberBo> delegationsMembersList = new ArrayList<DelegateMemberBo>();
2429 		DelegateMemberBo newDelegationMemberImpl;
2430 		DelegateMemberBo origDelegationMemberImplTemp = null;
2431 		List<DelegateMemberAttributeDataBo> origAttributes;
2432 		String delegationMemberId = "";
2433 		if(CollectionUtils.isNotEmpty(delegationMembers)){
2434 			for(RoleDocumentDelegationMember delegationMember: delegationMembers){
2435 				newDelegationMemberImpl = new DelegateMemberBo();
2436 				KimCommonUtilsInternal.copyProperties(newDelegationMemberImpl, delegationMember);
2437 				if(ObjectUtils.isNotNull(origDelegationMembers)){
2438 					for(DelegateMemberBo origDelegationMember: origDelegationMembers){
2439 						if(activatingInactive && StringUtils.equals(origDelegationMember.getMemberId(), newDelegationMemberImpl.getMemberId()) &&
2440 								StringUtils.equals(newDelegationMemberImpl.getDelegationId(), newDelegationIdAssigned) &&
2441 								!origDelegationMember.isActive(new Timestamp(System.currentTimeMillis()))){
2442 							newDelegationMemberImpl.setDelegationId(origDelegationMember.getDelegationId());
2443 							delegationMemberId = newDelegationMemberImpl.getDelegationMemberId();
2444 							newDelegationMemberImpl.setDelegationMemberId(origDelegationMember.getDelegationMemberId());
2445 						}
2446 						if(origDelegationMember.getDelegationMemberId()!=null && StringUtils.equals(origDelegationMember.getDelegationMemberId(), newDelegationMemberImpl.getDelegationMemberId())){
2447 							newDelegationMemberImpl.setVersionNumber(origDelegationMember.getVersionNumber());
2448 							origDelegationMemberImplTemp = origDelegationMember;
2449 						}
2450 					}
2451 				}
2452 				origAttributes = (origDelegationMemberImplTemp==null || origDelegationMemberImplTemp.getAttributes()==null)?
2453 						new ArrayList<DelegateMemberAttributeDataBo>():origDelegationMemberImplTemp.getAttributes();
2454 				newDelegationMemberImpl.setAttributes(getDelegationMemberAttributeData(delegationMember.getQualifiers(), origAttributes, activatingInactive, delegationMemberId));
2455 				delegationsMembersList.add(newDelegationMemberImpl);
2456 			}
2457 		}
2458 		return delegationsMembersList;
2459 	}
2460 
2461 	//TODO: implement logic same as role members - do not insert qualifiers with blank values
2462 	protected List<DelegateMemberAttributeDataBo> getDelegationMemberAttributeData(
2463 			List<RoleDocumentDelegationMemberQualifier> qualifiers, List<DelegateMemberAttributeDataBo> origAttributes,
2464 			boolean activatingInactive, String delegationMemberId){
2465 		List<DelegateMemberAttributeDataBo> delegationMemberAttributeDataList = new ArrayList<DelegateMemberAttributeDataBo>();
2466 		DelegateMemberAttributeDataBo newDelegationMemberAttributeData;
2467 		if(CollectionUtils.isNotEmpty(qualifiers)){
2468 			for(RoleDocumentDelegationMemberQualifier memberRoleQualifier: qualifiers){
2469 				if(StringUtils.isNotBlank(memberRoleQualifier.getAttrVal())){
2470 					newDelegationMemberAttributeData = new DelegateMemberAttributeDataBo();
2471 					newDelegationMemberAttributeData.setId(memberRoleQualifier.getAttrDataId());
2472 					newDelegationMemberAttributeData.setAttributeValue(memberRoleQualifier.getAttrVal());
2473 					newDelegationMemberAttributeData.setAssignedToId(memberRoleQualifier.getDelegationMemberId());
2474 					newDelegationMemberAttributeData.setKimTypeId(memberRoleQualifier.getKimTypId());
2475 					newDelegationMemberAttributeData.setKimAttributeId(memberRoleQualifier.getKimAttrDefnId());
2476 					if(ObjectUtils.isNotNull(origAttributes)){
2477 						for(DelegateMemberAttributeDataBo origAttribute: origAttributes){
2478 							if(activatingInactive && StringUtils.equals(origAttribute.getKimAttributeId(), newDelegationMemberAttributeData.getKimAttributeId()) &&
2479 									StringUtils.equals(newDelegationMemberAttributeData.getAssignedToId(), delegationMemberId)){
2480 								newDelegationMemberAttributeData.setAssignedToId(origAttribute.getAssignedToId());
2481 								newDelegationMemberAttributeData.setId(origAttribute.getId());
2482 							}
2483 							if(StringUtils.equals(origAttribute.getId(), newDelegationMemberAttributeData.getId())){
2484 								newDelegationMemberAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2485 							}
2486 						}
2487 					}
2488 					delegationMemberAttributeDataList.add(newDelegationMemberAttributeData);
2489 				}
2490 			}
2491 		}
2492 		return delegationMemberAttributeDataList;
2493 	}
2494 
2495 	/* Group document methods */
2496 	public void loadGroupDoc(IdentityManagementGroupDocument identityManagementGroupDocument, Group groupInfo){
2497 		//Map<String, String> criteria = new HashMap<String, String>();
2498 		//criteria.put(KimConstants.PrimaryKeyConstants.GROUP_ID, groupInfo.getId());
2499 		//GroupImpl kimGroupImpl = (GroupImpl)
2500 		//	getBusinessObjectService().findByPrimaryKey(GroupImpl.class, criteria);
2501 
2502 		identityManagementGroupDocument.setGroupId(groupInfo.getId());
2503         KimType kimType = KimApiServiceLocator.getKimTypeInfoService().getKimType(groupInfo.getKimTypeId());
2504 		identityManagementGroupDocument.setKimType(kimType);
2505 		identityManagementGroupDocument.setGroupTypeName(kimType.getName());
2506 		identityManagementGroupDocument.setGroupTypeId(kimType.getId());
2507 		identityManagementGroupDocument.setGroupName(groupInfo.getName());
2508 		identityManagementGroupDocument.setGroupDescription(groupInfo.getDescription());
2509 		identityManagementGroupDocument.setActive(groupInfo.isActive());
2510 		identityManagementGroupDocument.setGroupNamespace(groupInfo.getNamespaceCode());
2511 
2512         List<GroupMember> members = new ArrayList(KimApiServiceLocator.getGroupService().getMembersOfGroup(groupInfo.getId()));
2513         identityManagementGroupDocument.setMembers(loadGroupMembers(identityManagementGroupDocument, members));
2514 
2515 
2516 
2517         identityManagementGroupDocument.setQualifiers(loadGroupQualifiers(identityManagementGroupDocument, groupInfo.getAttributes()));
2518 		identityManagementGroupDocument.setEditing(true);
2519 	}
2520 
2521 	protected static class GroupMemberNameComparator implements Comparator<GroupDocumentMember> {
2522 		/**
2523 		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
2524 		 */
2525 		public int compare(GroupDocumentMember m1, GroupDocumentMember m2) {
2526 			return m1.getMemberName().compareToIgnoreCase(m2.getMemberName());
2527 		}
2528 	}
2529 
2530 	protected GroupMemberNameComparator groupMemberNameComparator = new GroupMemberNameComparator();
2531 
2532 	protected List<GroupDocumentMember> loadGroupMembers(
2533 			IdentityManagementGroupDocument identityManagementGroupDocument, List<GroupMember> members){
2534 		List<GroupDocumentMember> pndMembers = new ArrayList<GroupDocumentMember>();
2535 		GroupDocumentMember pndMember = new GroupDocumentMember();
2536 		if(ObjectUtils.isNotNull(members)){
2537 			for(GroupMember member: members){
2538 				pndMember = new GroupDocumentMember();
2539 				pndMember.setActiveFromDate(member.getActiveFromDate());
2540 				pndMember.setActiveToDate(member.getActiveToDate());
2541 				//pndMember.setActive(member.isActive());
2542 				if(pndMember.isActive()){
2543 					pndMember.setGroupMemberId(member.getMemberId());
2544 					pndMember.setGroupId(member.getGroupId());
2545 					pndMember.setMemberId(member.getMemberId());
2546 					pndMember.setMemberName(getMemberName(member.getTypeCode(), member.getMemberId()));
2547 					pndMember.setMemberFullName(getMemberFullName(member.getTypeCode(), member.getMemberId()));
2548 					pndMember.setMemberTypeCode(member.getTypeCode());
2549 					pndMember.setEdit(true);
2550 					pndMembers.add(pndMember);
2551 				}
2552 			}
2553 		}
2554 		Collections.sort(pndMembers, groupMemberNameComparator);
2555 		return pndMembers;
2556 	}
2557 
2558 	protected List<GroupDocumentQualifier> loadGroupQualifiers(IdentityManagementGroupDocument IdentityManagementGroupDocument,
2559 			Map<String, String> attributes){
2560 		List<GroupDocumentQualifier> pndGroupQualifiers = new ArrayList<GroupDocumentQualifier>();
2561 		GroupDocumentQualifier pndGroupQualifier = new GroupDocumentQualifier();
2562 		AttributeDefinitionMap origAttributes = IdentityManagementGroupDocument.getDefinitions();
2563 		boolean attributePresent = false;
2564 		String origAttributeId;
2565 		if(origAttributes!=null){
2566 
2567 			for(String key: origAttributes.keySet()) {
2568 				origAttributeId = IdentityManagementGroupDocument.getKimAttributeDefnId(origAttributes.get(key));
2569 				if(!attributes.isEmpty()){
2570 
2571 					for(GroupAttributeBo groupQualifier: KimAttributeDataBo.createFrom(GroupAttributeBo.class, attributes, IdentityManagementGroupDocument.getGroupTypeId())){
2572 						if(origAttributeId!=null && ObjectUtils.isNotNull(groupQualifier.getKimAttribute()) &&
2573 								StringUtils.equals(origAttributeId, groupQualifier.getKimAttribute().getId())){
2574 							pndGroupQualifier = new GroupDocumentQualifier();
2575 							KimCommonUtilsInternal.copyProperties(pndGroupQualifier, groupQualifier);
2576 							pndGroupQualifier.setAttrDataId(groupQualifier.getId());
2577 							pndGroupQualifier.setAttrVal(groupQualifier.getAttributeValue());
2578 							pndGroupQualifier.setKimAttrDefnId(groupQualifier.getKimAttribute().getId());
2579 							pndGroupQualifier.setKimTypId(groupQualifier.getKimType().getId());
2580 							pndGroupQualifier.setGroupId(groupQualifier.getAssignedToId());
2581 							pndGroupQualifiers.add(pndGroupQualifier);
2582 							attributePresent = true;
2583 						}
2584 					}
2585 				}
2586 				if(!attributePresent){
2587 					pndGroupQualifier = new GroupDocumentQualifier();
2588 					pndGroupQualifier.setKimAttrDefnId(origAttributeId);
2589 					pndGroupQualifiers.add(pndGroupQualifier);
2590 				}
2591 				attributePresent = false;
2592 			}
2593 		}
2594 		return pndGroupQualifiers;
2595 	}
2596 
2597 	/**
2598 	 * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
2599 	 */
2600 	@SuppressWarnings("unchecked")
2601 	public void saveGroup(IdentityManagementGroupDocument identityManagementGroupDocument) {
2602 		GroupBo kimGroup = new GroupBo();
2603 		Map<String, String> criteria = new HashMap<String, String>();
2604 		String groupId = identityManagementGroupDocument.getGroupId();
2605 		criteria.put("groupId", groupId);
2606 		GroupBo origGroup = (GroupBo)getBusinessObjectService().findBySinglePrimaryKey(GroupBo.class, groupId);
2607 		List<GroupMemberBo> origGroupMembers = new ArrayList<GroupMemberBo>();
2608 		if (ObjectUtils.isNull(origGroup)) {
2609 			origGroup = new GroupBo();
2610 			kimGroup.setActive(true);
2611 		} else {
2612 			kimGroup.setVersionNumber(origGroup.getVersionNumber());
2613 			//TODO: when a group is inactivated, inactivate the memberships of principals in that group
2614 			//and the memberships of that group in roles
2615 			kimGroup.setActive(identityManagementGroupDocument.isActive());
2616 			origGroupMembers = (List<GroupMemberBo>)getBusinessObjectService().findMatching(GroupMemberBo.class, criteria);
2617 		}
2618 
2619 		kimGroup.setId(identityManagementGroupDocument.getGroupId());
2620 		KimType kimType = getKimTypeInfoService().getKimType(identityManagementGroupDocument.getGroupTypeId());
2621 		if( kimType == null ) {
2622 			throw new RuntimeException("Kim type not found for:"+identityManagementGroupDocument.getGroupTypeId());
2623 		}
2624 
2625 		kimGroup.setKimTypeId(kimType.getId());
2626 		kimGroup.setNamespaceCode(identityManagementGroupDocument.getGroupNamespace());
2627 		kimGroup.setName(identityManagementGroupDocument.getGroupName());
2628 		kimGroup.setDescription(identityManagementGroupDocument.getGroupDescription());
2629 		kimGroup.setAttributeDetails(getGroupAttributeData(identityManagementGroupDocument, origGroup.getAttributeDetails()));
2630 
2631 		List<String> oldIds;
2632 		List<String> newIds;
2633 		oldIds = getGroupService().getMemberPrincipalIds(kimGroup.getId()); // for the actionList update
2634 
2635 
2636 		List<GroupMemberBo> newGroupMembersList = getGroupMembers(identityManagementGroupDocument, origGroupMembers);
2637 		kimGroup.setMembers(newGroupMembersList);  // add the new, complete list to the group
2638 
2639 		kimGroup = (GroupBo)getBusinessObjectService().save(kimGroup);
2640 
2641 		newIds = kimGroup.getMemberPrincipalIds();
2642 		//newIds = getGroupService().getMemberPrincipalIds(kimGroup.getGroupId()); // for the action list update
2643 
2644 		// Do an async update of the action list for the updated groups
2645 		org.kuali.rice.kim.service.KIMServiceLocatorInternal.getGroupInternalService().updateForWorkgroupChange(kimGroup.getId(), oldIds, newIds);
2646 		IdentityManagementNotificationService service = (IdentityManagementNotificationService) KsbApiServiceLocator.getMessageHelper().getServiceAsynchronously(new QName("KIM", "kimIdentityManagementNotificationService"));
2647         service.groupUpdated();
2648 		if(!kimGroup.isActive()){
2649 			// when a group is inactivated, inactivate the memberships of principals in that group
2650 			// and the memberships of that group in roles
2651 			KimApiServiceLocator.getRoleService().groupInactivated(identityManagementGroupDocument.getGroupId());
2652 		}
2653 
2654 	}
2655 
2656 	protected List<GroupMemberBo> getGroupMembers(IdentityManagementGroupDocument identityManagementGroupDocument, List<GroupMemberBo> origGroupMembers){
2657 		List<GroupMemberBo> groupMembers = new ArrayList<GroupMemberBo>();
2658 		GroupMemberBo newGroupMember;
2659 		if(CollectionUtils.isNotEmpty(identityManagementGroupDocument.getMembers())){
2660 			for(GroupDocumentMember documentGroupMember: identityManagementGroupDocument.getMembers()){
2661 				newGroupMember = new GroupMemberBo();
2662 				//KimCommonUtilsInternalInternal.copyProperties(newGroupMember, documentGroupMember);
2663                 //copy properties manually for now until new BO created for DocumentGroupMember
2664 
2665 				newGroupMember.setGroupId(identityManagementGroupDocument.getGroupId());
2666                 newGroupMember.setActiveFromDate(documentGroupMember.getActiveFromDate());
2667                 newGroupMember.setActiveToDate(documentGroupMember.getActiveToDate());
2668                 newGroupMember.setMemberId(documentGroupMember.getMemberId());
2669                 newGroupMember.setTypeCode(documentGroupMember.getMemberTypeCode());
2670 				if(ObjectUtils.isNotNull(origGroupMembers)){
2671 					for(GroupMemberBo origGroupMemberImpl: origGroupMembers){
2672 						if(StringUtils.equals(origGroupMemberImpl.getGroupId(), newGroupMember.getGroupId()) &&
2673 								StringUtils.equals(origGroupMemberImpl.getMemberId(), newGroupMember.getMemberId()) &&
2674 								!origGroupMemberImpl.isActive(new Timestamp(System.currentTimeMillis()))){
2675 							//TODO: verify if you want to add  && newGroupMember.isActive() condition to if...
2676 							newGroupMember.setMemberId(origGroupMemberImpl.getMemberId());
2677 						}
2678                         if(StringUtils.equals(origGroupMemberImpl.getGroupId(), newGroupMember.getGroupId()) &&
2679 								StringUtils.equals(origGroupMemberImpl.getMemberId(), newGroupMember.getMemberId()) &&
2680 								origGroupMemberImpl.isActive(new Timestamp(System.currentTimeMillis()))){
2681 							newGroupMember.setId(origGroupMemberImpl.getId());
2682                             newGroupMember.setVersionNumber(origGroupMemberImpl.getVersionNumber());
2683 						}
2684 					}
2685 				}
2686 				groupMembers.add(newGroupMember);
2687 			}
2688 		}
2689 		return groupMembers;
2690 	}
2691 
2692 	protected List<GroupAttributeBo> getGroupAttributeData(IdentityManagementGroupDocument identityManagementGroupDocument,
2693 			List<GroupAttributeBo> origAttributes){
2694 		List<GroupAttributeBo> groupAttributeDataList = new ArrayList<GroupAttributeBo>();
2695 		GroupAttributeBo newGroupAttributeData;
2696 		if(CollectionUtils.isNotEmpty(identityManagementGroupDocument.getQualifiers())){
2697 			for(GroupDocumentQualifier groupQualifier: identityManagementGroupDocument.getQualifiers()){
2698 				if(StringUtils.isNotBlank(groupQualifier.getAttrVal())){
2699 					newGroupAttributeData = new GroupAttributeBo();
2700 					newGroupAttributeData.setId(groupQualifier.getAttrDataId());
2701 					newGroupAttributeData.setAttributeValue(groupQualifier.getAttrVal());
2702 					newGroupAttributeData.setAssignedToId(groupQualifier.getGroupId());
2703 					newGroupAttributeData.setKimTypeId(groupQualifier.getKimTypId());
2704 					newGroupAttributeData.setKimAttributeId(groupQualifier.getKimAttrDefnId());
2705 					if(ObjectUtils.isNotNull(origAttributes)){
2706 						for(GroupAttributeBo origAttribute: origAttributes){
2707 							if(StringUtils.equals(origAttribute.getKimAttributeId(), newGroupAttributeData.getKimAttributeId()) &&
2708 									StringUtils.equals(newGroupAttributeData.getAssignedToId(), origAttribute.getAssignedToId())){
2709 							    newGroupAttributeData.setId(origAttribute.getId());
2710 							}
2711 							if(origAttribute.getId()!=null && StringUtils.equals(origAttribute.getId(), newGroupAttributeData.getId())){
2712 							    newGroupAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2713 							}
2714 						}
2715 					}
2716 					groupAttributeDataList.add(newGroupAttributeData);
2717 				}
2718 			}
2719 		}
2720 		return groupAttributeDataList;
2721 	}
2722 
2723     @SuppressWarnings("unchecked")
2724 	public KimDocumentRoleMember getKimDocumentRoleMember(String memberTypeCode, String memberId, String roleId){
2725     	if(StringUtils.isEmpty(memberTypeCode) || StringUtils.isEmpty(memberId) || StringUtils.isEmpty(roleId)) {
2726     		return null;
2727         }
2728     	KimDocumentRoleMember documentRoleMember = new KimDocumentRoleMember();
2729     	documentRoleMember.setRoleId(roleId);
2730     	Map<String, String> criteria = new HashMap<String, String>();
2731     	criteria.put("roleId", roleId);
2732     	criteria.put("mbr_id", memberId);
2733 
2734     	List<RoleMemberBo> matchingRoleMembers = (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, criteria);
2735     	if (matchingRoleMembers==null || matchingRoleMembers.size()<1) { return null; }
2736 
2737     	RoleMemberBo roleMemberImpl = matchingRoleMembers.get(0);
2738     	documentRoleMember.setRoleMemberId(roleMemberImpl.getRoleMemberId());
2739     	if(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE.equals(memberTypeCode)){
2740     		Principal principal = getIdentityService().getPrincipal(memberId);
2741     		if (principal != null) {
2742     			documentRoleMember.setMemberId(principal.getPrincipalId());
2743         		documentRoleMember.setMemberName(principal.getPrincipalName());
2744         		documentRoleMember.setMemberTypeCode(KimConstants.KimUIConstants.MEMBER_TYPE_PRINCIPAL_CODE);
2745     		}    		
2746         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE.equals(memberTypeCode)){
2747         	Group group = getGroupService().getGroup(memberId);
2748         	if (group != null) {
2749         		documentRoleMember.setMemberNamespaceCode(group.getNamespaceCode());
2750         		documentRoleMember.setMemberId(group.getId());
2751         		documentRoleMember.setMemberName(group.getName());
2752         		documentRoleMember.setMemberTypeCode(KimConstants.KimUIConstants.MEMBER_TYPE_GROUP_CODE);	
2753         	}
2754         	
2755         } else if(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE.equals(memberTypeCode)){
2756         	Role role = getRoleService().getRole(memberId);
2757         	if (role != null) {
2758         		documentRoleMember.setMemberNamespaceCode(role.getNamespaceCode());
2759         		documentRoleMember.setMemberId(role.getId());
2760         		documentRoleMember.setMemberName(role.getName());
2761         		documentRoleMember.setMemberTypeCode(KimConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE);
2762         	}        	
2763         }
2764     	return documentRoleMember;
2765     }
2766 
2767     protected Set<String> getChangedRoleResponsibilityIds(
2768 			IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleResponsibilityBo> origRoleResponsibilities){
2769 		Set<String> lRet = new HashSet<String>();
2770 		List<String> newResp = new ArrayList<String>();
2771 		List<String> oldResp = new ArrayList<String>();
2772 		if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2773 			for(KimDocumentRoleResponsibility documentRoleResponsibility: identityManagementRoleDocument.getResponsibilities()){
2774 				newResp.add(documentRoleResponsibility.getResponsibilityId());
2775 			}
2776 		}
2777 		if(ObjectUtils.isNotNull(origRoleResponsibilities)){
2778 			for(RoleResponsibilityBo roleRespBo: origRoleResponsibilities){
2779 				oldResp.add(roleRespBo.getResponsibilityId());
2780 			}
2781 		}
2782 		lRet.addAll(newResp);
2783 		lRet.addAll(oldResp);
2784 
2785 		return lRet;
2786 	}
2787 
2788 	public KimTypeInfoService getKimTypeInfoService() {
2789 		if ( kimTypeInfoService == null ) {
2790 			kimTypeInfoService = KimApiServiceLocator.getKimTypeInfoService();
2791 		}
2792 		return kimTypeInfoService;
2793 	}
2794 
2795     public List<KimDocumentRoleMember> getRoleMembers(Map<String,String> fieldValues) {
2796 		List<KimDocumentRoleMember> matchingRoleMembers = new ArrayList<KimDocumentRoleMember>();
2797 		List<RoleMember> matchingRoleMembersTemp = getRoleService().findRoleMembers(fieldValues);
2798 		KimDocumentRoleMember matchingRoleMember;
2799 		BusinessObject roleMemberObject;
2800 		RoleMemberBo roleMemberBo;
2801 		if(CollectionUtils.isNotEmpty(matchingRoleMembersTemp)){
2802 			for(RoleMember roleMember: matchingRoleMembersTemp){
2803 				roleMemberBo = getRoleMember(roleMember.getRoleMemberId());
2804 				roleMemberObject = getMember(roleMemberBo.getMemberTypeCode(), roleMemberBo.getMemberId());
2805 				matchingRoleMember = new KimDocumentRoleMember();
2806 				KimCommonUtilsInternal.copyProperties(matchingRoleMember, roleMemberBo);
2807 				matchingRoleMember.setMemberName(getMemberName(roleMemberBo.getMemberTypeCode(), roleMemberObject));
2808 				matchingRoleMember.setMemberNamespaceCode(getMemberNamespaceCode(roleMemberBo.getMemberTypeCode(), roleMemberObject));
2809 				matchingRoleMember.setQualifiers(getQualifiers(roleMemberBo.getAttributeDetails()));
2810 				matchingRoleMembers.add(matchingRoleMember);
2811 			}
2812 		}
2813 		return matchingRoleMembers;
2814     }
2815 
2816     private List<KimDocumentRoleQualifier> getQualifiers(List<RoleMemberAttributeDataBo> attributes){
2817     	if (attributes==null) {return null;}
2818     	List<KimDocumentRoleQualifier> qualifiers = new ArrayList<KimDocumentRoleQualifier>();
2819     	KimDocumentRoleQualifier qualifier;
2820     	if(ObjectUtils.isNotNull(attributes)){
2821 	    	for(RoleMemberAttributeDataBo attribute: attributes){
2822 		    	qualifier = new KimDocumentRoleQualifier();
2823 				qualifier.setAttrDataId(attribute.getId());
2824 				qualifier.setAttrVal(attribute.getAttributeValue());
2825 				qualifier.setRoleMemberId(attribute.getAssignedToId());
2826 				qualifier.setKimTypId(attribute.getKimTypeId());
2827 				qualifier.setKimAttrDefnId(attribute.getKimAttributeId());
2828 				qualifier.setKimAttribute(attribute.getKimAttribute());
2829 				qualifiers.add(qualifier);
2830 	    	}
2831     	}
2832     	return qualifiers;
2833     }
2834     
2835 	public ResponsibilityInternalService getResponsibilityInternalService() {
2836 		if ( responsibilityInternalService == null ) {
2837 				responsibilityInternalService = KIMServiceLocatorInternal.getResponsibilityInternalService();
2838 		}
2839 		return responsibilityInternalService;
2840 	}
2841 
2842    public PermissionService getPermissionService() {
2843 		if ( permissionService == null ) {
2844 				permissionService = KimApiServiceLocator.getPermissionService();
2845 		}
2846 		return permissionService;
2847 	}
2848 
2849     public ParameterService getParameterService() {
2850     	if ( parameterService == null ) {
2851     		parameterService = CoreFrameworkServiceLocator.getParameterService();
2852     	}
2853     	return parameterService;
2854     }
2855 
2856     public void setParameterService(ParameterService parameterService) {
2857     	this.parameterService = parameterService;
2858     }
2859 }