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