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