View Javadoc

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