View Javadoc

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