001    /**
002     * Copyright 2005-2012 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.joda.time.DateTime;
022    import org.kuali.rice.core.api.config.property.ConfigContext;
023    import org.kuali.rice.core.api.criteria.Predicate;
024    import org.kuali.rice.core.api.criteria.PredicateUtils;
025    import org.kuali.rice.core.api.criteria.QueryByCriteria;
026    import org.kuali.rice.core.api.membership.MemberType;
027    import org.kuali.rice.coreservice.api.parameter.Parameter;
028    import org.kuali.rice.core.api.uif.RemotableCheckbox;
029    import org.kuali.rice.core.api.uif.RemotableCheckboxGroup;
030    import org.kuali.rice.coreservice.framework.parameter.ParameterService;
031    import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
032    import org.kuali.rice.kim.api.KimConstants;
033    import org.kuali.rice.kim.api.KimConstants.KimGroupMemberTypes;
034    import org.kuali.rice.kim.api.group.Group;
035    import org.kuali.rice.kim.api.group.GroupMember;
036    import org.kuali.rice.kim.api.group.GroupService;
037    import org.kuali.rice.kim.api.identity.IdentityService;
038    import org.kuali.rice.kim.api.identity.Person;
039    import org.kuali.rice.kim.api.identity.address.EntityAddress;
040    import org.kuali.rice.kim.api.identity.address.EntityAddressContract;
041    import org.kuali.rice.kim.api.identity.affiliation.EntityAffiliation;
042    import org.kuali.rice.kim.api.identity.email.EntityEmail;
043    import org.kuali.rice.kim.api.identity.email.EntityEmailContract;
044    import org.kuali.rice.kim.api.identity.employment.EntityEmployment;
045    import org.kuali.rice.kim.api.identity.entity.Entity;
046    import org.kuali.rice.kim.api.identity.name.EntityName;
047    import org.kuali.rice.kim.api.identity.phone.EntityPhone;
048    import org.kuali.rice.kim.api.identity.phone.EntityPhoneContract;
049    import org.kuali.rice.kim.api.identity.principal.Principal;
050    import org.kuali.rice.kim.api.identity.privacy.EntityPrivacyPreferences;
051    import org.kuali.rice.kim.api.identity.type.EntityTypeContactInfo;
052    import org.kuali.rice.kim.api.permission.PermissionService;
053    import org.kuali.rice.kim.api.responsibility.ResponsibilityService;
054    import org.kuali.rice.kim.api.role.Role;
055    import org.kuali.rice.kim.api.role.RoleMember;
056    import org.kuali.rice.kim.api.role.RoleService;
057    import org.kuali.rice.kim.api.services.KimApiServiceLocator;
058    import org.kuali.rice.kim.api.type.KimAttributeField;
059    import org.kuali.rice.kim.api.type.KimType;
060    import org.kuali.rice.kim.api.type.KimTypeAttribute;
061    import org.kuali.rice.kim.api.type.KimTypeInfoService;
062    import org.kuali.rice.kim.bo.ui.GroupDocumentMember;
063    import org.kuali.rice.kim.bo.ui.GroupDocumentQualifier;
064    import org.kuali.rice.kim.bo.ui.KimDocumentRoleMember;
065    import org.kuali.rice.kim.bo.ui.KimDocumentRolePermission;
066    import org.kuali.rice.kim.bo.ui.KimDocumentRoleQualifier;
067    import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibility;
068    import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibilityAction;
069    import org.kuali.rice.kim.bo.ui.PersonDocumentAddress;
070    import org.kuali.rice.kim.bo.ui.PersonDocumentAffiliation;
071    import org.kuali.rice.kim.bo.ui.PersonDocumentEmail;
072    import org.kuali.rice.kim.bo.ui.PersonDocumentEmploymentInfo;
073    import org.kuali.rice.kim.bo.ui.PersonDocumentGroup;
074    import org.kuali.rice.kim.bo.ui.PersonDocumentName;
075    import org.kuali.rice.kim.bo.ui.PersonDocumentPhone;
076    import org.kuali.rice.kim.bo.ui.PersonDocumentPrivacy;
077    import org.kuali.rice.kim.bo.ui.PersonDocumentRole;
078    import org.kuali.rice.kim.bo.ui.RoleDocumentDelegation;
079    import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMember;
080    import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMemberQualifier;
081    import org.kuali.rice.kim.document.IdentityManagementGroupDocument;
082    import org.kuali.rice.kim.document.IdentityManagementPersonDocument;
083    import org.kuali.rice.kim.document.IdentityManagementRoleDocument;
084    import org.kuali.rice.kim.framework.services.KimFrameworkServiceLocator;
085    import org.kuali.rice.kim.framework.type.KimTypeService;
086    import org.kuali.rice.kim.impl.KIMPropertyConstants;
087    import org.kuali.rice.kim.impl.common.attribute.KimAttributeDataBo;
088    import org.kuali.rice.kim.impl.common.delegate.DelegateTypeBo;
089    import org.kuali.rice.kim.impl.common.delegate.DelegateMemberAttributeDataBo;
090    import org.kuali.rice.kim.impl.common.delegate.DelegateMemberBo;
091    import org.kuali.rice.kim.impl.group.GroupAttributeBo;
092    import org.kuali.rice.kim.impl.group.GroupBo;
093    import org.kuali.rice.kim.impl.group.GroupMemberBo;
094    import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
095    import org.kuali.rice.kim.impl.identity.address.EntityAddressTypeBo;
096    import org.kuali.rice.kim.impl.identity.affiliation.EntityAffiliationBo;
097    import org.kuali.rice.kim.impl.identity.affiliation.EntityAffiliationTypeBo;
098    import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
099    import org.kuali.rice.kim.impl.identity.email.EntityEmailTypeBo;
100    import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentBo;
101    import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentStatusBo;
102    import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentTypeBo;
103    import org.kuali.rice.kim.impl.identity.entity.EntityBo;
104    import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
105    import org.kuali.rice.kim.impl.identity.name.EntityNameTypeBo;
106    import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
107    import org.kuali.rice.kim.impl.identity.phone.EntityPhoneTypeBo;
108    import org.kuali.rice.kim.impl.identity.principal.PrincipalBo;
109    import org.kuali.rice.kim.impl.identity.privacy.EntityPrivacyPreferencesBo;
110    import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
111    import org.kuali.rice.kim.impl.permission.PermissionBo;
112    import org.kuali.rice.kim.impl.responsibility.ResponsibilityInternalService;
113    import org.kuali.rice.kim.impl.role.RoleBo;
114    import org.kuali.rice.kim.impl.role.RoleMemberAttributeDataBo;
115    import org.kuali.rice.kim.impl.role.RoleMemberBo;
116    import org.kuali.rice.kim.impl.role.RolePermissionBo;
117    import org.kuali.rice.kim.impl.role.RoleResponsibilityActionBo;
118    import org.kuali.rice.kim.impl.role.RoleResponsibilityBo;
119    import org.kuali.rice.kim.impl.services.KimImplServiceLocator;
120    import org.kuali.rice.kim.impl.type.KimTypeBo;
121    import org.kuali.rice.kim.service.UiDocumentService;
122    import org.kuali.rice.kim.util.KimCommonUtilsInternal;
123    import org.kuali.rice.kns.datadictionary.exporter.AttributesMapBuilder;
124    import org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceHelper;
125    import org.kuali.rice.kns.service.DocumentHelperService;
126    import org.kuali.rice.kns.service.KNSServiceLocator;
127    import org.kuali.rice.krad.bo.BusinessObject;
128    import org.kuali.rice.krad.bo.PersistableBusinessObject;
129    import org.kuali.rice.krad.datadictionary.AttributeDefinition;
130    import org.kuali.rice.krad.datadictionary.exporter.ExportMap;
131    import org.kuali.rice.krad.document.Document;
132    import org.kuali.rice.krad.service.BusinessObjectService;
133    import org.kuali.rice.krad.service.KRADServiceLocator;
134    import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
135    import org.kuali.rice.krad.util.KRADConstants;
136    import org.kuali.rice.krad.util.ObjectUtils;
137    
138    import java.sql.Timestamp;
139    import java.util.ArrayList;
140    import java.util.Collection;
141    import java.util.Collections;
142    import java.util.Comparator;
143    import java.util.HashMap;
144    import java.util.HashSet;
145    import java.util.List;
146    import java.util.Map;
147    import java.util.Set;
148    
149    /**
150     * This is a description of what this class does - shyu don't forget to fill this in.
151     *
152     * @author Kuali Rice Team (rice.collab@kuali.org)
153     *
154     */
155    public class UiDocumentServiceImpl implements UiDocumentService {
156            private static final Logger LOG = Logger.getLogger(UiDocumentServiceImpl.class);
157            private static final String SHOW_BLANK_QUALIFIERS = "kim.show.blank.qualifiers";
158            
159            private RoleService roleService;
160            private BusinessObjectService businessObjectService;
161            private IdentityService identityService;
162        private PermissionService permissionService;
163            private GroupService groupService;
164            private ResponsibilityService responsibilityService;
165        private ResponsibilityInternalService responsibilityInternalService;
166            private KimTypeInfoService kimTypeInfoService;
167        private DocumentHelperService documentHelperService;
168        private ParameterService parameterService;
169    
170    
171            /**
172             * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
173             */
174            public void saveEntityPerson(
175                IdentityManagementPersonDocument identityManagementPersonDocument) {
176                    EntityBo kimEntity = new EntityBo();
177                    EntityBo origEntity = getEntityBo(identityManagementPersonDocument.getEntityId());
178                    boolean creatingNew = true;
179                    if (origEntity == null) {
180                            origEntity = new EntityBo();
181                            kimEntity.setActive(true);
182                    } else {
183                            // TODO : in order to resolve optimistic locking issue. has to get identity and set the version number if identity records matched
184                            // Need to look into this.
185                            //kimEntity = origEntity;
186                            kimEntity.setActive(origEntity.isActive());
187                            kimEntity.setVersionNumber(origEntity.getVersionNumber());
188                            creatingNew = false;
189                    }
190    
191                    kimEntity.setId(identityManagementPersonDocument.getEntityId());
192                    String initiatorPrincipalId = getInitiatorPrincipalId(identityManagementPersonDocument);
193                    boolean inactivatingPrincipal = false;
194                    if(canModifyEntity(initiatorPrincipalId, identityManagementPersonDocument.getPrincipalId())){
195                            inactivatingPrincipal = setupPrincipal(identityManagementPersonDocument, kimEntity, origEntity.getPrincipals());
196                            setupAffiliation(identityManagementPersonDocument, kimEntity, origEntity.getAffiliations(), origEntity.getEmploymentInformation());
197                            setupName(identityManagementPersonDocument, kimEntity, origEntity.getNames());
198                    // entitytype
199                            List<EntityTypeContactInfoBo> entityTypes = new ArrayList<EntityTypeContactInfoBo>();
200                            EntityTypeContactInfoBo entityType = new EntityTypeContactInfoBo();
201                            entityType.setEntityId(identityManagementPersonDocument.getEntityId());
202                            entityType.setEntityTypeCode(KimConstants.EntityTypes.PERSON);
203                            entityType.setActive(true);
204                            entityTypes.add(entityType);
205                            EntityTypeContactInfoBo origEntityType = new EntityTypeContactInfoBo();
206                            for (EntityTypeContactInfoBo type : origEntity.getEntityTypeContactInfos()) {
207                                    // should check identity.entitytypeid, but it's not persist in persondoc yet
208                                    if (type.getEntityTypeCode()!=null && StringUtils.equals(type.getEntityTypeCode(), entityType.getEntityTypeCode())) {
209                                            origEntityType = type;
210                                            entityType.setVersionNumber(type.getVersionNumber());
211                                            entityType.setActive(type.isActive());
212                                    }
213                            }
214                            setupPhone(identityManagementPersonDocument, entityType, origEntityType.getPhoneNumbers());
215                            setupEmail(identityManagementPersonDocument, entityType, origEntityType.getEmailAddresses());
216                            setupAddress(identityManagementPersonDocument, entityType, origEntityType.getAddresses());
217                kimEntity.setEntityTypeContactInfos(entityTypes);
218                    } else{
219                            if(ObjectUtils.isNotNull(origEntity.getExternalIdentifiers())) {
220                    kimEntity.setExternalIdentifiers(origEntity.getExternalIdentifiers());
221                }
222                            if(ObjectUtils.isNotNull(origEntity.getEmploymentInformation())) {
223                    kimEntity.setEmploymentInformation(origEntity.getEmploymentInformation());
224                }
225                            if(ObjectUtils.isNotNull(origEntity.getAffiliations())) {
226                    kimEntity.setAffiliations(origEntity.getAffiliations());
227                }
228                            if(ObjectUtils.isNotNull(origEntity.getNames())) {
229                    kimEntity.setNames(origEntity.getNames());
230                }
231                            if(ObjectUtils.isNotNull(origEntity.getEntityTypeContactInfos())) {
232                    kimEntity.setEntityTypeContactInfos(origEntity.getEntityTypeContactInfos());
233                }
234                    }
235                    if(creatingNew || canOverrideEntityPrivacyPreferences(getInitiatorPrincipalId(identityManagementPersonDocument), identityManagementPersonDocument.getPrincipalId())) {
236                            setupPrivacy(identityManagementPersonDocument, kimEntity, origEntity.getPrivacyPreferences());
237                    } else {
238                            if(ObjectUtils.isNotNull(origEntity.getPrivacyPreferences())) {
239                                    kimEntity.setPrivacyPreferences(origEntity.getPrivacyPreferences());
240                            }
241                    }
242                    List <GroupMemberBo>  groupPrincipals = populateGroupMembers(identityManagementPersonDocument);
243                    List <RoleMemberBo>  rolePrincipals = populateRoleMembers(identityManagementPersonDocument);
244                    List <DelegateTypeBo> personDelegations = populateDelegations(identityManagementPersonDocument);
245                    List <PersistableBusinessObject> bos = new ArrayList<PersistableBusinessObject>();
246                    List <RoleResponsibilityActionBo> roleRspActions = populateRoleRspActions(identityManagementPersonDocument);
247                    List <RoleMemberAttributeDataBo> blankRoleMemberAttrs = getBlankRoleMemberAttrs(rolePrincipals);
248                    bos.add(kimEntity);
249                    //if(ObjectUtils.isNotNull(kimEntity.getPrivacyPreferences()))
250                    //      bos.add(kimEntity.getPrivacyPreferences());
251                    bos.addAll(groupPrincipals);
252                    bos.addAll(rolePrincipals);
253                    bos.addAll(roleRspActions);
254                    bos.addAll(personDelegations);
255                    // boservice.save(bos) does not handle deleteawarelist
256                    getBusinessObjectService().save(bos);
257    
258                    if (!blankRoleMemberAttrs.isEmpty()) {
259                            getBusinessObjectService().delete(blankRoleMemberAttrs);
260                    }
261                    if ( inactivatingPrincipal ) {
262                            //when a person is inactivated, inactivate their group, role, and delegation memberships
263                            KimImplServiceLocator.getRoleInternalService().principalInactivated(
264                        identityManagementPersonDocument.getPrincipalId());
265                    }
266            }
267    
268            private String getInitiatorPrincipalId(Document document){
269                    try{
270                            return document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
271                    } catch(Exception ex){
272                            return null;
273                    }
274            }
275    
276            public Map<String,Object> getAttributeEntries( List<KimAttributeField> definitions ) {
277                    final Map<String,Object> attributeEntries = new HashMap<String,Object>();
278                    if (definitions != null) {
279                    for (AttributeDefinition definition : DataDictionaryTypeServiceHelper.toKimAttributeDefinitions(definitions)) {
280                                    final AttributesMapBuilder builder = new AttributesMapBuilder();
281                    final ExportMap map = builder.buildAttributeMap(definition, "");
282                    attributeEntries.put(definition.getName(),map.getExportData());
283                            }
284                    }
285            return attributeEntries;
286            }
287    
288    
289            /**
290             *
291             * @see org.kuali.rice.kim.service.UiDocumentService#loadEntityToPersonDoc(IdentityManagementPersonDocument, String)
292             */
293            public void loadEntityToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument, String principalId) {
294                    Principal principal = this.getIdentityService().getPrincipal(principalId);
295            if(principal==null) {
296                    throw new RuntimeException("Principal does not exist for principal id:"+principalId);
297            }
298    
299            identityManagementPersonDocument.setPrincipalId(principal.getPrincipalId());
300            identityManagementPersonDocument.setPrincipalName(principal.getPrincipalName());
301            //identityManagementPersonDocument.setPassword(principal.getPassword());
302            identityManagementPersonDocument.setActive(principal.isActive());
303            Entity kimEntity = this.getIdentityService().getEntity(principal.getEntityId());
304                    identityManagementPersonDocument.setEntityId(kimEntity.getId());
305                    if ( ObjectUtils.isNotNull( kimEntity.getPrivacyPreferences() ) ) {
306                            identityManagementPersonDocument.setPrivacy(loadPrivacyReferences(kimEntity.getPrivacyPreferences()));
307                    }
308                    //identityManagementPersonDocument.setActive(kimEntity.isActive());
309                    identityManagementPersonDocument.setAffiliations(loadAffiliations(kimEntity.getAffiliations(),kimEntity.getEmploymentInformation()));
310                    identityManagementPersonDocument.setNames(loadNames( identityManagementPersonDocument, principalId, kimEntity.getNames(), identityManagementPersonDocument.getPrivacy().isSuppressName() ));
311                    EntityTypeContactInfo entityType = null;
312                    for (EntityTypeContactInfo type : kimEntity.getEntityTypeContactInfos()) {
313                            if (KimConstants.EntityTypes.PERSON.equals(type.getEntityTypeCode())) {
314                                    entityType = EntityTypeContactInfo.Builder.create(type).build();
315                            }
316                    }
317    
318                    if(entityType!=null){
319                            identityManagementPersonDocument.setEmails(loadEmails(identityManagementPersonDocument, principalId, entityType.getEmailAddresses(), identityManagementPersonDocument.getPrivacy().isSuppressEmail()));
320                            identityManagementPersonDocument.setPhones(loadPhones(identityManagementPersonDocument, principalId, entityType.getPhoneNumbers(), identityManagementPersonDocument.getPrivacy().isSuppressPhone()));
321                            identityManagementPersonDocument.setAddrs(loadAddresses(identityManagementPersonDocument, principalId, entityType.getAddresses(), identityManagementPersonDocument.getPrivacy().isSuppressAddress()));
322                    }
323    
324                    List<Group> groups = getGroupService().getGroups(getGroupService().getDirectGroupIdsByPrincipalId(
325                    identityManagementPersonDocument.getPrincipalId()));
326                    loadGroupToPersonDoc(identityManagementPersonDocument, groups);
327                    loadRoleToPersonDoc(identityManagementPersonDocument);
328                    loadDelegationsToPersonDoc(identityManagementPersonDocument);
329            }
330    
331        @SuppressWarnings("unchecked")
332            public List<DelegateTypeBo> getPersonDelegations(String principalId){
333                    if(principalId==null) {
334                            return new ArrayList<DelegateTypeBo>();
335            }
336                    Map<String,String> criteria = new HashMap<String,String>(1);
337                    criteria.put(KimConstants.PrimaryKeyConstants.MEMBER_ID, principalId);
338                    criteria.put( KIMPropertyConstants.DelegationMember.MEMBER_TYPE_CODE, MemberType.PRINCIPAL.getCode() );
339                    List<DelegateMemberBo> delegationMembers = (List<DelegateMemberBo>)getBusinessObjectService().findMatching(DelegateMemberBo.class, criteria);
340                    List<DelegateTypeBo> delegations = new ArrayList<DelegateTypeBo>();
341                    List<String> delegationIds = new ArrayList<String>();
342                    if(ObjectUtils.isNotNull(delegationMembers)){
343                            for(DelegateMemberBo delegationMember: delegationMembers){
344                                    if(!delegationIds.contains(delegationMember.getDelegationId())){
345                                            delegationIds.add(delegationMember.getDelegationId());
346                                            criteria = new HashMap<String,String>(1);
347                                            criteria.put(KimConstants.PrimaryKeyConstants.DELEGATION_ID, delegationMember.getDelegationId());
348                                            delegations.add(getBusinessObjectService().findByPrimaryKey(DelegateTypeBo.class, criteria));
349                                    }
350                            }
351                    }
352                    return delegations;
353            }
354    
355    
356        protected void loadDelegationsToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument){
357                    List<RoleDocumentDelegation> delList = new ArrayList<RoleDocumentDelegation>();
358                    RoleDocumentDelegation documentDelegation;
359                    List<DelegateTypeBo> origDelegations = getPersonDelegations(identityManagementPersonDocument.getPrincipalId());
360                    if(ObjectUtils.isNotNull(origDelegations)){
361                            for(DelegateTypeBo del: origDelegations){
362                                    if(del.isActive()){
363                                            documentDelegation = new RoleDocumentDelegation();
364                                            documentDelegation.setActive(del.isActive());
365                                            documentDelegation.setDelegationId(del.getDelegationId());
366                                            documentDelegation.setDelegationTypeCode(del.getDelegationTypeCode());
367                                            documentDelegation.setKimTypeId(del.getKimTypeId());
368                                            documentDelegation.setMembers(
369                                                            loadDelegationMembers(identityManagementPersonDocument,
370                                                                            del.getMembers(), (RoleBo)getMember(MemberType.ROLE, del.getRoleId())));
371                                            documentDelegation.setRoleId(del.getRoleId());
372                                            documentDelegation.setEdit(true);
373                                            delList.add(documentDelegation);
374                                    }
375                            }
376                    }
377                    identityManagementPersonDocument.setDelegations(delList);
378                    setDelegationMembersInDocument(identityManagementPersonDocument);
379            }
380    
381            public void setDelegationMembersInDocument(IdentityManagementPersonDocument identityManagementPersonDocument){
382                    if(CollectionUtils.isNotEmpty(identityManagementPersonDocument.getDelegations())){
383                            for(RoleDocumentDelegation delegation: identityManagementPersonDocument.getDelegations()){
384                                    if(CollectionUtils.isNotEmpty(delegation.getMembers())){
385                                            for(RoleDocumentDelegationMember member: delegation.getMembers()){
386                                                    if (StringUtils.equals(member.getMemberId(), identityManagementPersonDocument.getPrincipalId()))
387                                                    {
388                                                            member.setDelegationTypeCode(delegation.getDelegationTypeCode());
389                                                            identityManagementPersonDocument.getDelegationMembers().add(member);
390                                                    }
391                                            }
392                                    }
393                            }
394                    }
395            }
396    
397        protected List<RoleDocumentDelegationMember> loadDelegationMembers(
398                    IdentityManagementPersonDocument identityManagementPersonDocument, List<DelegateMemberBo> members, RoleBo roleImpl){
399                    List<RoleDocumentDelegationMember> pndMembers = new ArrayList<RoleDocumentDelegationMember>();
400                    RoleDocumentDelegationMember pndMember;
401                    RoleMemberBo roleMember;
402                    if(ObjectUtils.isNotNull(members)){
403                            for(DelegateMemberBo member: members){
404                                    pndMember = new RoleDocumentDelegationMember();
405                                    pndMember.setActiveFromDate(member.getActiveFromDateValue());
406                                    pndMember.setActiveToDate(member.getActiveToDateValue());
407                                    pndMember.setActive(member.isActive(new Timestamp(System.currentTimeMillis())));
408                                    pndMember.setRoleBo(roleImpl);
409                                    if(pndMember.isActive()){
410                                            KimCommonUtilsInternal.copyProperties(pndMember, member);
411                                            pndMember.setRoleMemberId(member.getRoleMemberId());
412                                            roleMember = getRoleMemberForRoleMemberId(member.getRoleMemberId());
413                                            if(roleMember!=null){
414                                                    pndMember.setRoleMemberName(getMemberName(roleMember.getType(), roleMember.getMemberId()));
415                                                    pndMember.setRoleMemberNamespaceCode(getMemberNamespaceCode(roleMember.getType(), roleMember.getMemberId()));
416                                            }
417                                            pndMember.setMemberNamespaceCode(getMemberNamespaceCode(member.getType(), member.getMemberId()));
418                                            pndMember.setMemberName(getMemberName(member.getType(), member.getMemberId()));
419                                            pndMember.setEdit(true);
420                                            pndMember.setQualifiers(loadDelegationMemberQualifiers(identityManagementPersonDocument, pndMember.getAttributesHelper().getDefinitions(), member.getAttributeDetails()));
421                                            pndMembers.add(pndMember);
422                                    }
423                            }
424                    }
425                    return pndMembers;
426            }
427    
428        protected List<RoleDocumentDelegationMemberQualifier> loadDelegationMemberQualifiers(IdentityManagementPersonDocument identityManagementPersonDocument,
429                    List<KimAttributeField> origAttributeDefinitions, List<DelegateMemberAttributeDataBo> attributeDataList){
430                    List<RoleDocumentDelegationMemberQualifier> pndMemberRoleQualifiers = new ArrayList<RoleDocumentDelegationMemberQualifier>();
431                    RoleDocumentDelegationMemberQualifier pndMemberRoleQualifier;
432                    boolean attributePresent = false;
433                    String origAttributeId;
434                    if(origAttributeDefinitions!=null){
435                            for(KimAttributeField key: origAttributeDefinitions) {
436                                    origAttributeId = identityManagementPersonDocument.getKimAttributeDefnId(key);
437                                    if(ObjectUtils.isNotNull(attributeDataList)){
438                                            for(DelegateMemberAttributeDataBo memberRoleQualifier: attributeDataList){
439                                                    if(StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
440                                                            pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
441                                                            pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
442                                                            pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
443                                                            pndMemberRoleQualifier.setDelegationMemberId(memberRoleQualifier.getAssignedToId());
444                                                            pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
445                                                            pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
446                                                            pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
447                                                            pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
448                                                            attributePresent = true;
449                                                    }
450                                            }
451                                    }
452                                    if(!attributePresent){
453                                            pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
454                                            pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
455                                            pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
456                                    }
457                                    attributePresent = false;
458                            }
459                    }
460                    return pndMemberRoleQualifiers;
461            }
462    
463            /**
464             *
465             * This method load related group data to pending document when usert initiate the 'edit'.
466             *
467             * @param identityManagementPersonDocument
468             * @param groups
469             */
470        protected void loadGroupToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument, List<? extends Group> groups) {
471            List <PersonDocumentGroup> docGroups = new ArrayList <PersonDocumentGroup>();
472            if(ObjectUtils.isNotNull(groups)){
473                List<String> directMemberPrincipalIds;
474                Collection<GroupMember> groupMemberships;
475                for (Group group: groups) {
476                    directMemberPrincipalIds = getGroupService().getDirectMemberPrincipalIds(group.getId());
477                    if(ObjectUtils.isNotNull(directMemberPrincipalIds)){
478                        directMemberPrincipalIds = new ArrayList<String>(new HashSet<String>(directMemberPrincipalIds));
479                        for (String memberId: directMemberPrincipalIds) {
480                            // other more direct methods for this ?
481                            // can't cast group to 'GroupImpl' because list is GroupInfo type
482                            if (StringUtils.equals(memberId, identityManagementPersonDocument.getPrincipalId())) {
483                                List<String> groupIds = new ArrayList<String>();
484                                groupIds.add(group.getId());
485                                groupMemberships = getGroupService().getMembers(groupIds);
486                                if(ObjectUtils.isNotNull(groupMemberships)){
487                                    for (GroupMember groupMember: groupMemberships) {
488                                        if (groupMember.isActive(new DateTime(System.currentTimeMillis())) && StringUtils.equals(groupMember.getMemberId(), identityManagementPersonDocument.getPrincipalId()) &&
489                                            KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.equals(groupMember.getType())) {
490                                            // create one PersonDocumentGroup per GroupMembershipInfo **
491                                            PersonDocumentGroup docGroup = new PersonDocumentGroup();
492                                            docGroup.setGroupId(group.getId());
493                                            docGroup.setGroupName(group.getName());
494                                            docGroup.setNamespaceCode(group.getNamespaceCode());
495                                            docGroup.setPrincipalId(memberId);
496                                            docGroup.setGroupMemberId(groupMember.getId());
497                                            if (groupMember.getActiveFromDate() != null) {
498                                                    docGroup.setActiveFromDate(groupMember.getActiveFromDate() == null ? null : new Timestamp(groupMember.getActiveFromDate().getMillis()));
499                                            }
500                                            if (groupMember.getActiveToDate() != null) {
501                                                    docGroup.setActiveToDate(groupMember.getActiveToDate() == null ? null : new Timestamp(groupMember.getActiveToDate().getMillis()));
502                                            }
503                                            docGroup.setKimTypeId(group.getKimTypeId());
504                                            docGroup.setEdit(true);
505                                            docGroups.add(docGroup);
506                                        }
507                                    }
508                                }
509                            }
510                        }
511                    }
512                }
513            }
514            identityManagementPersonDocument.setGroups(docGroups);
515        }
516    
517            protected void loadRoleToPersonDoc(IdentityManagementPersonDocument identityManagementPersonDocument) {
518                    List <PersonDocumentRole> docRoles = new ArrayList <PersonDocumentRole>();
519                    List<RoleBo> roles = getRolesForPrincipal(identityManagementPersonDocument.getPrincipalId());
520                    List<String> roleIds = new ArrayList<String>();
521                    if(ObjectUtils.isNotNull(roles)){
522                    for (RoleBo role : roles) {
523                            if (!roleIds.contains(role.getId())) {
524                                    PersonDocumentRole docRole = new PersonDocumentRole();
525                                    docRole.setKimTypeId(role.getKimTypeId());
526                                    docRole.setActive(role.isActive());
527                                    docRole.setNamespaceCode(role.getNamespaceCode());
528                                    docRole.setEdit(true);
529                                    docRole.setRoleId(role.getId());
530                                    docRole.setRoleName(role.getName());
531                                    docRole.setRolePrncpls(populateDocRolePrncpl(role.getNamespaceCode(), role.getMembers(), identityManagementPersonDocument.getPrincipalId(), getAttributeDefinitionsForRole(docRole)));
532                                    docRole.refreshReferenceObject("assignedResponsibilities");
533                                    if(docRole.getRolePrncpls()!=null && !docRole.getRolePrncpls().isEmpty()){
534                                            docRoles.add(docRole);
535                                            roleIds.add(role.getId());
536                                    }
537                            }
538                    }
539                    }
540                    for (PersonDocumentRole role : docRoles) {
541                            role.setDefinitions(getAttributeDefinitionsForRole(role));
542                    // when post again, it will need this during populate
543                KimDocumentRoleMember newRolePrncpl = new KimDocumentRoleMember();
544                newRolePrncpl.setMemberTypeCode(MemberType.PRINCIPAL.getCode());
545                newRolePrncpl.setMemberId(identityManagementPersonDocument.getPrincipalId());
546                role.setNewRolePrncpl(newRolePrncpl);
547                if(role.getDefinitions()!=null){
548                        for (KimAttributeField key : role.getDefinitions()) {
549                            KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
550                            //qualifier.setQualifierKey(key);
551                            setAttrDefnIdForQualifier(qualifier,key);
552                            role.getNewRolePrncpl().getQualifiers().add(qualifier);
553                        }
554                }
555                loadRoleRstAction(role);
556                role.setAttributeEntry( getAttributeEntries( role.getDefinitions() ) );
557                    }
558            //
559    
560            identityManagementPersonDocument.setRoles(docRoles);
561            }
562    
563            protected List<KimAttributeField> getAttributeDefinitionsForRole(PersonDocumentRole role) {
564            KimTypeService kimTypeService = KimFrameworkServiceLocator.getKimTypeService(KimTypeBo.to(
565                    role.getKimRoleType()));
566            //it is possible that the the kimTypeService is coming from a remote application
567            // and therefore it can't be guarenteed that it is up and working, so using a try/catch to catch this possibility.
568            try {
569                    if ( kimTypeService != null ) {
570                            return kimTypeService.getAttributeDefinitions(role.getKimTypeId());
571                    }
572            } catch (Exception ex) {
573                LOG.warn("Not able to retrieve KimTypeService from remote system for KIM Role Type: " + role.getKimRoleType(), ex);
574            }
575            return Collections.emptyList();
576            }
577    
578            protected void loadRoleRstAction(PersonDocumentRole role) {
579                    if(role!=null && CollectionUtils.isNotEmpty(role.getRolePrncpls())){
580                            for (KimDocumentRoleMember roleMbr : role.getRolePrncpls()) {
581                                    List<RoleResponsibilityActionBo> actions = getRoleRspActions( roleMbr.getRoleMemberId());
582                                    if(ObjectUtils.isNotNull(actions)){
583                                            for (RoleResponsibilityActionBo entRoleRspAction :actions) {
584                                                    KimDocumentRoleResponsibilityAction roleRspAction = new KimDocumentRoleResponsibilityAction();
585                                                    roleRspAction.setRoleResponsibilityActionId(entRoleRspAction.getId());
586                            roleRspAction.setRoleResponsibilityId(entRoleRspAction.getRoleResponsibilityId());
587                                                    roleRspAction.setActionTypeCode(entRoleRspAction.getActionTypeCode());
588                                                    roleRspAction.setActionPolicyCode(entRoleRspAction.getActionPolicyCode());
589                                                    roleRspAction.setPriorityNumber(entRoleRspAction.getPriorityNumber());
590                                                    roleRspAction.setRoleResponsibilityActionId(entRoleRspAction.getId());
591                                                    roleRspAction.refreshReferenceObject("roleResponsibility");
592                                                    roleMbr.getRoleRspActions().add(roleRspAction);
593                                            }
594                                    }
595                            }
596                    }
597            }
598    
599            protected void setAttrDefnIdForQualifier(KimDocumentRoleQualifier qualifier, KimAttributeField definition) {
600            qualifier.setKimAttrDefnId(getAttributeDefnId(definition));
601            qualifier.refreshReferenceObject("kimAttribute");
602        }
603    
604            protected String getAttributeDefnId(KimAttributeField definition) {
605            return definition.getId();
606        }
607    
608            private PrincipalBo getPrincipalImpl(String principalId) {
609                    Map<String,String> criteria = new HashMap<String,String>(1);
610            criteria.put(KIMPropertyConstants.Principal.PRINCIPAL_ID, principalId);
611                    return (PrincipalBo)getBusinessObjectService().findByPrimaryKey(PrincipalBo.class, criteria);
612            }
613    
614            public List<EntityEmployment> getEntityEmploymentInformationInfo(String entityId) {
615            EntityBo entityImpl = getEntityBo(entityId);
616            List<EntityEmployment> empInfos = new ArrayList<EntityEmployment>();
617            EntityEmployment empInfo;
618            if(ObjectUtils.isNotNull(entityImpl) && CollectionUtils.isNotEmpty(entityImpl.getEmploymentInformation())){
619                    for(EntityEmploymentBo empImpl: entityImpl.getEmploymentInformation()){
620                    empInfos.add(EntityEmploymentBo.to(empImpl));
621                    }
622            }
623            return empInfos;
624            }
625    
626            private EntityBo getEntityBo(String entityId) {
627                    EntityBo entityImpl = getBusinessObjectService().findBySinglePrimaryKey(EntityBo.class, entityId);
628            //TODO - remove this hack... This is here because currently jpa only seems to be going 2 levels deep on the eager fetching.
629                    if(entityImpl!=null  && entityImpl.getEntityTypeContactInfos() != null) {
630                    for (EntityTypeContactInfoBo et : entityImpl.getEntityTypeContactInfos()) {
631                            et.refresh();
632                    }
633            }
634                    return entityImpl;
635            }
636    
637        @SuppressWarnings("unchecked")
638            protected List<RoleBo> getRolesForPrincipal(String principalId) {
639                    if ( principalId == null ) {
640                            return new ArrayList<RoleBo>();
641                    }
642                    Map<String,String> criteria = new HashMap<String,String>( 2 );
643                    criteria.put("members.memberId", principalId);
644                    criteria.put("members.typeCode", MemberType.PRINCIPAL.getCode());
645                    return (List<RoleBo>)getBusinessObjectService().findMatching(RoleBo.class, criteria);
646            }
647    
648            @SuppressWarnings("unchecked")
649            protected List<RoleMemberBo> getRoleMembersForPrincipal(String principalId) {
650                    if ( principalId == null ) {
651                            return new ArrayList<RoleMemberBo>();
652                    }
653                    Map<String,String> criteria = new HashMap<String,String>( 2 );
654                    criteria.put("memberId", principalId);
655                    criteria.put("typeCode", MemberType.PRINCIPAL.getCode());
656                    return (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, criteria);
657            }
658    
659            public RoleMemberBo getRoleMember(String id) {
660                    if ( id == null ) {
661                            return null;
662                    }
663                    Map<String,String> criteria = new HashMap<String,String>( 2 );
664                    criteria.put("id", id);
665                    return getBusinessObjectService().findByPrimaryKey(RoleMemberBo.class, criteria);
666            }
667    
668        @SuppressWarnings("unchecked")
669            protected List<RoleResponsibilityActionBo> getRoleRspActions(String roleMemberId) {
670                    Map<String,String> criteria = new HashMap<String,String>( 1 );
671                    criteria.put(KIMPropertyConstants.RoleMember.ROLE_MEMBER_ID, roleMemberId);
672                    return (List<RoleResponsibilityActionBo>)getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
673            }
674    
675        protected List<KimDocumentRoleMember> populateDocRolePrncpl(String namespaceCode, List <RoleMemberBo> roleMembers, String principalId, List<KimAttributeField> definitions) {
676                    List <KimDocumentRoleMember> docRoleMembers = new ArrayList <KimDocumentRoleMember>();
677                    if(ObjectUtils.isNotNull(roleMembers)){
678                    for (RoleMemberBo rolePrincipal : roleMembers) {
679                            if (rolePrincipal.isActive(new Timestamp(System.currentTimeMillis())) && MemberType.PRINCIPAL.equals(
680                            rolePrincipal.getType()) &&
681                                            StringUtils.equals(rolePrincipal.getMemberId(), principalId)) {
682                                    KimDocumentRoleMember docRolePrncpl = new KimDocumentRoleMember();
683                                    docRolePrncpl.setMemberId(rolePrincipal.getMemberId());
684                                    docRolePrncpl.setRoleMemberId(rolePrincipal.getId());
685                                    docRolePrncpl.setActive(rolePrincipal.isActive(new Timestamp(System.currentTimeMillis())));
686                                    docRolePrncpl.setRoleId(rolePrincipal.getRoleId());
687                                    docRolePrncpl.setActiveFromDate(rolePrincipal.getActiveFromDateValue());
688                                    docRolePrncpl.setActiveToDate(rolePrincipal.getActiveToDateValue());
689                                    docRolePrncpl.setQualifiers(populateDocRoleQualifier(namespaceCode, rolePrincipal.getAttributeDetails(), definitions));
690                                    docRolePrncpl.setEdit(true);
691                                    docRoleMembers.add(docRolePrncpl);
692                             }
693                    }
694                    }
695            return docRoleMembers;
696        }
697    
698        // UI layout for rolequalifier is a little different from kimroleattribute set up.
699        // each principal may have member with same role multiple times with different qualifier, but the role
700        // only displayed once, and the qualifier displayed multiple times.
701        protected List<KimDocumentRoleQualifier> populateDocRoleQualifier(String namespaceCode, List <RoleMemberAttributeDataBo> qualifiers, List<KimAttributeField> definitions) {
702    
703                    List <KimDocumentRoleQualifier> docRoleQualifiers = new ArrayList <KimDocumentRoleQualifier>();
704                    if(definitions!=null){
705                            for (KimAttributeField definition : definitions) {
706                                    String attrDefId=definition.getId();
707                                    boolean qualifierFound = false;
708                                    if(ObjectUtils.isNotNull(qualifiers)){
709                                            for (RoleMemberAttributeDataBo qualifier : qualifiers) {
710                                                    if (attrDefId!=null && StringUtils.equals(attrDefId, qualifier.getKimAttributeId())) {
711                                                    KimDocumentRoleQualifier docRoleQualifier = new KimDocumentRoleQualifier();
712                                                    docRoleQualifier.setAttrDataId(qualifier.getId());
713                                                    docRoleQualifier.setAttrVal(qualifier.getAttributeValue());
714                                                    docRoleQualifier.setKimAttrDefnId(qualifier.getKimAttributeId());
715                                                    docRoleQualifier.setKimAttribute(qualifier.getKimAttribute());
716                                                    docRoleQualifier.setKimTypId(qualifier.getKimTypeId());
717                                                    docRoleQualifier.setRoleMemberId(qualifier.getAssignedToId());
718                                                    docRoleQualifier.setEdit(true);
719                                                    formatAttrValIfNecessary(docRoleQualifier);
720                                                    docRoleQualifiers.add(docRoleQualifier);
721                                                    qualifierFound = true;
722                                                    break;
723                                                    }
724                                            }
725                                    }
726                                    if (!qualifierFound) {
727                                    KimDocumentRoleQualifier docRoleQualifier = new KimDocumentRoleQualifier();
728                                    docRoleQualifier.setAttrVal("");
729                                    docRoleQualifier.setKimAttrDefnId(attrDefId);
730                                    docRoleQualifier.refreshReferenceObject("kimAttribute");
731                                    docRoleQualifiers.add(docRoleQualifier);
732                                    }
733                            }
734                            // If all of the qualifiers are empty, return an empty list
735                            // This is to prevent dynamic qualifiers from appearing in the
736                            // person maintenance roles tab.  see KULRICE-3989 for more detail
737                            // and KULRICE-5071 for detail on switching from config value to 
738                            // application-scoped parameter
739                            if (!isBlankRoleQualifierVisible(namespaceCode)) {
740                                    int qualCount = 0;
741                                    for (KimDocumentRoleQualifier qual : docRoleQualifiers){
742                                            if (StringUtils.isEmpty(qual.getAttrVal())){
743                                                    qualCount++;
744                                            }
745                                    }
746                                    if (qualCount == docRoleQualifiers.size()){
747                                            return new ArrayList <KimDocumentRoleQualifier>();
748                                    }
749                            }
750                    }
751            return docRoleQualifiers;
752        }
753    
754        protected List<PersonDocumentName> loadNames( IdentityManagementPersonDocument personDoc, String principalId, List <EntityName> names, boolean suppressDisplay ) {
755                    List<PersonDocumentName> docNames = new ArrayList<PersonDocumentName>();
756                    if(ObjectUtils.isNotNull(names)){
757                            for (EntityName name: names) {
758                                    if(name.isActive()){
759                                            PersonDocumentName docName = new PersonDocumentName();
760                        if (name.getNameType() != null) {
761                                                docName.setNameCode(name.getNameType().getCode());
762                        }
763    
764                                            //We do not need to check the privacy setting here - The UI should care of it
765                                            docName.setFirstName(name.getFirstNameUnmasked());
766                                            docName.setLastName(name.getLastNameUnmasked());
767                                            docName.setMiddleName(name.getMiddleNameUnmasked());
768                                            docName.setNamePrefix(name.getNamePrefixUnmasked());
769                                            docName.setNameSuffix(name.getNameSuffixUnmasked());
770    
771                                            docName.setActive(name.isActive());
772                                            docName.setDflt(name.isDefaultValue());
773                                            docName.setEdit(true);
774                                            docName.setEntityNameId(name.getId());
775                                            docNames.add(docName);
776                                    }
777                            }
778                    }
779                    return docNames;
780            }
781    
782            public boolean canModifyEntity( String currentUserPrincipalId, String toModifyPrincipalId ){
783                    return (StringUtils.isNotBlank(currentUserPrincipalId) && StringUtils.isNotBlank(toModifyPrincipalId) &&
784                                    currentUserPrincipalId.equals(toModifyPrincipalId)) ||
785                                    getPermissionService().isAuthorized(
786                                                    currentUserPrincipalId,
787                                                    KimConstants.NAMESPACE_CODE,
788                                                    KimConstants.PermissionNames.MODIFY_ENTITY,
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.singletonMap(KimConstants.AttributeConstants.PRINCIPAL_ID, currentUserPrincipalId) );
800            }
801    
802            protected boolean canAssignToRole(IdentityManagementRoleDocument document, String initiatorPrincipalId){
803            boolean rulePassed = true;
804            Map<String,String> additionalPermissionDetails = new HashMap<String,String>();
805            additionalPermissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, document.getRoleNamespace());
806            additionalPermissionDetails.put(KimConstants.AttributeConstants.ROLE_NAME, document.getRoleName());
807                    if(!getDocumentHelperService().getDocumentAuthorizer(document).isAuthorizedByTemplate(
808                                    document, KimConstants.NAMESPACE_CODE, KimConstants.PermissionTemplateNames.ASSIGN_ROLE,
809                                    initiatorPrincipalId, additionalPermissionDetails, null)){
810                rulePassed = false;
811                    }
812                    return rulePassed;
813            }
814    
815            protected List<PersonDocumentAffiliation> loadAffiliations(List <EntityAffiliation> affiliations, List<EntityEmployment> empInfos) {
816                    List<PersonDocumentAffiliation> docAffiliations = new ArrayList<PersonDocumentAffiliation>();
817                    if(ObjectUtils.isNotNull(affiliations)){
818                            for (EntityAffiliation affiliation: affiliations) {
819                                    if(affiliation.isActive()){
820                                            PersonDocumentAffiliation docAffiliation = new PersonDocumentAffiliation();
821                                            docAffiliation.setAffiliationTypeCode(affiliation.getAffiliationType().getCode());
822                                            docAffiliation.setCampusCode(affiliation.getCampusCode());
823                                            docAffiliation.setActive(affiliation.isActive());
824                                            docAffiliation.setDflt(affiliation.isDefaultValue());
825                                            docAffiliation.setEntityAffiliationId(affiliation.getId());
826                                            docAffiliation.refreshReferenceObject("affiliationType");
827                                            // EntityAffiliationImpl does not define empinfos as collection
828                                            docAffiliations.add(docAffiliation);
829                                            docAffiliation.setEdit(true);
830                                            // employment informations
831                                            List<PersonDocumentEmploymentInfo> docEmploymentInformations = new ArrayList<PersonDocumentEmploymentInfo>();
832                                            if(ObjectUtils.isNotNull(empInfos)){
833                                                    for (EntityEmployment empInfo: empInfos) {
834                                                            if (empInfo.isActive()
835                                        && StringUtils.equals(docAffiliation.getEntityAffiliationId(),
836                                                              (empInfo.getEntityAffiliation() != null ? empInfo.getEntityAffiliation().getId() : null))) {
837                                                                    PersonDocumentEmploymentInfo docEmpInfo = new PersonDocumentEmploymentInfo();
838                                                                    docEmpInfo.setEntityEmploymentId(empInfo.getEmployeeId());
839                                                                    docEmpInfo.setEmployeeId(empInfo.getEmployeeId());
840                                                                    docEmpInfo.setEmploymentRecordId(empInfo.getEmploymentRecordId());
841                                                                    docEmpInfo.setBaseSalaryAmount(empInfo.getBaseSalaryAmount());
842                                                                    docEmpInfo.setPrimaryDepartmentCode(empInfo.getPrimaryDepartmentCode());
843                                                                    docEmpInfo.setEmploymentStatusCode(empInfo.getEmployeeStatus() != null ? empInfo.getEmployeeStatus().getCode() : null);
844                                                                    docEmpInfo.setEmploymentTypeCode(empInfo.getEmployeeType() != null ? empInfo.getEmployeeType().getCode() : null);
845                                                                    docEmpInfo.setActive(empInfo.isActive());
846                                                                    docEmpInfo.setPrimary(empInfo.isPrimary());
847                                                                    docEmpInfo.setEntityAffiliationId(empInfo.getEntityAffiliation() != null ? empInfo.getEntityAffiliation().getId() : null);
848                                                                    // there is no version number on KimEntityEmploymentInformationInfo
849                                                                    //docEmpInfo.setVersionNumber(empInfo.getVersionNumber());
850                                                                    docEmpInfo.setEdit(true);
851                                                                    docEmpInfo.refreshReferenceObject("employmentType");
852                                                                    docEmploymentInformations.add(docEmpInfo);
853                                                            }
854                                                    }
855                                            }
856                                            docAffiliation.setEmpInfos(docEmploymentInformations);
857                                    }
858                            }
859                    }
860                    return docAffiliations;
861    
862            }
863    
864        protected boolean setupPrincipal(IdentityManagementPersonDocument identityManagementPersonDocument, EntityBo kimEntity, List<PrincipalBo> origPrincipals) {
865            boolean inactivatingPrincipal = false;
866                    List<PrincipalBo> principals = new ArrayList<PrincipalBo>();
867                    PrincipalBo principal = new PrincipalBo();
868            principal.setPrincipalName(identityManagementPersonDocument.getPrincipalName());
869                    principal.setPrincipalId(identityManagementPersonDocument.getPrincipalId());
870                    principal.setActive(identityManagementPersonDocument.isActive());
871                    principal.setEntityId(identityManagementPersonDocument.getEntityId());
872                    if(ObjectUtils.isNotNull(origPrincipals)){
873                            for (PrincipalBo prncpl : origPrincipals) {
874                                    if (prncpl.getPrincipalId()!=null && StringUtils.equals(prncpl.getPrincipalId(), principal.getPrincipalId())) {
875                                            principal.setVersionNumber(prncpl.getVersionNumber());
876                        principal.setObjectId(prncpl.getObjectId());
877                        principal.setPassword(prncpl.getPassword());
878                                            // check if inactivating the principal
879                                            if ( prncpl.isActive() && !principal.isActive() ) {
880                                                    inactivatingPrincipal = true;
881                                            }
882                                    }
883                            }
884                    }
885                    principals.add(principal);
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 = KNSServiceLocator.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 RoleResponsibilityActionBo getRoleResponsibilityActionImpl(String roleResponsibilityActionId){
1686            Map<String, String> criteria = new HashMap<String, String>();
1687            criteria.put(KimConstants.PrimaryKeyConstants.ID, roleResponsibilityActionId);
1688            return getBusinessObjectService().findByPrimaryKey(RoleResponsibilityActionBo.class, criteria);
1689        }
1690    
1691            @SuppressWarnings("unchecked")
1692            protected List<RoleResponsibilityActionBo> getRoleResponsibilityActionImpls(String roleResponsibilityId){
1693                    Map<String, String> criteria = new HashMap<String, String>();
1694                    criteria.put(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID, "*");
1695                    criteria.put(KimConstants.PrimaryKeyConstants.ROLE_RESPONSIBILITY_ID, roleResponsibilityId);
1696                    return (List<RoleResponsibilityActionBo>)
1697                            getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
1698            }
1699    
1700            @SuppressWarnings("unchecked")
1701            public List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActionImpls(String roleMemberId){
1702                    Map<String, String> criteria = new HashMap<String, String>(1);
1703                    criteria.put(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID, roleMemberId);
1704                    return (List<RoleResponsibilityActionBo>)
1705                            getBusinessObjectService().findMatching(RoleResponsibilityActionBo.class, criteria);
1706            }
1707    
1708            protected void loadMemberRoleRspActions(IdentityManagementRoleDocument identityManagementRoleDocument){
1709                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
1710                            for(KimDocumentRoleMember member: identityManagementRoleDocument.getMembers()){
1711                                    member.getRoleRspActions().addAll(loadKimDocumentRoleRespActions(
1712                                                    getRoleMemberResponsibilityActionImpls(member.getRoleMemberId()) ) );
1713                            }
1714                    }
1715            }
1716    
1717            protected List<KimDocumentRoleResponsibilityAction> loadKimDocumentRoleRespActions(
1718                            List<RoleResponsibilityActionBo> roleRespActionImpls){
1719                    List<KimDocumentRoleResponsibilityAction> documentRoleRespActions = new ArrayList<KimDocumentRoleResponsibilityAction>();
1720                    KimDocumentRoleResponsibilityAction documentRoleRespAction;
1721                    if(ObjectUtils.isNotNull(roleRespActionImpls)){
1722                            for(RoleResponsibilityActionBo roleRespActionImpl: roleRespActionImpls){
1723                                    documentRoleRespAction = new KimDocumentRoleResponsibilityAction();
1724                                    KimCommonUtilsInternal.copyProperties(documentRoleRespAction, roleRespActionImpl);
1725    
1726                    //primary key has different name in these objects!  we need to make sure to copy it over
1727                    documentRoleRespAction.setRoleResponsibilityActionId(roleRespActionImpl.getId());
1728    
1729                                    // handle the roleResponsibility object being null since not all may be defined when ID value is "*"
1730                                    if ( ObjectUtils.isNotNull(roleRespActionImpl.getRoleResponsibility()) ) {
1731                                            documentRoleRespAction.setKimResponsibility(roleRespActionImpl.getRoleResponsibility().getKimResponsibility());
1732                                    }
1733                                    documentRoleRespActions.add(documentRoleRespAction);
1734                            }
1735                    }
1736                    return documentRoleRespActions;
1737            }
1738    
1739        public BusinessObject getMember(MemberType memberType, String memberId){
1740            Class<? extends BusinessObject> roleMemberTypeClass = null;
1741            String roleMemberIdName = "";
1742            if(MemberType.PRINCIPAL.equals(memberType)) {
1743                    roleMemberTypeClass = PrincipalBo.class;
1744                    roleMemberIdName = KimConstants.PrimaryKeyConstants.PRINCIPAL_ID;
1745                            Principal principalInfo = getIdentityService().getPrincipal(memberId);
1746                            if (principalInfo != null) {
1747                                    
1748                            }
1749            } else if(MemberType.GROUP.equals(memberType)){
1750                    roleMemberTypeClass = GroupBo.class;
1751                    roleMemberIdName = KimConstants.PrimaryKeyConstants.GROUP_ID;
1752                    Group groupInfo = null;
1753                            groupInfo = getGroupService().getGroup(memberId);
1754                            if (groupInfo != null) {
1755                                    
1756                            }
1757            } else if(MemberType.ROLE.equals(memberType)){
1758                    roleMemberTypeClass = RoleBo.class;
1759                    roleMemberIdName = KimConstants.PrimaryKeyConstants.ROLE_ID;
1760                            Role role = getRoleService().getRole(memberId);
1761                            if (role != null) {
1762                                    
1763                            }
1764            }
1765            Map<String, String> criteria = new HashMap<String, String>();
1766            criteria.put(roleMemberIdName, memberId);
1767            return getBusinessObjectService().findByPrimaryKey(roleMemberTypeClass, criteria);
1768        }
1769    
1770            public String getMemberName(MemberType memberType, String memberId){
1771                    if (memberType == null || StringUtils.isEmpty(memberId)) { return "";}
1772                    BusinessObject member = getMember(memberType, memberId);
1773                    if (member == null) { //not a REAL principal, try to fake the name
1774                            String fakeName = "";
1775                            Principal kp = KimApiServiceLocator.getIdentityService().getPrincipal(memberId);
1776                            if(kp != null && kp.getPrincipalName() != null && !"".equals(kp.getPrincipalName())){
1777                                    fakeName = kp.getPrincipalName();
1778                            }
1779    
1780                            return fakeName;
1781                    }
1782                    return getMemberName(memberType, member);
1783            }
1784    
1785            public String getMemberFullName(MemberType memberType, String memberId){
1786                    if(memberType == null || StringUtils.isEmpty(memberId)) {return "";}
1787                    String memberFullName = "";
1788            if(MemberType.PRINCIPAL.equals(memberType)){
1789                    Principal principalInfo = null;
1790                    principalInfo = getIdentityService().getPrincipal(memberId);
1791                    if (principalInfo != null) {
1792                            String principalName = principalInfo.getPrincipalName();
1793                            Person psn = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(principalName);
1794                            memberFullName = psn.getFirstName() + " " + psn.getLastName();
1795                    }                               
1796            } else if(MemberType.GROUP.equals(memberType)){
1797                    Group group = null;
1798                    group = getGroupService().getGroup(memberId);
1799                    if (group != null) {
1800                            memberFullName = group.getName();
1801                    }
1802                    
1803            } else if(MemberType.ROLE.equals(memberType)){
1804                    Role role = getRoleService().getRole(memberId);
1805                    memberFullName = role.getName();
1806            }
1807            return memberFullName;
1808            }
1809    
1810            public String getMemberNamespaceCode(MemberType memberType, String memberId){
1811                    if(memberType == null || StringUtils.isEmpty(memberId)) {return "";}
1812            String roleMemberNamespaceCode = "";
1813            if(MemberType.PRINCIPAL.equals(memberType)){
1814                    roleMemberNamespaceCode = "";
1815            } else if(MemberType.GROUP.equals(memberType)){
1816                    Group groupInfo = getGroupService().getGroup(memberId);
1817                    if (groupInfo!= null) {
1818                            roleMemberNamespaceCode = groupInfo.getNamespaceCode();
1819                    }
1820            } else if(MemberType.ROLE.equals(memberType)){
1821                    Role role = getRoleService().getRole(memberId);
1822                    if (role != null) {
1823                            roleMemberNamespaceCode = role.getNamespaceCode();
1824                    }               
1825            }
1826            return roleMemberNamespaceCode;
1827            }
1828    
1829        public String getMemberIdByName(MemberType memberType, String memberNamespaceCode, String memberName){
1830            String memberId = "";
1831            if(MemberType.PRINCIPAL.equals(memberType)){
1832                Principal principal = getIdentityService().getPrincipalByPrincipalName(memberName);
1833                if(principal!=null) {
1834                    memberId = principal.getPrincipalId();
1835                }
1836    
1837           } else if(MemberType.GROUP.equals(memberType)){
1838                    Group groupInfo = getGroupService().getGroupByNamespaceCodeAndName(memberNamespaceCode, memberName);
1839                    if (groupInfo!=null) {
1840                    memberId = groupInfo.getId();
1841                }
1842    
1843            } else if(MemberType.ROLE.equals(memberType)){
1844                    memberId = getRoleService().getRoleIdByNamespaceCodeAndName(memberNamespaceCode, memberName);
1845            }
1846            return memberId;
1847        }
1848    
1849        public String getMemberName(MemberType memberType, BusinessObject member){
1850            String roleMemberName = "";
1851            if(MemberType.PRINCIPAL.equals(memberType)){
1852                    roleMemberName = ((PrincipalBo)member).getPrincipalName();
1853            } else if(MemberType.GROUP.equals(memberType)){
1854                    roleMemberName = ((GroupBo)member).getName();
1855            } else if(MemberType.ROLE.equals(memberType)){
1856                    roleMemberName = ((RoleBo)member).getName();
1857            }
1858            return roleMemberName;
1859        }
1860    
1861        public String getMemberNamespaceCode(MemberType memberType, BusinessObject member){
1862            String roleMemberNamespaceCode = "";
1863            if(MemberType.PRINCIPAL.equals(memberType)){
1864                    roleMemberNamespaceCode = "";
1865            } else if(MemberType.GROUP.equals(memberType)){
1866                    roleMemberNamespaceCode = ((GroupBo)member).getNamespaceCode();
1867            } else if(MemberType.ROLE.equals(memberType)){
1868                    roleMemberNamespaceCode = ((RoleBo)member).getNamespaceCode();
1869            }
1870            return roleMemberNamespaceCode;
1871        }
1872    
1873        protected List<KimDocumentRoleQualifier> loadRoleMemberQualifiers(IdentityManagementRoleDocument identityManagementRoleDocument,
1874                            List<RoleMemberAttributeDataBo> attributeDataList){
1875                    List<KimDocumentRoleQualifier> pndMemberRoleQualifiers = new ArrayList<KimDocumentRoleQualifier>();
1876                    KimDocumentRoleQualifier pndMemberRoleQualifier;
1877    
1878                    // add all attributes from attributeDataList
1879                    if(attributeDataList!=null){
1880                            for(RoleMemberAttributeDataBo memberRoleQualifier: attributeDataList){
1881                                    pndMemberRoleQualifier = new KimDocumentRoleQualifier();
1882                                    pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
1883                                    pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
1884                                    pndMemberRoleQualifier.setRoleMemberId(memberRoleQualifier.getAssignedToId());
1885                                    pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
1886                                    pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
1887                                    pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
1888                                    formatAttrValIfNecessary(pndMemberRoleQualifier);
1889                                    pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
1890                            }
1891                    }
1892                    // also add any attributes already in the document that are not in the attributeDataList
1893                    int countOfOriginalAttributesNotPresent = 0;
1894                    List<KimDocumentRoleQualifier> fillerRoleQualifiers = new ArrayList<KimDocumentRoleQualifier>();
1895    
1896                    List<KimAttributeField> origAttributes = identityManagementRoleDocument.getDefinitions();
1897                    if ( origAttributes != null ) {
1898                            for(KimAttributeField key: origAttributes) {
1899                                    boolean attributePresent = false;
1900                                    String origAttributeId = identityManagementRoleDocument.getKimAttributeDefnId(key);
1901                                    if(attributeDataList!=null){
1902                                            for(RoleMemberAttributeDataBo memberRoleQualifier: attributeDataList){
1903                                                    if(origAttributeId!=null && StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
1904                                                            attributePresent = true;
1905                                                            break;
1906                                                    }
1907                                            }
1908                                    }
1909                                    if(!attributePresent){
1910                                            countOfOriginalAttributesNotPresent++;
1911                                            pndMemberRoleQualifier = new KimDocumentRoleQualifier();
1912                                            pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
1913                                            pndMemberRoleQualifier.refreshReferenceObject("kimAttribute");
1914                                            fillerRoleQualifiers.add(pndMemberRoleQualifier);
1915                                    }
1916                            }
1917    
1918                            if(countOfOriginalAttributesNotPresent != origAttributes.size()) {
1919                                    pndMemberRoleQualifiers.addAll(fillerRoleQualifiers);
1920                            }
1921                    }
1922                    return pndMemberRoleQualifiers;
1923            }
1924    
1925        @SuppressWarnings("unchecked")
1926            public List<DelegateTypeBo> getRoleDelegations(String roleId){
1927                    if(roleId==null) {
1928                            return new ArrayList<DelegateTypeBo>();
1929            }
1930                    Map<String,String> criteria = new HashMap<String,String>(1);
1931                    criteria.put("roleId", roleId);
1932                    return (List<DelegateTypeBo>)getBusinessObjectService().findMatching(DelegateTypeBo.class, criteria);
1933            }
1934    
1935        protected List<RoleDocumentDelegation> loadRoleDocumentDelegations(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateTypeBo> delegations){
1936                    List<RoleDocumentDelegation> delList = new ArrayList<RoleDocumentDelegation>();
1937                    RoleDocumentDelegation documentDelegation;
1938                    if(ObjectUtils.isNotNull(delegations)){
1939                            for(DelegateTypeBo del: delegations){
1940                                    documentDelegation = new RoleDocumentDelegation();
1941                                    documentDelegation.setActive(del.isActive());
1942                                    if(documentDelegation.isActive()){
1943                                            documentDelegation.setDelegationId(del.getDelegationId());
1944                                            documentDelegation.setDelegationTypeCode(del.getDelegationTypeCode());
1945                                            documentDelegation.setKimTypeId(del.getKimTypeId());
1946                                            documentDelegation.setMembers(loadDelegationMembers(identityManagementRoleDocument, del.getMembers()));
1947                                            documentDelegation.setRoleId(del.getRoleId());
1948                                            documentDelegation.setEdit(true);
1949                                            delList.add(documentDelegation);
1950                                    }
1951                            }
1952                    }
1953                    return delList;
1954            }
1955    
1956        protected List<RoleDocumentDelegationMember> loadDelegationMembers(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateMemberBo> members){
1957                    List<RoleDocumentDelegationMember> pndMembers = new ArrayList<RoleDocumentDelegationMember>();
1958                    RoleDocumentDelegationMember pndMember;
1959                    RoleMemberBo roleMember;
1960                    if(ObjectUtils.isNotNull(members)){
1961                            for(DelegateMemberBo member: members){
1962                                    pndMember = new RoleDocumentDelegationMember();
1963                                    pndMember.setActiveFromDate(member.getActiveFromDateValue());
1964                                    pndMember.setActiveToDate(member.getActiveToDateValue());
1965                                    pndMember.setActive(member.isActive(new Timestamp(System.currentTimeMillis())));
1966                                    if(pndMember.isActive()){
1967                                            //KimCommonUtilsInternal.copyProperties(pndMember, member);
1968                        pndMember.setDelegationId(member.getDelegationId());
1969                        pndMember.setDelegationMemberId(member.getDelegationMemberId());
1970                        pndMember.setDelegationTypeCode(member.getType().getCode());
1971                        pndMember.setRoleMemberId(member.getRoleMemberId());
1972                        pndMember.setMemberId(member.getMemberId());
1973                        pndMember.setMemberTypeCode(member.getType().getCode());
1974    
1975                                            roleMember = getRoleMemberForRoleMemberId(member.getRoleMemberId());
1976                                            if(roleMember!=null){
1977                                                    pndMember.setRoleMemberName(getMemberName(roleMember.getType(), roleMember.getMemberId()));
1978                                                    pndMember.setRoleMemberNamespaceCode(getMemberNamespaceCode(roleMember.getType(), roleMember.getMemberId()));
1979                                            }
1980                                            pndMember.setMemberNamespaceCode(getMemberNamespaceCode(member.getType(), member.getMemberId()));
1981                                            pndMember.setMemberName(getMemberName(member.getType(), member.getMemberId()));
1982                                            pndMember.setEdit(true);
1983                                            pndMember.setQualifiers(loadDelegationMemberQualifiers(identityManagementRoleDocument, member.getAttributeDetails()));
1984                                            pndMembers.add(pndMember);
1985                                    }
1986                            }
1987                    }
1988                    return pndMembers;
1989            }
1990    
1991        protected RoleMemberBo getRoleMemberForRoleMemberId(String roleMemberId){
1992                    Map<String,String> criteria = new HashMap<String,String>( 2 );
1993                    criteria.put(KimConstants.PrimaryKeyConstants.ID, roleMemberId);
1994                    return getBusinessObjectService().findByPrimaryKey(RoleMemberBo.class, criteria);
1995        }
1996    
1997        protected List<RoleDocumentDelegationMemberQualifier> loadDelegationMemberQualifiers(IdentityManagementRoleDocument identityManagementRoleDocument,
1998                            List<DelegateMemberAttributeDataBo> attributeDataList){
1999                    List<RoleDocumentDelegationMemberQualifier> pndMemberRoleQualifiers = new ArrayList<RoleDocumentDelegationMemberQualifier>();
2000                    RoleDocumentDelegationMemberQualifier pndMemberRoleQualifier;
2001                    List<KimAttributeField> origAttributes = identityManagementRoleDocument.getDefinitions();
2002                    boolean attributePresent = false;
2003                    String origAttributeId;
2004                    if(origAttributes!=null){
2005                            for(KimAttributeField key: origAttributes) {
2006                                    origAttributeId = identityManagementRoleDocument.getKimAttributeDefnId(key);
2007                                    if(attributeDataList!=null){
2008                                            for(DelegateMemberAttributeDataBo memberRoleQualifier: attributeDataList){
2009                                                    if(origAttributeId!=null && StringUtils.equals(origAttributeId, memberRoleQualifier.getKimAttribute().getId())){
2010                                                            pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
2011                                                            pndMemberRoleQualifier.setAttrDataId(memberRoleQualifier.getId());
2012                                                            pndMemberRoleQualifier.setAttrVal(memberRoleQualifier.getAttributeValue());
2013                                                            pndMemberRoleQualifier.setDelegationMemberId(memberRoleQualifier.getAssignedToId());
2014                                                            pndMemberRoleQualifier.setKimTypId(memberRoleQualifier.getKimTypeId());
2015                                                            pndMemberRoleQualifier.setKimAttrDefnId(memberRoleQualifier.getKimAttributeId());
2016                                                            pndMemberRoleQualifier.setKimAttribute(memberRoleQualifier.getKimAttribute());
2017                                                            pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
2018                                                            attributePresent = true;
2019                                                    }
2020                                            }
2021                                    }
2022                                    if(!attributePresent){
2023                                            pndMemberRoleQualifier = new RoleDocumentDelegationMemberQualifier();
2024                                            pndMemberRoleQualifier.setKimAttrDefnId(origAttributeId);
2025                                            pndMemberRoleQualifier.refreshReferenceObject("kimAttribute");
2026                                            pndMemberRoleQualifiers.add(pndMemberRoleQualifier);
2027                                    }
2028                                    attributePresent = false;
2029                            }
2030                    }
2031                    return pndMemberRoleQualifiers;
2032            }
2033    
2034            /**
2035             * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
2036             */
2037            @SuppressWarnings("unchecked")
2038            public void saveRole(IdentityManagementRoleDocument identityManagementRoleDocument) {
2039                    RoleBo roleBo = new RoleBo();
2040                    Map<String, String> criteria = new HashMap<String, String>();
2041                    String roleId = identityManagementRoleDocument.getRoleId();
2042                    criteria.put(KimConstants.PrimaryKeyConstants.ID, roleId);
2043                    RoleBo origRole = getBusinessObjectService().findByPrimaryKey(RoleBo.class, criteria);
2044    
2045                    List<RolePermissionBo> origRolePermissions = new ArrayList<RolePermissionBo>();
2046                    List<RoleResponsibilityBo> origRoleResponsibilities = new ArrayList<RoleResponsibilityBo>();
2047                    List<RoleMemberBo> origRoleMembers = new ArrayList<RoleMemberBo>();
2048                    List<DelegateTypeBo> origRoleDelegations = new ArrayList<DelegateTypeBo>();
2049    
2050                    roleBo.setId(identityManagementRoleDocument.getRoleId());
2051                    roleBo.setKimTypeId(identityManagementRoleDocument.getRoleTypeId());
2052                    roleBo.setNamespaceCode(identityManagementRoleDocument.getRoleNamespace());
2053                    roleBo.setName(identityManagementRoleDocument.getRoleName());
2054                    roleBo.setDescription(identityManagementRoleDocument.getRoleDescription());
2055    
2056                    if (origRole == null) {
2057                            origRole = new RoleBo();
2058                            roleBo.setActive(true);
2059                    } else {
2060                            roleBo.setActive(identityManagementRoleDocument.isActive());
2061                            roleBo.setVersionNumber(origRole.getVersionNumber());
2062                Map<String, String> altCriteria = new HashMap<String, String>();
2063                altCriteria.put(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, roleId);
2064                            origRolePermissions = new ArrayList<RolePermissionBo>(getBusinessObjectService().findMatching(RolePermissionBo.class, altCriteria));
2065                origRoleResponsibilities = (List<RoleResponsibilityBo>)getBusinessObjectService().findMatching(RoleResponsibilityBo.class, altCriteria);
2066                            origRoleMembers = (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, altCriteria);
2067                            origRoleDelegations = (List<DelegateTypeBo>)getBusinessObjectService().findMatching(DelegateTypeBo.class, altCriteria);
2068                    }
2069    
2070                    if( getKimTypeInfoService().getKimType(identityManagementRoleDocument.getRoleTypeId()) == null ) {
2071                            LOG.error( "Kim type not found for:"+identityManagementRoleDocument.getRoleTypeId(), new Throwable() );
2072                    }
2073    
2074                    List<PersistableBusinessObject> bos = new ArrayList<PersistableBusinessObject>();
2075    
2076            bos.add(roleBo);
2077                    bos.addAll(getRolePermissions(identityManagementRoleDocument, origRolePermissions));
2078                    bos.addAll(getRoleResponsibilities(identityManagementRoleDocument, origRoleResponsibilities));
2079                    bos.addAll(getRoleResponsibilitiesActions(identityManagementRoleDocument));
2080                    String initiatorPrincipalId = getInitiatorPrincipalId(identityManagementRoleDocument);
2081    
2082                    if(canAssignToRole(identityManagementRoleDocument, initiatorPrincipalId)){
2083                            List<RoleMemberBo> newRoleMembersList = getRoleMembers(identityManagementRoleDocument, origRoleMembers);
2084                roleBo.setMembers(newRoleMembersList);
2085    
2086                            bos.addAll(getRoleMemberResponsibilityActions(newRoleMembersList));
2087                            //bos.addAll(getRoleMemberResponsibilityActions(identityManagementRoleDocument));
2088                            bos.addAll(getRoleDelegations(identityManagementRoleDocument, origRoleDelegations));
2089                    }
2090           // bos.add(roleBo);
2091                    getBusinessObjectService().save(bos);
2092                    KimImplServiceLocator.getResponsibilityInternalService().updateActionRequestsForResponsibilityChange(getChangedRoleResponsibilityIds(identityManagementRoleDocument, origRoleResponsibilities));
2093                    if(!roleBo.isActive()){
2094                            // when a role is inactivated, inactivate the memberships of principals, groups, and roles in
2095                            // that role, delegations, and delegation members, and that roles memberships in other roles
2096                            KimImplServiceLocator.getRoleInternalService().roleInactivated(identityManagementRoleDocument.getRoleId());
2097                    }
2098            }
2099    
2100            protected List<RolePermissionBo> getRolePermissions(
2101                            IdentityManagementRoleDocument identityManagementRoleDocument, List<RolePermissionBo> origRolePermissions){
2102                    List<RolePermissionBo> rolePermissions = new ArrayList<RolePermissionBo>();
2103                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getPermissions())){
2104                            for(KimDocumentRolePermission documentRolePermission: identityManagementRoleDocument.getPermissions()){
2105                                    RolePermissionBo newRolePermission = new RolePermissionBo();
2106                                    newRolePermission.setId(documentRolePermission.getRolePermissionId());
2107                                    newRolePermission.setRoleId(identityManagementRoleDocument.getRoleId());
2108                                    newRolePermission.setPermissionId(documentRolePermission.getPermissionId());
2109                                    newRolePermission.setActive( documentRolePermission.isActive() );
2110    
2111                                    newRolePermission.setActive(documentRolePermission.isActive());
2112                                    if (ObjectUtils.isNotNull(origRolePermissions)) {
2113                        for (RolePermissionBo origPermissionImpl : origRolePermissions) {
2114                            if (!StringUtils.equals(origPermissionImpl.getRoleId(), newRolePermission.getRoleId())
2115                                    && StringUtils.equals(origPermissionImpl.getPermissionId(), newRolePermission.getPermissionId())
2116                                    && origPermissionImpl.isActive()
2117                                    && newRolePermission.isActive()) {
2118                                                            newRolePermission.setId(origPermissionImpl.getId());
2119                                                    }
2120                                                    if(origPermissionImpl.getId()!=null && StringUtils.equals(origPermissionImpl.getId(), newRolePermission.getId())){
2121                                                            newRolePermission.setVersionNumber(origPermissionImpl.getVersionNumber());
2122                                newRolePermission.setObjectId(origPermissionImpl.getObjectId());
2123                                                    }
2124                                            }
2125                                    }
2126                                    rolePermissions.add(newRolePermission);
2127                            }
2128                    }
2129                    return rolePermissions;
2130            }
2131    
2132            protected List<RoleResponsibilityBo> getRoleResponsibilities(
2133                            IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleResponsibilityBo> origRoleResponsibilities){
2134                    List<RoleResponsibilityBo> roleResponsibilities = new ArrayList<RoleResponsibilityBo>();
2135                    RoleResponsibilityBo newRoleResponsibility;
2136                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2137                            for(KimDocumentRoleResponsibility documentRoleResponsibility: identityManagementRoleDocument.getResponsibilities()){
2138                                    newRoleResponsibility = new RoleResponsibilityBo();
2139                                    KimCommonUtilsInternal.copyProperties(newRoleResponsibility, documentRoleResponsibility);
2140                                    newRoleResponsibility.setActive(documentRoleResponsibility.isActive());
2141                                    newRoleResponsibility.setRoleId(identityManagementRoleDocument.getRoleId());
2142                                    if(ObjectUtils.isNotNull(origRoleResponsibilities)){
2143                                            for(RoleResponsibilityBo origResponsibilityImpl: origRoleResponsibilities){
2144                                                    if(!StringUtils.equals(origResponsibilityImpl.getRoleId(), newRoleResponsibility.getRoleId()) &&
2145                                                                    StringUtils.equals(origResponsibilityImpl.getResponsibilityId(), newRoleResponsibility.getResponsibilityId()) &&
2146                                                                    !origResponsibilityImpl.isActive() && newRoleResponsibility.isActive()){
2147                                                            newRoleResponsibility.setRoleResponsibilityId(origResponsibilityImpl.getRoleResponsibilityId());
2148                                                    }
2149                                                    if(origResponsibilityImpl.getRoleResponsibilityId()!=null && StringUtils.equals(origResponsibilityImpl.getRoleResponsibilityId(), newRoleResponsibility.getRoleResponsibilityId())) {
2150                                newRoleResponsibility.setVersionNumber(origResponsibilityImpl.getVersionNumber());
2151                                newRoleResponsibility.setObjectId(origResponsibilityImpl.getObjectId());
2152                            }
2153                                            }
2154                                    }
2155                                    roleResponsibilities.add(newRoleResponsibility);
2156                            }
2157                    }
2158                    return roleResponsibilities;
2159            }
2160    
2161    
2162            protected List <RoleResponsibilityActionBo> getRoleResponsibilitiesActions(
2163                            IdentityManagementRoleDocument identityManagementRoleDocument){
2164                    List <RoleResponsibilityActionBo>  roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2165                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2166                    // loop over the responsibilities assigned to the role
2167                            for(KimDocumentRoleResponsibility roleResponsibility : identityManagementRoleDocument.getResponsibilities()){
2168                                    // only process if the actions are not assigned at the role member level
2169                                    if(!getResponsibilityInternalService().areActionsAtAssignmentLevelById(roleResponsibility.getResponsibilityId())){
2170                                            List<KimDocumentRoleResponsibilityAction> documentRoleResponsibilityActions = roleResponsibility.getRoleRspActions();
2171                                            if( ObjectUtils.isNotNull(documentRoleResponsibilityActions)
2172                                                            && !documentRoleResponsibilityActions.isEmpty()
2173                                                            && StringUtils.isNotBlank(documentRoleResponsibilityActions.get(0).getRoleResponsibilityActionId() ) ) {
2174                                                    RoleResponsibilityActionBo roleRspAction = new RoleResponsibilityActionBo();
2175                                                    roleRspAction.setId(documentRoleResponsibilityActions.get(0).getRoleResponsibilityActionId());
2176                                                    roleRspAction.setActionPolicyCode(documentRoleResponsibilityActions.get(0).getActionPolicyCode());
2177                                                    roleRspAction.setActionTypeCode(documentRoleResponsibilityActions.get(0).getActionTypeCode());
2178                                                    roleRspAction.setPriorityNumber(documentRoleResponsibilityActions.get(0).getPriorityNumber());
2179                                                    roleRspAction.setForceAction(documentRoleResponsibilityActions.get(0).isForceAction());
2180                                                    roleRspAction.setRoleMemberId("*");
2181                                                    roleRspAction.setRoleResponsibilityId(documentRoleResponsibilityActions.get(0).getRoleResponsibilityId());
2182                                                    updateResponsibilityActionVersionNumber(roleRspAction, getRoleResponsibilityActionImpl(roleRspAction.getId()));
2183                                                    roleRspActions.add(roleRspAction);
2184                                            }
2185                                    }
2186                            }
2187                    }
2188                    return roleRspActions;
2189            }
2190    
2191            // FIXME: This should be pulling by the PK, not using another method which pulls multiple records and then finds
2192            // the right one here!
2193            protected void updateResponsibilityActionVersionNumber(RoleResponsibilityActionBo newRoleRspAction,
2194                            RoleResponsibilityActionBo origRoleRespActionImpl){
2195                    if(ObjectUtils.isNotNull(origRoleRespActionImpl)){
2196                if(origRoleRespActionImpl.getId()!=null && StringUtils.equals(origRoleRespActionImpl.getId(), newRoleRspAction.getId())) {
2197                    newRoleRspAction.setVersionNumber(origRoleRespActionImpl.getVersionNumber());
2198                    newRoleRspAction.setObjectId(origRoleRespActionImpl.getObjectId());
2199                }
2200                    }
2201            }
2202    
2203            protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(List<RoleMemberBo> newRoleMembersList){
2204                    List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2205                    if(ObjectUtils.isNotNull(newRoleMembersList)){
2206                            for(RoleMemberBo roleMember: newRoleMembersList){
2207                                    roleRspActions.addAll(roleMember.getRoleRspActions());
2208                            }
2209                    }
2210                    return roleRspActions;
2211            }
2212    
2213            /*protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(IdentityManagementRoleDocument identityManagementRoleDocument){
2214                    List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2215                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
2216                            for(KimDocumentRoleMember roleMember: identityManagementRoleDocument.getMembers()){
2217                                    for(KimDocumentRoleResponsibilityAction roleRspAction : roleMember.getRoleRspActions()){
2218                                            RoleResponsibilityActionBo entRoleRspAction = new RoleResponsibilityActionBo();
2219                                            entRoleRspAction.setId(roleRspAction.getRoleResponsibilityActionId());
2220                                            entRoleRspAction.setActionPolicyCode(roleRspAction.getActionPolicyCode());
2221                                            entRoleRspAction.setActionTypeCode(roleRspAction.getActionTypeCode());
2222                                            entRoleRspAction.setPriorityNumber(roleRspAction.getPriorityNumber());
2223                                            entRoleRspAction.setRoleMemberId(roleRspAction.getRoleMemberId());
2224                                            entRoleRspAction.setForceAction(roleRspAction.isForceAction());
2225                                            entRoleRspAction.setRoleResponsibilityId(roleRspAction.getRoleResponsibilityId());
2226                                            List<RoleResponsibilityActionBo> actions = getRoleRspActions(roleMember.getRoleMemberId());
2227                                            if(ObjectUtils.isNotNull(actions)){
2228                                                    for(RoleResponsibilityActionBo orgRspAction : actions) {
2229                                                            if (orgRspAction.getId()!=null && StringUtils.equals(orgRspAction.getId(), roleRspAction.getRoleResponsibilityActionId())) {
2230                                                                    entRoleRspAction.setVersionNumber(orgRspAction.getVersionNumber());
2231                                                            }
2232                                                    }
2233                                            }
2234                                            roleRspActions.add(entRoleRspAction);
2235                                    }
2236                            }
2237                    }
2238                    return roleRspActions;
2239            }*/
2240    
2241        protected List<RoleMemberBo> getRoleMembers(IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleMemberBo> origRoleMembers){
2242            List<RoleMemberBo> roleMembers = new ArrayList<RoleMemberBo>();
2243            RoleMemberBo newRoleMember;
2244            RoleMemberBo origRoleMemberImplTemp;
2245            List<RoleMemberAttributeDataBo> origAttributes;
2246            boolean activatingInactive = false;
2247            String newRoleMemberIdAssigned = "";
2248    
2249            identityManagementRoleDocument.setKimType(KimApiServiceLocator.getKimTypeInfoService().getKimType(identityManagementRoleDocument.getRoleTypeId()));
2250            KimTypeService kimTypeService = KimFrameworkServiceLocator.getKimTypeService(identityManagementRoleDocument.getKimType());
2251    
2252            if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getMembers())){
2253                for(KimDocumentRoleMember documentRoleMember: identityManagementRoleDocument.getMembers()){
2254                    origRoleMemberImplTemp = null;
2255    
2256                    newRoleMember = new RoleMemberBo();
2257                    KimCommonUtilsInternal.copyProperties(newRoleMember, documentRoleMember);
2258                    newRoleMember.setId(documentRoleMember.getRoleMemberId());
2259                    newRoleMember.setRoleId(identityManagementRoleDocument.getRoleId());
2260                    if(ObjectUtils.isNotNull(origRoleMembers)){
2261                        for(RoleMemberBo origRoleMemberImpl: origRoleMembers){
2262                            if((origRoleMemberImpl.getRoleId()!=null && StringUtils.equals(origRoleMemberImpl.getRoleId(), newRoleMember.getRoleId())) &&
2263                                (origRoleMemberImpl.getMemberId()!=null && StringUtils.equals(origRoleMemberImpl.getMemberId(), newRoleMember.getMemberId())) &&
2264                                (origRoleMemberImpl.getType()!=null && org.apache.commons.lang.ObjectUtils.equals(origRoleMemberImpl.getType(), newRoleMember.getType())) &&
2265                                !origRoleMemberImpl.isActive() &&
2266                                !kimTypeService.validateUniqueAttributes(
2267                                        identityManagementRoleDocument.getKimType().getId(),
2268                                        documentRoleMember.getQualifierAsMap(), origRoleMemberImpl.getAttributes()).isEmpty()) {
2269    
2270                                //TODO: verify if you want to add  && newRoleMember.isActive() condition to if...
2271    
2272                                newRoleMemberIdAssigned = newRoleMember.getId();
2273                                newRoleMember.setId(origRoleMemberImpl.getId());
2274                                activatingInactive = true;
2275                            }
2276                            if(origRoleMemberImpl.getId()!=null && StringUtils.equals(origRoleMemberImpl.getId(), newRoleMember.getId())){
2277                                newRoleMember.setVersionNumber(origRoleMemberImpl.getVersionNumber());
2278                                origRoleMemberImplTemp = origRoleMemberImpl;
2279                            }
2280                        }
2281                    }
2282                    origAttributes = (origRoleMemberImplTemp==null || origRoleMemberImplTemp.getAttributes()==null)?
2283                                        new ArrayList<RoleMemberAttributeDataBo>():origRoleMemberImplTemp.getAttributeDetails();
2284                    newRoleMember.setActiveFromDateValue(documentRoleMember.getActiveFromDate());
2285                    newRoleMember.setActiveToDateValue(documentRoleMember.getActiveToDate());
2286                    newRoleMember.setAttributeDetails(getRoleMemberAttributeData(documentRoleMember.getQualifiers(), origAttributes, activatingInactive, newRoleMemberIdAssigned));
2287                    newRoleMember.setRoleRspActions(getRoleMemberResponsibilityActions(documentRoleMember, origRoleMemberImplTemp, activatingInactive, newRoleMemberIdAssigned));
2288                    newRoleMember.setType(MemberType.fromCode(documentRoleMember.getMemberTypeCode()));
2289                    roleMembers.add(newRoleMember);
2290                    activatingInactive = false;
2291                }
2292            }
2293            return roleMembers;
2294        }
2295    
2296            protected List<RoleResponsibilityActionBo> getRoleMemberResponsibilityActions(
2297                            KimDocumentRoleMember documentRoleMember, RoleMemberBo origRoleMemberImplTemp, boolean activatingInactive, String newRoleMemberIdAssigned){
2298                    List<RoleResponsibilityActionBo> roleRspActions = new ArrayList<RoleResponsibilityActionBo>();
2299                    List<RoleResponsibilityActionBo> origActions = new ArrayList<RoleResponsibilityActionBo>();
2300                    if(origRoleMemberImplTemp!=null) {
2301                            origActions = getRoleRspActions(origRoleMemberImplTemp.getId());
2302                    }
2303                    if(CollectionUtils.isNotEmpty(documentRoleMember.getRoleRspActions())){
2304                            for(KimDocumentRoleResponsibilityAction roleRspAction : documentRoleMember.getRoleRspActions()){
2305                                    RoleResponsibilityActionBo newRoleRspAction = new RoleResponsibilityActionBo();
2306                                    newRoleRspAction.setId(roleRspAction.getRoleResponsibilityActionId());
2307                                    newRoleRspAction.setActionPolicyCode(roleRspAction.getActionPolicyCode());
2308                                    newRoleRspAction.setActionTypeCode(roleRspAction.getActionTypeCode());
2309                                    newRoleRspAction.setPriorityNumber(roleRspAction.getPriorityNumber());
2310                                    newRoleRspAction.setRoleMemberId(roleRspAction.getRoleMemberId());
2311                                    newRoleRspAction.setForceAction(roleRspAction.isForceAction());
2312                                    newRoleRspAction.setRoleResponsibilityId("*");
2313                                    if(ObjectUtils.isNotNull(origActions)){
2314                                            for(RoleResponsibilityActionBo origRspAction: origActions) {
2315                                                    if(activatingInactive && StringUtils.equals(origRspAction.getRoleResponsibilityId(), newRoleRspAction.getRoleResponsibilityId()) &&
2316                                                                    StringUtils.equals(newRoleRspAction.getRoleMemberId(), newRoleMemberIdAssigned)){
2317                                                            newRoleRspAction.setRoleMemberId(origRspAction.getRoleMemberId());
2318                                                            newRoleRspAction.setId(origRspAction.getId());
2319                                                    }
2320                                                    if (origRspAction.getId()!=null && StringUtils.equals(origRspAction.getId(), newRoleRspAction.getId())) {
2321                                                            newRoleRspAction.setVersionNumber(origRspAction.getVersionNumber());
2322                                                    }
2323                                            }
2324                                    }
2325                                    roleRspActions.add(newRoleRspAction);
2326                            }
2327                    }
2328                    return roleRspActions;
2329            }
2330    
2331            protected List<RoleMemberAttributeDataBo> getRoleMemberAttributeData(List<KimDocumentRoleQualifier> qualifiers,
2332                            List<RoleMemberAttributeDataBo> origAttributes, boolean activatingInactive, String newRoleMemberIdAssigned){
2333                    List<RoleMemberAttributeDataBo> roleMemberAttributeDataList = new ArrayList<RoleMemberAttributeDataBo>();
2334                    RoleMemberAttributeDataBo newRoleMemberAttributeData;
2335                    if(CollectionUtils.isNotEmpty(qualifiers)){
2336                            for(KimDocumentRoleQualifier memberRoleQualifier: qualifiers){
2337                                    if(StringUtils.isNotBlank(memberRoleQualifier.getAttrVal())){
2338                                            newRoleMemberAttributeData = new RoleMemberAttributeDataBo();
2339                                            newRoleMemberAttributeData.setId(memberRoleQualifier.getAttrDataId());
2340                                            newRoleMemberAttributeData.setAttributeValue(memberRoleQualifier.getAttrVal());
2341                                            newRoleMemberAttributeData.setAssignedToId(memberRoleQualifier.getRoleMemberId());
2342                                            newRoleMemberAttributeData.setKimTypeId(memberRoleQualifier.getKimTypId());
2343                                            newRoleMemberAttributeData.setKimAttributeId(memberRoleQualifier.getKimAttrDefnId());
2344    
2345                                            updateAttrValIfNecessary(newRoleMemberAttributeData);
2346    
2347                                            if(ObjectUtils.isNotNull(origAttributes)){
2348                                                    for(RoleMemberAttributeDataBo origAttribute: origAttributes){
2349                                                            if(activatingInactive && StringUtils.equals(origAttribute.getKimAttributeId(), newRoleMemberAttributeData.getKimAttributeId()) &&
2350                                                                            StringUtils.equals(newRoleMemberAttributeData.getAssignedToId(), newRoleMemberIdAssigned)){
2351                                                                    newRoleMemberAttributeData.setAssignedToId(origAttribute.getAssignedToId());
2352                                                                    newRoleMemberAttributeData.setId(origAttribute.getId());
2353                                                            }
2354                                                            if(origAttribute.getId()!=null && StringUtils.equals(origAttribute.getId(), newRoleMemberAttributeData.getId())){
2355                                                                    newRoleMemberAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2356                                                            }
2357                                                    }
2358                                            }
2359                                            roleMemberAttributeDataList.add(newRoleMemberAttributeData);
2360                                    }
2361                            }
2362                    }
2363                    return roleMemberAttributeDataList;
2364            }
2365    
2366            /**
2367             * Determines if the attribute value on the attribute data should be updated; if so, it performs some attribute value formatting.
2368             * In the default implementation, this method formats checkbox controls
2369             *
2370             * @param roleMemberAttributeData a role member qualifier attribute to update
2371             */
2372            protected void updateAttrValIfNecessary(RoleMemberAttributeDataBo roleMemberAttributeData) {
2373                    if (doCheckboxLogic(roleMemberAttributeData.getKimTypeId(), roleMemberAttributeData.getKimAttributeId())) {
2374                            convertCheckboxAttributeData(roleMemberAttributeData);
2375                    }
2376            }
2377    
2378            protected void formatAttrValIfNecessary(KimDocumentRoleQualifier roleQualifier) {
2379            if (doCheckboxLogic(roleQualifier.getKimTypId(), roleQualifier.getKimAttrDefnId())) {
2380                formatCheckboxAttributeData(roleQualifier);
2381            }
2382            }
2383    
2384        private boolean doCheckboxLogic(String kimTypeId, String attrId) {
2385            final KimAttributeField attributeDefinition = getAttributeDefinition(kimTypeId, attrId);
2386            return attributeDefinition != null
2387                    && attributeDefinition.getAttributeField().getControl() != null
2388                    && (attributeDefinition.getAttributeField().getControl() instanceof RemotableCheckboxGroup
2389                            || attributeDefinition.getAttributeField().getControl() instanceof RemotableCheckbox);
2390        }
2391    
2392            protected void formatCheckboxAttributeData(KimDocumentRoleQualifier roleQualifier) {
2393                    if (roleQualifier.getAttrVal().equals(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE)) {
2394                            roleQualifier.setAttrVal(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY);
2395                    } else if (roleQualifier.getAttrVal().equals(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE)) {
2396                            roleQualifier.setAttrVal(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY);
2397                    }
2398            }
2399    
2400            /**
2401             * Finds the KNS attribute used to render the given KimAttributeData
2402             *
2403         * @return the KNS attribute used to render that qualifier, or null if the AttributeDefinition cannot be determined
2404             */
2405            protected KimAttributeField getAttributeDefinition(String kimTypId, String attrDefnId) {
2406                    final KimType type = getKimTypeInfoService().getKimType(kimTypId);
2407                    if (type != null) {
2408                            final KimTypeService typeService = (KimTypeService) KimImplServiceLocator.getBean(type.getServiceName());
2409                            if (typeService != null) {
2410                                    final KimTypeAttribute attributeInfo = type.getAttributeDefinitionById(attrDefnId);
2411                                    if (attributeInfo != null) {
2412                                            final List<KimAttributeField> attributeMap = typeService.getAttributeDefinitions(type.getId());
2413                                            if (attributeMap != null) {
2414                                                    return DataDictionaryTypeServiceHelper.findAttributeField(
2415                                    attributeInfo.getKimAttribute().getAttributeName(), attributeMap);
2416                                            }
2417                                    }
2418                            }
2419                    }
2420                    return null;
2421            }
2422    
2423            /**
2424             * Formats the attribute value on this checkbox attribute, changing "on" to "Y" and "off" to "N"
2425             *
2426             * @param roleMemberAttributeData the attribute data to format the attribute value of
2427             */
2428            protected void convertCheckboxAttributeData(RoleMemberAttributeDataBo roleMemberAttributeData) {
2429                    if (roleMemberAttributeData.getAttributeValue().equalsIgnoreCase(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY)) {
2430                            roleMemberAttributeData.setAttributeValue(KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE);
2431                    } else if (roleMemberAttributeData.getAttributeValue().equalsIgnoreCase(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY)) {
2432                            roleMemberAttributeData.setAttributeValue(KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE);
2433                    }
2434            }
2435    
2436            protected List<DelegateTypeBo> getRoleDelegations(IdentityManagementRoleDocument identityManagementRoleDocument, List<DelegateTypeBo> origDelegations){
2437                    List<DelegateTypeBo> kimDelegations = new ArrayList<DelegateTypeBo>();
2438                    DelegateTypeBo newKimDelegation;
2439                    DelegateTypeBo origDelegationImplTemp = null;
2440                    List<DelegateMemberBo> origMembers;
2441                    boolean activatingInactive = false;
2442                    String newDelegationIdAssigned = "";
2443                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getDelegations())){
2444                            for(RoleDocumentDelegation roleDocumentDelegation: identityManagementRoleDocument.getDelegations()){
2445                                    newKimDelegation = new DelegateTypeBo();
2446                                    KimCommonUtilsInternal.copyProperties(newKimDelegation, roleDocumentDelegation);
2447                                    newKimDelegation.setRoleId(identityManagementRoleDocument.getRoleId());
2448                                    if(ObjectUtils.isNotNull(origDelegations)){
2449                                            for(DelegateTypeBo origDelegationImpl: origDelegations){
2450                                                    if(StringUtils.equals(origDelegationImpl.getRoleId(), newKimDelegation.getRoleId()) &&
2451                                                                    StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId())){
2452                                                            //TODO: verify if you want to add  && newRoleMember.isActive() condition to if...
2453                                                            newDelegationIdAssigned = newKimDelegation.getDelegationId();
2454                                                            newKimDelegation.setDelegationId(origDelegationImpl.getDelegationId());
2455                                                            activatingInactive = true;
2456                                                    }
2457                                                    if(origDelegationImpl.getDelegationId()!=null && StringUtils.equals(origDelegationImpl.getDelegationId(), newKimDelegation.getDelegationId())){
2458                                                            newKimDelegation.setVersionNumber(origDelegationImpl.getVersionNumber());
2459                                                            origDelegationImplTemp = origDelegationImpl;
2460                                                    }
2461                                            }
2462                                    }
2463                                    origMembers = (origDelegationImplTemp == null || origDelegationImplTemp.getMembers()==null)?
2464                                                                            new ArrayList<DelegateMemberBo>():origDelegationImplTemp.getMembers();
2465                                    newKimDelegation.setMembers(getDelegationMembers(roleDocumentDelegation.getMembers(), origMembers, activatingInactive, newDelegationIdAssigned));
2466                    kimDelegations.add(newKimDelegation);
2467                                    activatingInactive = false;
2468                            }
2469                    }
2470                    return kimDelegations;
2471            }
2472    
2473            protected List<DelegateMemberBo> getDelegationMembers(List<RoleDocumentDelegationMember> delegationMembers,
2474                            List<DelegateMemberBo> origDelegationMembers, boolean activatingInactive, String newDelegationIdAssigned){
2475                    List<DelegateMemberBo> delegationsMembersList = new ArrayList<DelegateMemberBo>();
2476                    DelegateMemberBo newDelegationMemberImpl;
2477                    DelegateMemberBo origDelegationMemberImplTemp = null;
2478                    List<DelegateMemberAttributeDataBo> origAttributes;
2479                    String delegationMemberId = "";
2480                    if(CollectionUtils.isNotEmpty(delegationMembers)){
2481                            for(RoleDocumentDelegationMember delegationMember: delegationMembers){
2482                                    newDelegationMemberImpl = new DelegateMemberBo();
2483                                    KimCommonUtilsInternal.copyProperties(newDelegationMemberImpl, delegationMember);
2484                    newDelegationMemberImpl.setType(MemberType.fromCode(delegationMember.getMemberTypeCode()));
2485                                    if(ObjectUtils.isNotNull(origDelegationMembers)){
2486                                            for(DelegateMemberBo origDelegationMember: origDelegationMembers){
2487                                                    if(activatingInactive && StringUtils.equals(origDelegationMember.getMemberId(), newDelegationMemberImpl.getMemberId()) &&
2488                                                                    StringUtils.equals(newDelegationMemberImpl.getDelegationId(), newDelegationIdAssigned) &&
2489                                                                    !origDelegationMember.isActive(new Timestamp(System.currentTimeMillis()))){
2490                                                            newDelegationMemberImpl.setDelegationId(origDelegationMember.getDelegationId());
2491                                                            delegationMemberId = newDelegationMemberImpl.getDelegationMemberId();
2492                                                            newDelegationMemberImpl.setDelegationMemberId(origDelegationMember.getDelegationMemberId());
2493                                                    }
2494                                                    if(origDelegationMember.getDelegationMemberId()!=null && StringUtils.equals(origDelegationMember.getDelegationMemberId(), newDelegationMemberImpl.getDelegationMemberId())){
2495                                                            newDelegationMemberImpl.setVersionNumber(origDelegationMember.getVersionNumber());
2496                                                            origDelegationMemberImplTemp = origDelegationMember;
2497                                                    }
2498                                            }
2499                                    }
2500                                    origAttributes = (origDelegationMemberImplTemp==null || origDelegationMemberImplTemp.getAttributeDetails()==null)?
2501                                                    new ArrayList<DelegateMemberAttributeDataBo>():origDelegationMemberImplTemp.getAttributeDetails();
2502                                    newDelegationMemberImpl.setAttributeDetails(getDelegationMemberAttributeData(delegationMember.getQualifiers(), origAttributes, activatingInactive, delegationMemberId));
2503                                    newDelegationMemberImpl.setActiveFromDateValue(delegationMember.getActiveFromDate());
2504                    newDelegationMemberImpl.setActiveToDateValue(delegationMember.getActiveToDate());
2505                    delegationsMembersList.add(newDelegationMemberImpl);
2506                            }
2507                    }
2508                    return delegationsMembersList;
2509            }
2510    
2511            //TODO: implement logic same as role members - do not insert qualifiers with blank values
2512            protected List<DelegateMemberAttributeDataBo> getDelegationMemberAttributeData(
2513                            List<RoleDocumentDelegationMemberQualifier> qualifiers, List<DelegateMemberAttributeDataBo> origAttributes,
2514                            boolean activatingInactive, String delegationMemberId){
2515                    List<DelegateMemberAttributeDataBo> delegationMemberAttributeDataList = new ArrayList<DelegateMemberAttributeDataBo>();
2516                    DelegateMemberAttributeDataBo newDelegationMemberAttributeData;
2517                    if(CollectionUtils.isNotEmpty(qualifiers)){
2518                            for(RoleDocumentDelegationMemberQualifier memberRoleQualifier: qualifiers){
2519                                    if(StringUtils.isNotBlank(memberRoleQualifier.getAttrVal())){
2520                                            newDelegationMemberAttributeData = new DelegateMemberAttributeDataBo();
2521                                            newDelegationMemberAttributeData.setId(memberRoleQualifier.getAttrDataId());
2522                                            newDelegationMemberAttributeData.setAttributeValue(memberRoleQualifier.getAttrVal());
2523                                            newDelegationMemberAttributeData.setAssignedToId(memberRoleQualifier.getDelegationMemberId());
2524                                            newDelegationMemberAttributeData.setKimTypeId(memberRoleQualifier.getKimTypId());
2525                                            newDelegationMemberAttributeData.setKimAttributeId(memberRoleQualifier.getKimAttrDefnId());
2526                                            if(ObjectUtils.isNotNull(origAttributes)){
2527                                                    for(DelegateMemberAttributeDataBo origAttribute: origAttributes){
2528                                                            if(activatingInactive && StringUtils.equals(origAttribute.getKimAttributeId(), newDelegationMemberAttributeData.getKimAttributeId()) &&
2529                                                                            StringUtils.equals(newDelegationMemberAttributeData.getAssignedToId(), delegationMemberId)){
2530                                                                    newDelegationMemberAttributeData.setAssignedToId(origAttribute.getAssignedToId());
2531                                                                    newDelegationMemberAttributeData.setId(origAttribute.getId());
2532                                                            }
2533                                                            if(StringUtils.equals(origAttribute.getId(), newDelegationMemberAttributeData.getId())){
2534                                                                    newDelegationMemberAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2535                                                            }
2536                                                    }
2537                                            }
2538                                            delegationMemberAttributeDataList.add(newDelegationMemberAttributeData);
2539                                    }
2540                            }
2541                    }
2542                    return delegationMemberAttributeDataList;
2543            }
2544    
2545            /* Group document methods */
2546            public void loadGroupDoc(IdentityManagementGroupDocument identityManagementGroupDocument, Group groupInfo){
2547                    //Map<String, String> criteria = new HashMap<String, String>();
2548                    //criteria.put(KimApiConstants.PrimaryKeyConstants.GROUP_ID, groupInfo.getId());
2549                    //GroupImpl kimGroupImpl = (GroupImpl)
2550                    //      getBusinessObjectService().findByPrimaryKey(GroupImpl.class, criteria);
2551    
2552                    identityManagementGroupDocument.setGroupId(groupInfo.getId());
2553            KimType kimType = KimApiServiceLocator.getKimTypeInfoService().getKimType(groupInfo.getKimTypeId());
2554                    identityManagementGroupDocument.setKimType(kimType);
2555                    identityManagementGroupDocument.setGroupTypeName(kimType.getName());
2556                    identityManagementGroupDocument.setGroupTypeId(kimType.getId());
2557                    identityManagementGroupDocument.setGroupName(groupInfo.getName());
2558                    identityManagementGroupDocument.setGroupDescription(groupInfo.getDescription());
2559                    identityManagementGroupDocument.setActive(groupInfo.isActive());
2560                    identityManagementGroupDocument.setGroupNamespace(groupInfo.getNamespaceCode());
2561    
2562            List<GroupMember> members = new ArrayList(KimApiServiceLocator.getGroupService().getMembersOfGroup(groupInfo.getId()));
2563            identityManagementGroupDocument.setMembers(loadGroupMembers(identityManagementGroupDocument, members));
2564    
2565    
2566    
2567            identityManagementGroupDocument.setQualifiers(loadGroupQualifiers(identityManagementGroupDocument, groupInfo.getAttributes()));
2568                    identityManagementGroupDocument.setEditing(true);
2569            }
2570    
2571            protected static class GroupMemberNameComparator implements Comparator<GroupDocumentMember> {
2572                    /**
2573                     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
2574                     */
2575                    public int compare(GroupDocumentMember m1, GroupDocumentMember m2) {
2576                            return m1.getMemberName().compareToIgnoreCase(m2.getMemberName());
2577                    }
2578            }
2579    
2580            protected GroupMemberNameComparator groupMemberNameComparator = new GroupMemberNameComparator();
2581    
2582            protected List<GroupDocumentMember> loadGroupMembers(
2583                            IdentityManagementGroupDocument identityManagementGroupDocument, List<GroupMember> members){
2584                    List<GroupDocumentMember> pndMembers = new ArrayList<GroupDocumentMember>();
2585                    GroupDocumentMember pndMember = new GroupDocumentMember();
2586                    if(ObjectUtils.isNotNull(members)){
2587                            for(GroupMember member: members){
2588                                    pndMember = new GroupDocumentMember();
2589    
2590                                    pndMember.setActiveFromDate(member.getActiveFromDate() == null ? null : new Timestamp(member.getActiveFromDate().getMillis()));
2591                                    pndMember.setActiveToDate(member.getActiveToDate() == null ? null : new Timestamp(member.getActiveToDate().getMillis()));
2592                                    //pndMember.setActive(member.isActive());
2593                                    if(pndMember.isActive()){
2594                                            pndMember.setGroupMemberId(member.getMemberId());
2595                                            pndMember.setGroupId(member.getGroupId());
2596                                            pndMember.setMemberId(member.getMemberId());
2597                                            pndMember.setMemberName(getMemberName(member.getType(), member.getMemberId()));
2598                                            pndMember.setMemberFullName(getMemberFullName(member.getType(), member.getMemberId()));
2599                                            pndMember.setMemberTypeCode(member.getType().getCode());
2600                                            pndMember.setEdit(true);
2601                                            pndMembers.add(pndMember);
2602                                    }
2603                            }
2604                    }
2605                    Collections.sort(pndMembers, groupMemberNameComparator);
2606                    return pndMembers;
2607            }
2608    
2609            protected List<GroupDocumentQualifier> loadGroupQualifiers(IdentityManagementGroupDocument IdentityManagementGroupDocument,
2610                            Map<String, String> attributes){
2611                    List<GroupDocumentQualifier> pndGroupQualifiers = new ArrayList<GroupDocumentQualifier>();
2612                    GroupDocumentQualifier pndGroupQualifier = new GroupDocumentQualifier();
2613                    List<KimAttributeField> origAttributes = IdentityManagementGroupDocument.getDefinitions();
2614                    boolean attributePresent = false;
2615                    String origAttributeId;
2616                    if(origAttributes!=null){
2617    
2618                            for(KimAttributeField key: origAttributes) {
2619                                    origAttributeId = IdentityManagementGroupDocument.getKimAttributeDefnId(key);
2620                                    if(!attributes.isEmpty()){
2621    
2622                                            for(GroupAttributeBo groupQualifier: KimAttributeDataBo.createFrom(GroupAttributeBo.class, attributes, IdentityManagementGroupDocument.getGroupTypeId())){
2623                                                    if(origAttributeId!=null && ObjectUtils.isNotNull(groupQualifier.getKimAttribute()) &&
2624                                                                    StringUtils.equals(origAttributeId, groupQualifier.getKimAttribute().getId())){
2625                                                            pndGroupQualifier = new GroupDocumentQualifier();
2626                                                            KimCommonUtilsInternal.copyProperties(pndGroupQualifier, groupQualifier);
2627                                                            pndGroupQualifier.setAttrDataId(groupQualifier.getId());
2628                                                            pndGroupQualifier.setAttrVal(groupQualifier.getAttributeValue());
2629                                                            pndGroupQualifier.setKimAttrDefnId(groupQualifier.getKimAttribute().getId());
2630                                                            pndGroupQualifier.setKimTypId(groupQualifier.getKimType().getId());
2631                                                            pndGroupQualifier.setGroupId(groupQualifier.getAssignedToId());
2632                                                            pndGroupQualifiers.add(pndGroupQualifier);
2633                                                            attributePresent = true;
2634                                                    }
2635                                            }
2636                                    }
2637                                    if(!attributePresent){
2638                                            pndGroupQualifier = new GroupDocumentQualifier();
2639                                            pndGroupQualifier.setKimAttrDefnId(origAttributeId);
2640                                            pndGroupQualifiers.add(pndGroupQualifier);
2641                                    }
2642                                    attributePresent = false;
2643                            }
2644                    }
2645                    return pndGroupQualifiers;
2646            }
2647    
2648            /**
2649             * @see org.kuali.rice.kim.service.UiDocumentService#saveEntityPerson(IdentityManagementPersonDocument)
2650             */
2651            @SuppressWarnings("unchecked")
2652            public void saveGroup(IdentityManagementGroupDocument identityManagementGroupDocument) {
2653                    GroupBo kimGroup = new GroupBo();
2654                    Map<String, String> criteria = new HashMap<String, String>();
2655                    String groupId = identityManagementGroupDocument.getGroupId();
2656                    criteria.put("groupId", groupId);
2657                    GroupBo origGroup = (GroupBo)getBusinessObjectService().findBySinglePrimaryKey(GroupBo.class, groupId);
2658                    List<GroupMemberBo> origGroupMembers = new ArrayList<GroupMemberBo>();
2659                    if (ObjectUtils.isNull(origGroup)) {
2660                            origGroup = new GroupBo();
2661                            kimGroup.setActive(true);
2662                    } else {
2663                            kimGroup.setVersionNumber(origGroup.getVersionNumber());
2664                            //TODO: when a group is inactivated, inactivate the memberships of principals in that group
2665                            //and the memberships of that group in roles
2666                            kimGroup.setActive(identityManagementGroupDocument.isActive());
2667                            origGroupMembers = (List<GroupMemberBo>)getBusinessObjectService().findMatching(GroupMemberBo.class, criteria);
2668                    }
2669    
2670                    kimGroup.setId(identityManagementGroupDocument.getGroupId());
2671                    KimType kimType = getKimTypeInfoService().getKimType(identityManagementGroupDocument.getGroupTypeId());
2672                    if( kimType == null ) {
2673                            throw new RuntimeException("Kim type not found for:"+identityManagementGroupDocument.getGroupTypeId());
2674                    }
2675    
2676                    kimGroup.setKimTypeId(kimType.getId());
2677                    kimGroup.setNamespaceCode(identityManagementGroupDocument.getGroupNamespace());
2678                    kimGroup.setName(identityManagementGroupDocument.getGroupName());
2679                    kimGroup.setDescription(identityManagementGroupDocument.getGroupDescription());
2680                    kimGroup.setAttributeDetails(getGroupAttributeData(identityManagementGroupDocument, origGroup.getAttributeDetails()));
2681    
2682                    List<String> oldIds;
2683                    List<String> newIds;
2684                    oldIds = getGroupService().getMemberPrincipalIds(kimGroup.getId()); // for the actionList update
2685    
2686    
2687                    List<GroupMemberBo> newGroupMembersList = getGroupMembers(identityManagementGroupDocument, origGroupMembers);
2688                    kimGroup.setMembers(newGroupMembersList);  // add the new, complete list to the group
2689    
2690                    kimGroup = (GroupBo)getBusinessObjectService().save(kimGroup);
2691    
2692                    newIds = kimGroup.getMemberPrincipalIds();
2693                    //newIds = getGroupService().getMemberPrincipalIds(kimGroup.getGroupId()); // for the action list update
2694    
2695                    // Do an async update of the action list for the updated groups
2696                    org.kuali.rice.kim.service.KIMServiceLocatorInternal.getGroupInternalService().updateForWorkgroupChange(kimGroup.getId(), oldIds, newIds);
2697                    if(!kimGroup.isActive()){
2698                            // when a group is inactivated, inactivate the memberships of principals in that group
2699                            // and the memberships of that group in roles
2700                            KimImplServiceLocator.getRoleInternalService().groupInactivated(identityManagementGroupDocument.getGroupId());
2701                    }
2702    
2703            }
2704    
2705            protected List<GroupMemberBo> getGroupMembers(IdentityManagementGroupDocument identityManagementGroupDocument, List<GroupMemberBo> origGroupMembers){
2706                    List<GroupMemberBo> groupMembers = new ArrayList<GroupMemberBo>();
2707                    GroupMemberBo newGroupMember;
2708                    if(CollectionUtils.isNotEmpty(identityManagementGroupDocument.getMembers())){
2709                            for(GroupDocumentMember documentGroupMember: identityManagementGroupDocument.getMembers()){
2710                                    newGroupMember = new GroupMemberBo();
2711                                    //KimCommonUtilsInternalInternal.copyProperties(newGroupMember, documentGroupMember);
2712                    //copy properties manually for now until new BO created for DocumentGroupMember
2713    
2714                                    newGroupMember.setGroupId(identityManagementGroupDocument.getGroupId());
2715                    newGroupMember.setActiveFromDateValue(documentGroupMember.getActiveFromDate());
2716                    newGroupMember.setActiveToDateValue(documentGroupMember.getActiveToDate());
2717                    newGroupMember.setMemberId(documentGroupMember.getMemberId());
2718                    newGroupMember.setTypeCode(documentGroupMember.getMemberTypeCode());
2719                                    if(ObjectUtils.isNotNull(origGroupMembers)){
2720                                            for(GroupMemberBo origGroupMemberImpl: origGroupMembers){
2721                                                    if(StringUtils.equals(origGroupMemberImpl.getGroupId(), newGroupMember.getGroupId()) &&
2722                                                                    StringUtils.equals(origGroupMemberImpl.getMemberId(), newGroupMember.getMemberId()) &&
2723                                                                    !origGroupMemberImpl.isActive(new Timestamp(System.currentTimeMillis()))){
2724                                                            //TODO: verify if you want to add  && newGroupMember.isActive() condition to if...
2725                                                            newGroupMember.setMemberId(origGroupMemberImpl.getMemberId());
2726                                                    }
2727                            if(StringUtils.equals(origGroupMemberImpl.getGroupId(), newGroupMember.getGroupId()) &&
2728                                                                    StringUtils.equals(origGroupMemberImpl.getMemberId(), newGroupMember.getMemberId()) &&
2729                                                                    origGroupMemberImpl.isActive(new Timestamp(System.currentTimeMillis()))){
2730                                                            newGroupMember.setId(origGroupMemberImpl.getId());
2731                                newGroupMember.setVersionNumber(origGroupMemberImpl.getVersionNumber());
2732                                                    }
2733                                            }
2734                                    }
2735                                    groupMembers.add(newGroupMember);
2736                            }
2737                    }
2738                    return groupMembers;
2739            }
2740    
2741            protected List<GroupAttributeBo> getGroupAttributeData(IdentityManagementGroupDocument identityManagementGroupDocument,
2742                            List<GroupAttributeBo> origAttributes){
2743                    List<GroupAttributeBo> groupAttributeDataList = new ArrayList<GroupAttributeBo>();
2744                    GroupAttributeBo newGroupAttributeData;
2745                    if(CollectionUtils.isNotEmpty(identityManagementGroupDocument.getQualifiers())){
2746                            for(GroupDocumentQualifier groupQualifier: identityManagementGroupDocument.getQualifiers()){
2747                                    if(StringUtils.isNotBlank(groupQualifier.getAttrVal())){
2748                                            newGroupAttributeData = new GroupAttributeBo();
2749                                            newGroupAttributeData.setId(groupQualifier.getAttrDataId());
2750                                            newGroupAttributeData.setAttributeValue(groupQualifier.getAttrVal());
2751                                            newGroupAttributeData.setAssignedToId(groupQualifier.getGroupId());
2752                                            newGroupAttributeData.setKimTypeId(groupQualifier.getKimTypId());
2753                                            newGroupAttributeData.setKimAttributeId(groupQualifier.getKimAttrDefnId());
2754                                            if(ObjectUtils.isNotNull(origAttributes)){
2755                                                    for(GroupAttributeBo origAttribute: origAttributes){
2756                                                            if(StringUtils.equals(origAttribute.getKimAttributeId(), newGroupAttributeData.getKimAttributeId()) &&
2757                                                                            StringUtils.equals(newGroupAttributeData.getAssignedToId(), origAttribute.getAssignedToId())){
2758                                                                newGroupAttributeData.setId(origAttribute.getId());
2759                                                            }
2760                                                            if(origAttribute.getId()!=null && StringUtils.equals(origAttribute.getId(), newGroupAttributeData.getId())){
2761                                                                newGroupAttributeData.setVersionNumber(origAttribute.getVersionNumber());
2762                                                            }
2763                                                    }
2764                                            }
2765                                            groupAttributeDataList.add(newGroupAttributeData);
2766                                    }
2767                            }
2768                    }
2769                    return groupAttributeDataList;
2770            }
2771    
2772        @SuppressWarnings("unchecked")
2773            public KimDocumentRoleMember getKimDocumentRoleMember(MemberType memberType, String memberId, String roleId){
2774            if(memberType == null || StringUtils.isEmpty(memberId) || StringUtils.isEmpty(roleId)) {
2775                    return null;
2776            }
2777            KimDocumentRoleMember documentRoleMember = new KimDocumentRoleMember();
2778            documentRoleMember.setRoleId(roleId);
2779            Map<String, String> criteria = new HashMap<String, String>();
2780            criteria.put("roleId", roleId);
2781            criteria.put("mbr_id", memberId);
2782    
2783            List<RoleMemberBo> matchingRoleMembers = (List<RoleMemberBo>)getBusinessObjectService().findMatching(RoleMemberBo.class, criteria);
2784            if (matchingRoleMembers==null || matchingRoleMembers.size()<1) { return null; }
2785    
2786            RoleMemberBo roleMemberImpl = matchingRoleMembers.get(0);
2787            documentRoleMember.setRoleMemberId(roleMemberImpl.getId());
2788            if(MemberType.PRINCIPAL.equals(memberType)){
2789                    Principal principal = getIdentityService().getPrincipal(memberId);
2790                    if (principal != null) {
2791                            documentRoleMember.setMemberId(principal.getPrincipalId());
2792                            documentRoleMember.setMemberName(principal.getPrincipalName());
2793                            documentRoleMember.setMemberTypeCode(MemberType.PRINCIPAL.getCode());
2794                    }               
2795            } else if(MemberType.GROUP.equals(memberType)){
2796                    Group group = getGroupService().getGroup(memberId);
2797                    if (group != null) {
2798                            documentRoleMember.setMemberNamespaceCode(group.getNamespaceCode());
2799                            documentRoleMember.setMemberId(group.getId());
2800                            documentRoleMember.setMemberName(group.getName());
2801                            documentRoleMember.setMemberTypeCode(MemberType.GROUP.getCode());
2802                    }
2803                    
2804            } else if(MemberType.ROLE.equals(memberType)){
2805                    Role role = getRoleService().getRole(memberId);
2806                    if (role != null) {
2807                            documentRoleMember.setMemberNamespaceCode(role.getNamespaceCode());
2808                            documentRoleMember.setMemberId(role.getId());
2809                            documentRoleMember.setMemberName(role.getName());
2810                            documentRoleMember.setMemberTypeCode(MemberType.ROLE.getCode());
2811                    }               
2812            }
2813            return documentRoleMember;
2814        }
2815    
2816        protected Set<String> getChangedRoleResponsibilityIds(
2817                            IdentityManagementRoleDocument identityManagementRoleDocument, List<RoleResponsibilityBo> origRoleResponsibilities){
2818                    Set<String> lRet = new HashSet<String>();
2819                    List<String> newResp = new ArrayList<String>();
2820                    List<String> oldResp = new ArrayList<String>();
2821                    if(CollectionUtils.isNotEmpty(identityManagementRoleDocument.getResponsibilities())){
2822                            for(KimDocumentRoleResponsibility documentRoleResponsibility: identityManagementRoleDocument.getResponsibilities()){
2823                                    newResp.add(documentRoleResponsibility.getResponsibilityId());
2824                            }
2825                    }
2826                    if(ObjectUtils.isNotNull(origRoleResponsibilities)){
2827                            for(RoleResponsibilityBo roleRespBo: origRoleResponsibilities){
2828                                    oldResp.add(roleRespBo.getResponsibilityId());
2829                            }
2830                    }
2831                    lRet.addAll(newResp);
2832                    lRet.addAll(oldResp);
2833    
2834                    return lRet;
2835            }
2836    
2837            public KimTypeInfoService getKimTypeInfoService() {
2838                    if ( kimTypeInfoService == null ) {
2839                            kimTypeInfoService = KimApiServiceLocator.getKimTypeInfoService();
2840                    }
2841                    return kimTypeInfoService;
2842            }
2843    
2844        public List<KimDocumentRoleMember> getRoleMembers(Map<String,String> fieldValues) {
2845            List<KimDocumentRoleMember> matchingRoleMembers = new ArrayList<KimDocumentRoleMember>();
2846            //Remove since they are KNS fieldValues and not BO
2847            fieldValues.remove(KRADConstants.BACK_LOCATION);
2848            fieldValues.remove(KRADConstants.DOC_FORM_KEY);
2849            fieldValues.remove(KRADConstants.DOC_NUM);
2850    
2851    
2852    
2853                    List<RoleMember> matchingRoleMembersTemp = getRoleService().findRoleMembers(toQuery(fieldValues)).getResults();
2854                    KimDocumentRoleMember matchingRoleMember;
2855                    BusinessObject roleMemberObject;
2856                    RoleMemberBo roleMemberBo;
2857                    if(CollectionUtils.isNotEmpty(matchingRoleMembersTemp)){
2858                            for(RoleMember roleMember: matchingRoleMembersTemp){
2859                                    roleMemberBo = getRoleMember(roleMember.getId());
2860                                    roleMemberObject = getMember(roleMemberBo.getType(), roleMemberBo.getMemberId());
2861                                    matchingRoleMember = new KimDocumentRoleMember();
2862                                    KimCommonUtilsInternal.copyProperties(matchingRoleMember, roleMemberBo);
2863                    matchingRoleMember.setMemberId(roleMemberBo.getMemberId());
2864                    matchingRoleMember.setRoleMemberId(roleMemberBo.getId());
2865                                    matchingRoleMember.setMemberName(getMemberName(roleMemberBo.getType(), roleMemberObject));
2866                                    matchingRoleMember.setMemberNamespaceCode(getMemberNamespaceCode(roleMemberBo.getType(), roleMemberObject));
2867                                    matchingRoleMember.setQualifiers(getQualifiers(roleMemberBo.getAttributeDetails()));
2868                                    matchingRoleMembers.add(matchingRoleMember);
2869                            }
2870                    }
2871                    return matchingRoleMembers;
2872        }
2873    
2874       private QueryByCriteria toQuery(Map<String,String> fieldValues) {
2875           String memberTypeCode = fieldValues.get(KIMPropertyConstants.KimMember.MEMBER_TYPE_CODE);
2876           String memberName = fieldValues.get(KimConstants.KimUIConstants.MEMBER_NAME);
2877           String memberNamespaceCode = fieldValues.get(KimConstants.KimUIConstants.MEMBER_NAMESPACE_CODE);
2878    
2879           if(StringUtils.isNotEmpty(memberName) || StringUtils.isNotEmpty(memberNamespaceCode)) {
2880                String memberId  = getMemberIdByName(MemberType.fromCode(memberTypeCode),memberNamespaceCode,memberName)  ;
2881               if(StringUtils.isNotEmpty(memberId)) {
2882                      fieldValues.put(KIMPropertyConstants.KimMember.MEMBER_ID, memberId);
2883               }
2884           }
2885    
2886           List<Predicate> pred = new ArrayList<Predicate>();
2887    
2888           pred.add(PredicateUtils.convertMapToPredicate(fieldValues));
2889           Predicate[] predicates = new Predicate[0];
2890           predicates = pred.toArray(predicates)  ;
2891            return QueryByCriteria.Builder.fromPredicates(predicates);
2892        }
2893    
2894        private List<KimDocumentRoleQualifier> getQualifiers(List<RoleMemberAttributeDataBo> attributes){
2895            if (attributes==null) {return null;}
2896            List<KimDocumentRoleQualifier> qualifiers = new ArrayList<KimDocumentRoleQualifier>();
2897            KimDocumentRoleQualifier qualifier;
2898            if(ObjectUtils.isNotNull(attributes)){
2899                    for(RoleMemberAttributeDataBo attribute: attributes){
2900                            qualifier = new KimDocumentRoleQualifier();
2901                                    qualifier.setAttrDataId(attribute.getId());
2902                                    qualifier.setAttrVal(attribute.getAttributeValue());
2903                                    qualifier.setRoleMemberId(attribute.getAssignedToId());
2904                                    qualifier.setKimTypId(attribute.getKimTypeId());
2905                                    qualifier.setKimAttrDefnId(attribute.getKimAttributeId());
2906                                    qualifier.setKimAttribute(attribute.getKimAttribute());
2907                                    qualifiers.add(qualifier);
2908                    }
2909            }
2910            return qualifiers;
2911        }
2912        
2913            public ResponsibilityInternalService getResponsibilityInternalService() {
2914                    if ( responsibilityInternalService == null ) {
2915                                    responsibilityInternalService = KimImplServiceLocator.getResponsibilityInternalService();
2916                    }
2917                    return responsibilityInternalService;
2918            }
2919    
2920       public PermissionService getPermissionService() {
2921                    if ( permissionService == null ) {
2922                                    permissionService = KimApiServiceLocator.getPermissionService();
2923                    }
2924                    return permissionService;
2925            }
2926    
2927        public ParameterService getParameterService() {
2928            if ( parameterService == null ) {
2929                    parameterService = CoreFrameworkServiceLocator.getParameterService();
2930            }
2931            return parameterService;
2932        }
2933    
2934        public void setParameterService(ParameterService parameterService) {
2935            this.parameterService = parameterService;
2936        }
2937    }