View Javadoc

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