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