001    /**
002     * Copyright 2005-2011 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.kim.web.struts.action;
017    
018    import org.apache.commons.lang.StringUtils;
019    import org.apache.struts.action.ActionForm;
020    import org.apache.struts.action.ActionForward;
021    import org.apache.struts.action.ActionMapping;
022    import org.kuali.rice.core.api.membership.MemberType;
023    import org.kuali.rice.core.api.util.RiceConstants;
024    import org.kuali.rice.core.api.util.RiceKeyConstants;
025    import org.kuali.rice.kew.api.exception.WorkflowException;
026    import org.kuali.rice.kim.api.KimConstants;
027    import org.kuali.rice.kim.api.group.Group;
028    import org.kuali.rice.kim.api.identity.entity.EntityDefault;
029    import org.kuali.rice.kim.api.identity.principal.Principal;
030    import org.kuali.rice.kim.api.role.Role;
031    import org.kuali.rice.kim.api.services.KimApiServiceLocator;
032    import org.kuali.rice.kim.api.type.KimAttributeField;
033    import org.kuali.rice.kim.bo.ui.KimDocumentRoleMember;
034    import org.kuali.rice.kim.bo.ui.KimDocumentRoleQualifier;
035    import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibilityAction;
036    import org.kuali.rice.kim.bo.ui.PersonDocumentAddress;
037    import org.kuali.rice.kim.bo.ui.PersonDocumentAffiliation;
038    import org.kuali.rice.kim.bo.ui.PersonDocumentCitizenship;
039    import org.kuali.rice.kim.bo.ui.PersonDocumentEmail;
040    import org.kuali.rice.kim.bo.ui.PersonDocumentEmploymentInfo;
041    import org.kuali.rice.kim.bo.ui.PersonDocumentGroup;
042    import org.kuali.rice.kim.bo.ui.PersonDocumentName;
043    import org.kuali.rice.kim.bo.ui.PersonDocumentPhone;
044    import org.kuali.rice.kim.bo.ui.PersonDocumentRole;
045    import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMember;
046    import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMemberQualifier;
047    import org.kuali.rice.kim.document.IdentityManagementPersonDocument;
048    import org.kuali.rice.kim.document.rule.AttributeValidationHelper;
049    import org.kuali.rice.kim.framework.type.KimTypeService;
050    import org.kuali.rice.kim.impl.KIMPropertyConstants;
051    import org.kuali.rice.kim.impl.responsibility.ResponsibilityInternalService;
052    import org.kuali.rice.kim.impl.role.RoleBo;
053    import org.kuali.rice.kim.impl.role.RoleMemberBo;
054    import org.kuali.rice.kim.impl.role.RoleResponsibilityBo;
055    import org.kuali.rice.kim.impl.services.KimImplServiceLocator;
056    import org.kuali.rice.kim.impl.type.KimTypeAttributesHelper;
057    import org.kuali.rice.kim.impl.type.KimTypeBo;
058    import org.kuali.rice.kim.rule.event.ui.AddGroupEvent;
059    import org.kuali.rice.kim.rule.event.ui.AddPersonDelegationMemberEvent;
060    import org.kuali.rice.kim.rule.event.ui.AddPersonDocumentRoleQualifierEvent;
061    import org.kuali.rice.kim.rule.event.ui.AddRoleEvent;
062    import org.kuali.rice.kim.rules.ui.PersonDocumentRoleRule;
063    import org.kuali.rice.kim.service.KIMServiceLocatorInternal;
064    import org.kuali.rice.kim.web.struts.form.IdentityManagementPersonDocumentForm;
065    import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
066    import org.kuali.rice.krad.util.GlobalVariables;
067    import org.kuali.rice.krad.util.KRADConstants;
068    import org.kuali.rice.krad.util.UrlFactory;
069    
070    import javax.servlet.http.HttpServletRequest;
071    import javax.servlet.http.HttpServletResponse;
072    import java.sql.Timestamp;
073    import java.text.MessageFormat;
074    import java.util.ArrayList;
075    import java.util.Calendar;
076    import java.util.List;
077    import java.util.Map;
078    import java.util.Properties;
079    
080    /**
081     * This is a description of what this class does - shyu don't forget to fill this in. 
082     * 
083     * @author Kuali Rice Team (rice.collab@kuali.org)
084     *
085     */
086    public class IdentityManagementPersonDocumentAction extends IdentityManagementDocumentActionBase {
087    
088        protected ResponsibilityInternalService responsibilityInternalService;
089    
090            @Override
091            public ActionForward execute(ActionMapping mapping, ActionForm form,
092                            HttpServletRequest request, HttpServletResponse response)
093                            throws Exception {
094                    ActionForward forward;
095            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
096            // accept either the principal name or principal ID, looking up the latter if necessary
097            // this allows inquiry links to work even when only the principal name is present
098            String principalId = request.getParameter(KIMPropertyConstants.Person.PRINCIPAL_ID);
099            String principalName = request.getParameter(KIMPropertyConstants.Person.PRINCIPAL_NAME);
100            if ( StringUtils.isBlank(principalId) && StringUtils.isNotBlank(principalName) ) {
101                    Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalName);
102                    if ( principal != null ) {
103                            principalId = principal.getPrincipalId();
104                    }
105            }
106            if ( principalId != null ) {
107                    personDocumentForm.setPrincipalId(principalId);
108            }
109            forward = super.execute(mapping, form, request, response);
110            
111            personDocumentForm.setCanModifyEntity(getUiDocumentService().canModifyEntity(GlobalVariables.getUserSession().getPrincipalId(), personDocumentForm.getPrincipalId()));
112            EntityDefault origEntity = null;
113            if(personDocumentForm.getPersonDocument()!=null) {
114                            origEntity = getIdentityService().getEntityDefault(personDocumentForm.getPersonDocument().getEntityId());
115                    }
116            boolean isCreatingNew = (personDocumentForm.getPersonDocument()==null || origEntity==null)?true:false;
117            personDocumentForm.setCanOverrideEntityPrivacyPreferences(isCreatingNew || getUiDocumentService().canOverrideEntityPrivacyPreferences(GlobalVariables.getUserSession().getPrincipalId(), personDocumentForm.getPrincipalId()));
118                    return forward;
119        }
120    
121            @Override
122            protected void loadDocument(KualiDocumentFormBase form)
123                            throws WorkflowException {
124                    super.loadDocument(form);
125            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
126                    IdentityManagementPersonDocument personDoc = personDocumentForm.getPersonDocument();
127                    populateRoleInformation(personDoc);
128            }
129    
130            protected void populateRoleInformation( IdentityManagementPersonDocument personDoc ) {
131                    for (PersonDocumentRole role : personDoc.getRoles()) {
132    //                      try {
133                    KimTypeService kimTypeService = getKimTypeService(KimTypeBo.to(role.getKimRoleType()));
134                    if ( kimTypeService != null ) {
135                            role.setDefinitions(kimTypeService.getAttributeDefinitions(role.getKimTypeId()));
136                    }
137                    // when post again, it will need this during populate
138                role.setNewRolePrncpl(new KimDocumentRoleMember());
139                for (KimAttributeField key : role.getDefinitions()) {
140                    KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
141                    //qualifier.setQualifierKey(key);
142                            setAttrDefnIdForQualifier(qualifier,key);
143                    role.getNewRolePrncpl().getQualifiers().add(qualifier);
144                }
145                    role.setAttributeEntry( getUiDocumentService().getAttributeEntries( role.getDefinitions() ) );
146                    }
147            }
148    
149            @Override
150            protected void createDocument(KualiDocumentFormBase form)
151                            throws WorkflowException {
152                    super.createDocument(form);
153            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
154            if(StringUtils.isBlank(personDocumentForm.getPrincipalId())){
155                    personDocumentForm.getPersonDocument().initializeDocumentForNewPerson();
156                    personDocumentForm.setPrincipalId(personDocumentForm.getPersonDocument().getPrincipalId());
157            } else {
158                    getUiDocumentService().loadEntityToPersonDoc(personDocumentForm.getPersonDocument(), personDocumentForm.getPrincipalId() );
159                    populateRoleInformation( personDocumentForm.getPersonDocument() );
160                    if(personDocumentForm.getPersonDocument()!=null) {
161                                    personDocumentForm.getPersonDocument().setIfRolesEditable();
162                            }
163            }
164            }
165            
166            /***
167             * @see org.kuali.rice.kim.web.struts.action.IdentityManagementDocumentActionBase#getActionName()
168             */
169            @Override
170            public String getActionName(){
171                    return KimConstants.KimUIConstants.KIM_PERSON_DOCUMENT_ACTION;
172            }
173    
174            public ActionForward addAffln(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
175            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
176            PersonDocumentAffiliation newAffln = personDocumentForm.getNewAffln();
177            newAffln.setDocumentNumber(personDocumentForm.getPersonDocument().getDocumentNumber());
178            newAffln.refreshReferenceObject("affiliationType");
179            personDocumentForm.getPersonDocument().getAffiliations().add(newAffln);
180            personDocumentForm.setNewAffln(new PersonDocumentAffiliation());        
181            return mapping.findForward(RiceConstants.MAPPING_BASIC);
182        }
183            
184        public ActionForward deleteAffln(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
185            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
186            personDocumentForm.getPersonDocument().getAffiliations().remove(getLineToDelete(request));
187            return mapping.findForward(RiceConstants.MAPPING_BASIC);
188        }
189        public ActionForward addCitizenship(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
190            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
191            PersonDocumentCitizenship newCitizenship = personDocumentForm.getNewCitizenship();
192            personDocumentForm.getPersonDocument().getCitizenships().add(newCitizenship);
193            personDocumentForm.setNewCitizenship(new PersonDocumentCitizenship());        
194            return mapping.findForward(RiceConstants.MAPPING_BASIC);
195        }
196        
197        public ActionForward deleteCitizenship(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
198            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
199            personDocumentForm.getPersonDocument().getCitizenships().remove(getLineToDelete(request));
200            return mapping.findForward(RiceConstants.MAPPING_BASIC);
201        }
202    
203        public ActionForward addEmpInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
204            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
205            IdentityManagementPersonDocument personDOc = personDocumentForm.getPersonDocument();
206            PersonDocumentAffiliation affiliation = personDOc.getAffiliations().get(getSelectedLine(request));        
207            PersonDocumentEmploymentInfo newempInfo = affiliation.getNewEmpInfo();
208            newempInfo.setDocumentNumber(personDOc.getDocumentNumber());
209            newempInfo.setVersionNumber(new Long(1));
210            affiliation.getEmpInfos().add(newempInfo);
211            affiliation.setNewEmpInfo(new PersonDocumentEmploymentInfo());        
212            return mapping.findForward(RiceConstants.MAPPING_BASIC);
213        }
214        
215        public ActionForward deleteEmpInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
216            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
217            String selectedIndexes = getSelectedParentChildIdx(request);
218            if (selectedIndexes != null) {
219                    String [] indexes = StringUtils.split(selectedIndexes,":");
220                    PersonDocumentAffiliation affiliation = personDocumentForm.getPersonDocument().getAffiliations().get(Integer.parseInt(indexes[0]));
221                    affiliation.getEmpInfos().remove(Integer.parseInt(indexes[1]));
222            }
223            return mapping.findForward(RiceConstants.MAPPING_BASIC);
224        }
225        
226        protected String getSelectedParentChildIdx(HttpServletRequest request) {
227            String lineNumber = null;
228            String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
229            if (StringUtils.isNotBlank(parameterName)) {
230                lineNumber = StringUtils.substringBetween(parameterName, ".line", ".");
231            }
232            return lineNumber;
233        }
234    
235        public ActionForward addName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
236            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
237            PersonDocumentName newName = personDocumentForm.getNewName();
238            newName.setDocumentNumber(personDocumentForm.getDocument().getDocumentNumber());
239            personDocumentForm.getPersonDocument().getNames().add(newName);
240            personDocumentForm.setNewName(new PersonDocumentName());        
241            return mapping.findForward(RiceConstants.MAPPING_BASIC);
242        }
243        
244        public ActionForward deleteName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
245            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
246            personDocumentForm.getPersonDocument().getNames().remove(getLineToDelete(request));
247            return mapping.findForward(RiceConstants.MAPPING_BASIC);
248        }
249    
250        public ActionForward addAddress(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
251            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
252            PersonDocumentAddress newAddress = personDocumentForm.getNewAddress();
253            newAddress.setDocumentNumber(personDocumentForm.getDocument().getDocumentNumber());
254            personDocumentForm.getPersonDocument().getAddrs().add(newAddress);
255            personDocumentForm.setNewAddress(new PersonDocumentAddress());        
256            return mapping.findForward(RiceConstants.MAPPING_BASIC);
257        }
258        
259        public ActionForward deleteAddress(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
260            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
261            personDocumentForm.getPersonDocument().getAddrs().remove(getLineToDelete(request));
262            return mapping.findForward(RiceConstants.MAPPING_BASIC);
263        }
264    
265        public ActionForward addPhone(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
266            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
267            PersonDocumentPhone newPhone = personDocumentForm.getNewPhone();
268            newPhone.setDocumentNumber(personDocumentForm.getDocument().getDocumentNumber());
269            personDocumentForm.getPersonDocument().getPhones().add(newPhone);
270            personDocumentForm.setNewPhone(new PersonDocumentPhone());        
271            return mapping.findForward(RiceConstants.MAPPING_BASIC);
272        }
273        
274        public ActionForward deletePhone(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
275            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
276            personDocumentForm.getPersonDocument().getPhones().remove(getLineToDelete(request));
277            return mapping.findForward(RiceConstants.MAPPING_BASIC);
278        }
279    
280        public ActionForward addEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
281            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
282            PersonDocumentEmail newEmail = personDocumentForm.getNewEmail();
283            newEmail.setDocumentNumber(personDocumentForm.getDocument().getDocumentNumber());
284            personDocumentForm.getPersonDocument().getEmails().add(newEmail);
285            personDocumentForm.setNewEmail(new PersonDocumentEmail());        
286            return mapping.findForward(RiceConstants.MAPPING_BASIC);
287        }
288        
289        public ActionForward deleteEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
290            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
291            personDocumentForm.getPersonDocument().getEmails().remove(getLineToDelete(request));
292            return mapping.findForward(RiceConstants.MAPPING_BASIC);
293        }
294    
295        public ActionForward addGroup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
296            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
297            PersonDocumentGroup newGroup = personDocumentForm.getNewGroup();
298            if (newGroup.getGroupName() == null 
299                            && newGroup.getNamespaceCode() == null 
300                            && newGroup.getGroupId() != null) {
301                    Group tempGroup = KimApiServiceLocator.getGroupService().getGroup(newGroup.getGroupId());
302                    newGroup.setGroupName(tempGroup.getName());
303                    newGroup.setNamespaceCode(tempGroup.getNamespaceCode());
304                    newGroup.setKimTypeId(tempGroup.getKimTypeId());
305            } else if (newGroup.getGroupName() != null 
306                            && newGroup.getNamespaceCode() != null 
307                            && newGroup.getGroupId() == null) {
308                    Group tempGroup = KimApiServiceLocator.getGroupService().getGroupByNameAndNamespaceCode(
309                        newGroup.getNamespaceCode(), newGroup.getGroupName());
310                    newGroup.setGroupId(tempGroup.getId());
311                    newGroup.setKimTypeId(tempGroup.getKimTypeId());
312            }
313            if (getKualiRuleService().applyRules(new AddGroupEvent("",personDocumentForm.getPersonDocument(), newGroup))) {
314                    Group group = getGroupService().getGroup(newGroup.getGroupId());
315                    newGroup.setGroupName(group.getName());
316                    newGroup.setNamespaceCode(group.getNamespaceCode());
317                    newGroup.setKimTypeId(group.getKimTypeId());
318                    personDocumentForm.getPersonDocument().getGroups().add(newGroup);
319                    personDocumentForm.setNewGroup(new PersonDocumentGroup());
320            }
321            return mapping.findForward(RiceConstants.MAPPING_BASIC);
322        }
323        
324        public ActionForward deleteGroup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
325            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
326            PersonDocumentGroup inactivedGroupMembership = personDocumentForm.getPersonDocument().getGroups().get(getLineToDelete(request));
327            Calendar cal = Calendar.getInstance();
328            inactivedGroupMembership.setActiveToDate(new Timestamp(cal.getTimeInMillis()));        
329            personDocumentForm.getPersonDocument().getGroups().set(getLineToDelete(request), inactivedGroupMembership);
330            return mapping.findForward(RiceConstants.MAPPING_BASIC);
331        }
332    
333        public ActionForward addRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
334            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
335            PersonDocumentRole newRole = personDocumentForm.getNewRole();
336            if (getKualiRuleService().applyRules(new AddRoleEvent("",personDocumentForm.getPersonDocument(), newRole))) {
337                    Role role = KimApiServiceLocator.getRoleService().getRole(newRole.getRoleId());
338                    if(!validateRole(newRole.getRoleId(), role, PersonDocumentRoleRule.ERROR_PATH, "Person")){
339                            return mapping.findForward(RiceConstants.MAPPING_BASIC);
340                    }
341                    newRole.setRoleName(role.getName());
342                    newRole.setNamespaceCode(role.getNamespaceCode());
343                    newRole.setKimTypeId(role.getKimTypeId());
344                    if(!validateRoleAssignment(personDocumentForm.getPersonDocument(), newRole)){
345                            return mapping.findForward(RiceConstants.MAPPING_BASIC);
346                    }
347                    KimTypeService kimTypeService = getKimTypeService(KimTypeBo.to(newRole.getKimRoleType()));
348                    //AttributeDefinitionMap definitions = kimTypeService.getAttributeDefinitions();
349                    // role type populated from form is not a complete record
350                    if ( kimTypeService != null ) {
351                            newRole.setDefinitions(kimTypeService.getAttributeDefinitions(newRole.getKimTypeId()));
352                    }
353                   // KimDocumentRoleMember newRolePrncpl = newRole.getNewRolePrncpl();
354                KimDocumentRoleMember newRolePrncpl = newRole.getNewRolePrncpl() == null ? new KimDocumentRoleMember() : newRole.getNewRolePrncpl();
355                    newRole.refreshReferenceObject("assignedResponsibilities");
356                    
357                    for (KimAttributeField key : newRole.getDefinitions()) {
358                            KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
359                            //qualifier.setQualifierKey(key);
360                            setAttrDefnIdForQualifier(qualifier,key);
361                            newRolePrncpl.getQualifiers().add(qualifier);
362                    }
363                    if (newRole.getDefinitions().isEmpty()) {
364                            List<KimDocumentRoleMember> rolePrncpls = new ArrayList<KimDocumentRoleMember>();
365                            setupRoleRspActions(newRole, newRolePrncpl);
366                        rolePrncpls.add(newRolePrncpl);
367                            newRole.setRolePrncpls(rolePrncpls);
368                    }
369                    //newRole.setNewRolePrncpl(newRolePrncpl);
370                    newRole.setAttributeEntry( getUiDocumentService().getAttributeEntries( newRole.getDefinitions() ) );
371                    personDocumentForm.getPersonDocument().getRoles().add(newRole);
372                    personDocumentForm.setNewRole(new PersonDocumentRole());
373            }
374            return mapping.findForward(RiceConstants.MAPPING_BASIC);
375        }
376          /*  public ActionForward addRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
377            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
378            PersonDocumentRole newRole = personDocumentForm.getNewRole();
379    
380            if (getKualiRuleService().applyRules(new AddRoleEvent("",personDocumentForm.getPersonDocument(), newRole))) {
381             Role role = KimApiServiceLocator.getRoleService().getRole(newRole.getRoleId());
382             if(!validateRole(newRole.getRoleId(), role, PersonDocumentRoleRule.ERROR_PATH, "Person")){
383              return mapping.findForward(RiceConstants.MAPPING_BASIC);
384             }
385             newRole.setRoleName(role.getName());
386             newRole.setNamespaceCode(role.getNamespaceCode());
387             newRole.setKimTypeId(role.getKimTypeId());
388                KimDocumentRoleMember roleMember = new KimDocumentRoleMember();
389                roleMember.setMemberId(personDocumentForm.getPrincipalId());
390                roleMember.setMemberTypeCode(MemberType.PRINCIPAL.getCode());
391                roleMember.setRoleId(newRole.getRoleId());
392                newRole.setNewRolePrncpl(roleMember);
393             if(!validateRoleAssignment(personDocumentForm.getPersonDocument(), newRole)){
394              return mapping.findForward(RiceConstants.MAPPING_BASIC);
395             }
396             KimTypeService kimTypeService = getKimTypeService(KimTypeBo.to(newRole.getKimRoleType()));
397             //AttributeDefinitionMap definitions = kimTypeService.getAttributeDefinitions();
398             // role type populated from form is not a complete record
399             if ( kimTypeService != null ) {
400              newRole.setDefinitions(kimTypeService.getAttributeDefinitions(newRole.getKimTypeId()));
401             }
402             KimDocumentRoleMember newRolePrncpl = newRole.getNewRolePrncpl();
403             newRole.refreshReferenceObject("assignedResponsibilities");
404    
405             for (KimAttributeField key : newRole.getDefinitions()) {
406              KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
407              //qualifier.setQualifierKey(key);
408              setAttrDefnIdForQualifier(qualifier,key);
409              newRolePrncpl.getQualifiers().add(qualifier);
410             }
411             if (newRole.getDefinitions().isEmpty()) {
412              List<KimDocumentRoleMember> rolePrncpls = new ArrayList<KimDocumentRoleMember>();
413              setupRoleRspActions(newRole, newRolePrncpl);
414                 rolePrncpls.add(newRolePrncpl);
415              newRole.setRolePrncpls(rolePrncpls);
416             }
417             //newRole.setNewRolePrncpl(newRolePrncpl);
418             newRole.setAttributeEntry( getUiDocumentService().getAttributeEntries( newRole.getDefinitions() ) );
419             personDocumentForm.getPersonDocument().getRoles().add(newRole);
420             personDocumentForm.setNewRole(new PersonDocumentRole());
421            }
422            return mapping.findForward(RiceConstants.MAPPING_BASIC);
423        }       */
424        
425            protected boolean validateRoleAssignment(IdentityManagementPersonDocument document, PersonDocumentRole newRole){
426            boolean rulePassed = true;
427            if(!document.validAssignRole(newRole)){
428                            GlobalVariables.getMessageMap().putError("newRole.roleId", 
429                                            RiceKeyConstants.ERROR_ASSIGN_ROLE, 
430                                            new String[] {newRole.getNamespaceCode(), newRole.getRoleName()});
431                    rulePassed = false;
432            }
433                    return rulePassed;
434            }
435    
436        protected void setupRoleRspActions(PersonDocumentRole role, KimDocumentRoleMember rolePrncpl) {
437            for (RoleResponsibilityBo roleResp : role.getAssignedResponsibilities()) {
438                    if (getResponsibilityInternalService().areActionsAtAssignmentLevelById(roleResp.getRoleResponsibilityId())) {
439                            KimDocumentRoleResponsibilityAction roleRspAction = new KimDocumentRoleResponsibilityAction();
440                            roleRspAction.setRoleResponsibilityId("*");                     
441                            roleRspAction.refreshReferenceObject("roleResponsibility");
442                            if(rolePrncpl.getRoleRspActions()==null || rolePrncpl.getRoleRspActions().size()<1){
443                                    if(rolePrncpl.getRoleRspActions()==null) {
444                                                    rolePrncpl.setRoleRspActions(new ArrayList<KimDocumentRoleResponsibilityAction>());
445                                            }
446                                     rolePrncpl.getRoleRspActions().add(roleRspAction);
447                            }
448                    }               
449            }
450        }
451        
452    //      protected boolean isUniqueRoleRspAction(List<KimDocumentRoleResponsibilityAction> roleRspActions, KimDocumentRoleResponsibilityAction roleRspAction){
453    //      if(roleRspActions==null || roleRspAction==null) return false;
454    //      for(KimDocumentRoleResponsibilityAction roleRspActionTemp: roleRspActions){
455    //              if((StringUtils.isNotEmpty(roleRspActionTemp.getRoleMemberId()) && roleRspActionTemp.getRoleMemberId().equals(roleRspAction.getRoleMemberId())) && 
456    //                      (StringUtils.isNotEmpty(roleRspActionTemp.getRoleResponsibilityId())    && roleRspActionTemp.getRoleResponsibilityId().equals(roleRspAction.getRoleResponsibilityId())))
457    //                      return false;
458    //      }
459    //      return true;
460    //    }
461                
462    
463        protected void setAttrDefnIdForQualifier(KimDocumentRoleQualifier qualifier,KimAttributeField definition) {
464                    qualifier.setKimAttrDefnId(definition.getId());
465                    qualifier.refreshReferenceObject("kimAttribute");
466        }
467    
468        public ActionForward deleteRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
469            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
470            personDocumentForm.getPersonDocument().getRoles().remove(getLineToDelete(request));
471            return mapping.findForward(RiceConstants.MAPPING_BASIC);
472        }
473    
474        public ActionForward addRoleQualifier(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
475            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
476            IdentityManagementPersonDocument personDOc = personDocumentForm.getPersonDocument();
477            int selectedRoleIdx = getSelectedLine(request);
478            PersonDocumentRole role = personDOc.getRoles().get(selectedRoleIdx);
479            KimDocumentRoleMember newRolePrncpl = role.getNewRolePrncpl();
480            
481            if (getKualiRuleService().applyRules(new AddPersonDocumentRoleQualifierEvent("",
482                            personDOc, newRolePrncpl, role, selectedRoleIdx))) {
483                    setupRoleRspActions(role, newRolePrncpl);
484                    role.getRolePrncpls().add(newRolePrncpl);
485                    role.setNewRolePrncpl(new KimDocumentRoleMember());
486                    for (KimAttributeField key : role.getDefinitions()) {
487                            KimDocumentRoleQualifier qualifier = new KimDocumentRoleQualifier();
488                            //qualifier.setQualifierKey(key);
489                            setAttrDefnIdForQualifier(qualifier,key);
490                            role.getNewRolePrncpl().getQualifiers().add(qualifier);
491                    }
492            }
493    
494            return mapping.findForward(RiceConstants.MAPPING_BASIC);
495        }
496    
497        public ActionForward deleteRoleQualifier(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
498            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
499            String selectedIndexes = getSelectedParentChildIdx(request);
500            if (selectedIndexes != null) {
501                    String [] indexes = StringUtils.split(selectedIndexes,":");
502                    PersonDocumentRole role = personDocumentForm.getPersonDocument().getRoles().get(Integer.parseInt(indexes[0]));
503                    role.getRolePrncpls().remove(Integer.parseInt(indexes[1]));
504            }
505            return mapping.findForward(RiceConstants.MAPPING_BASIC);
506        }
507        
508        public ActionForward addDelegationMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
509            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
510            IdentityManagementPersonDocument personDocument = personDocumentForm.getPersonDocument();
511            RoleDocumentDelegationMember newDelegationMember = personDocumentForm.getNewDelegationMember();
512            KimTypeAttributesHelper attrHelper = newDelegationMember.getAttributesHelper();
513            if (getKualiRuleService().applyRules(new AddPersonDelegationMemberEvent("", personDocumentForm.getPersonDocument(), newDelegationMember))) {
514                    //RoleImpl roleBo = (RoleImpl)getUiDocumentService().getMember(KimApiConstants.KimUIConstants.MEMBER_TYPE_ROLE_CODE, newDelegationMember.getRoleDao().getRoleId());
515                    Role role;
516                    role = KimApiServiceLocator.getRoleService().getRole(newDelegationMember.getRoleBo().getId());
517                    if (role != null) {
518                            if(!validateRole(newDelegationMember.getRoleBo().getId(),role, PersonDocumentRoleRule.ERROR_PATH, "Person")){
519                                    return mapping.findForward(RiceConstants.MAPPING_BASIC);
520                            }
521                            newDelegationMember.setRoleBo(RoleBo.from(role));
522                    }
523                    KimAttributeField attrDefinition;
524                    RoleMemberBo roleMember = KIMServiceLocatorInternal.getUiDocumentService().getRoleMember(newDelegationMember.getRoleMemberId());
525                    Map<String, String>
526                        roleMemberAttributes = (new AttributeValidationHelper()).convertAttributesToMap(roleMember.getAttributeDetails());
527                    for (KimAttributeField key: attrHelper.getDefinitions()) {
528                            RoleDocumentDelegationMemberQualifier qualifier = new RoleDocumentDelegationMemberQualifier();
529                            attrDefinition = key;
530                            qualifier.setKimAttrDefnId(attrHelper.getKimAttributeDefnId(attrDefinition));
531                            qualifier.setAttrVal(attrHelper.getAttributeValue(roleMemberAttributes, attrDefinition.getAttributeField().getName()));
532                            newDelegationMember.setMemberId(personDocument.getPrincipalId());
533                            newDelegationMember.setMemberTypeCode(MemberType.PRINCIPAL.getCode());
534                            newDelegationMember.getQualifiers().add(qualifier);
535                    }
536                    //newDelegationMember.setAttributeEntry(getUiDocumentService().getAttributeEntries(newDelegationMember.getAttributesHelper().getDefinitions())));
537                    personDocument.getDelegationMembers().add(newDelegationMember);
538                    personDocumentForm.setNewDelegationMember(new RoleDocumentDelegationMember());
539            }
540            return mapping.findForward(RiceConstants.MAPPING_BASIC);
541        }
542        
543        public ActionForward deleteDelegationMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
544            IdentityManagementPersonDocumentForm personDocumentForm = (IdentityManagementPersonDocumentForm) form;
545            personDocumentForm.getPersonDocument().getDelegationMembers().remove(getLineToDelete(request));
546            return mapping.findForward(RiceConstants.MAPPING_BASIC);
547        }
548    
549            @Override
550            public ActionForward save(ActionMapping mapping, ActionForm form,
551                            HttpServletRequest request, HttpServletResponse response)
552                            throws Exception {
553    
554                    return super.save(mapping, form, request, response);
555            }
556            
557        @Override
558        public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
559            IdentityManagementPersonDocumentForm impdForm = (IdentityManagementPersonDocumentForm) form;
560    
561            ActionForward forward = this.refreshAfterDelegationMemberRoleSelection(mapping, impdForm, request);
562            if (forward != null) {
563                return forward;
564            }
565    
566            return super.refresh(mapping, form, request, response);
567            }
568        
569        protected ActionForward refreshAfterDelegationMemberRoleSelection(ActionMapping mapping, IdentityManagementPersonDocumentForm impdForm, HttpServletRequest request) {
570            String refreshCaller = impdForm.getRefreshCaller();
571    
572            boolean isRoleLookupable = KimConstants.KimUIConstants.ROLE_LOOKUPABLE_IMPL.equals(refreshCaller);
573            boolean isRoleMemberLookupable = KimConstants.KimUIConstants.KIM_DOCUMENT_ROLE_MEMBER_LOOKUPABLE_IMPL.equals(refreshCaller);
574    
575            // do not execute the further refreshing logic if the refresh caller is not a lookupable
576            if (!isRoleLookupable && !isRoleMemberLookupable) {
577                return null;
578            }
579    
580            //In case of delegation member lookup impdForm.getNewDelegationMemberRoleId() will be populated.
581            if(impdForm.getNewDelegationMemberRoleId() == null){
582                return null;
583            }
584            if(isRoleLookupable){
585                return renderRoleMemberSelection(mapping, request, impdForm);
586            }
587    
588            String roleMemberId = request.getParameter(KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID);
589            if(StringUtils.isNotBlank(roleMemberId)){
590                impdForm.getNewDelegationMember().setRoleMemberId(roleMemberId);
591                RoleMemberBo roleMember = getUiDocumentService().getRoleMember(roleMemberId);
592                impdForm.getNewDelegationMember().setRoleMemberMemberId(roleMember.getMemberId());
593                impdForm.getNewDelegationMember().setRoleMemberMemberTypeCode(roleMember.getType().getCode());
594                impdForm.getNewDelegationMember().setRoleMemberName(getUiDocumentService().getMemberName(MemberType.fromCode(impdForm.getNewDelegationMember().getRoleMemberMemberTypeCode()), impdForm.getNewDelegationMember().getRoleMemberMemberId()));
595                impdForm.getNewDelegationMember().setRoleMemberNamespaceCode(getUiDocumentService().getMemberNamespaceCode(MemberType.fromCode(impdForm.getNewDelegationMember().getRoleMemberMemberTypeCode()), impdForm.getNewDelegationMember().getRoleMemberMemberId()));
596    
597                Role role;
598                    role = KimApiServiceLocator.getRoleService().getRole(impdForm.getNewDelegationMember().getRoleBo().getId());
599                    if (role != null) {
600                            if(!validateRole(impdForm.getNewDelegationMember().getRoleBo().getId(), role, PersonDocumentRoleRule.ERROR_PATH, "Person")){
601                                    return mapping.findForward(RiceConstants.MAPPING_BASIC);
602                            }
603                            impdForm.getNewDelegationMember().setRoleBo(RoleBo.from(role));
604                    }
605            }
606            impdForm.setNewDelegationMemberRoleId(null);
607            return null;
608        }
609        
610        protected ActionForward renderRoleMemberSelection(ActionMapping mapping, HttpServletRequest request, IdentityManagementPersonDocumentForm impdForm) {
611            Properties props = new Properties();
612    
613            props.put(KRADConstants.SUPPRESS_ACTIONS, Boolean.toString(true));
614            props.put(KRADConstants.BUSINESS_OBJECT_CLASS_ATTRIBUTE, KimDocumentRoleMember.class.getName());
615            props.put(KRADConstants.LOOKUP_ANCHOR, KRADConstants.ANCHOR_TOP_OF_FORM);
616            props.put(KRADConstants.LOOKED_UP_COLLECTION_NAME, KimConstants.KimUIConstants.ROLE_MEMBERS_COLLECTION_NAME);
617    
618            String conversionPatttern = "{0}" + KRADConstants.FIELD_CONVERSION_PAIR_SEPARATOR + "{0}";
619            StringBuilder fieldConversion = new StringBuilder();
620            fieldConversion.append(MessageFormat.format(conversionPatttern, 
621                    KimConstants.PrimaryKeyConstants.SUB_ROLE_ID)).append(KRADConstants.FIELD_CONVERSIONS_SEPARATOR);
622            fieldConversion.append(MessageFormat.format(conversionPatttern, 
623                            KimConstants.PrimaryKeyConstants.ROLE_MEMBER_ID)).append(KRADConstants.FIELD_CONVERSIONS_SEPARATOR);
624    
625            props.put(KRADConstants.CONVERSION_FIELDS_PARAMETER, fieldConversion);
626    
627            props.put(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID, impdForm.getNewDelegationMember().getRoleBo().getId());
628    
629            props.put(KRADConstants.RETURN_LOCATION_PARAMETER, this.getReturnLocation(request, mapping));
630         //   props.put(KRADConstants.BACK_LOCATION, this.getReturnLocation(request, mapping));
631    
632            props.put(KRADConstants.LOOKUP_AUTO_SEARCH, "Yes");
633            props.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.SEARCH_METHOD);
634    
635            props.put(KRADConstants.DOC_FORM_KEY, GlobalVariables.getUserSession().addObjectWithGeneratedKey(impdForm));
636         //   props.put(KRADConstants.DOC_NUM, impdForm.getDocument().getDocumentNumber());
637    
638            // TODO: how should this forward be handled
639            String url = UrlFactory.parameterizeUrl(getApplicationBaseUrl() + "/kr/" + KRADConstants.LOOKUP_ACTION, props);
640    
641            impdForm.registerEditableProperty("methodToCall");
642    
643            return new ActionForward(url, true);
644        }
645    
646    
647        public ResponsibilityInternalService getResponsibilityInternalService() {
648            if ( responsibilityInternalService == null ) {
649                    responsibilityInternalService = KimImplServiceLocator.getResponsibilityInternalService();
650            }
651                    return responsibilityInternalService;
652            }
653    }