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