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 java.sql.Timestamp;
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.Calendar;
22  import java.util.HashMap;
23  import java.util.List;
24  import java.util.Map;
25  
26  import javax.servlet.http.HttpServletRequest;
27  import javax.servlet.http.HttpServletResponse;
28  
29  import org.apache.commons.lang.StringUtils;
30  import org.apache.struts.action.ActionForm;
31  import org.apache.struts.action.ActionForward;
32  import org.apache.struts.action.ActionMapping;
33  import org.kuali.rice.core.api.delegation.DelegationType;
34  import org.kuali.rice.core.api.membership.MemberType;
35  import org.kuali.rice.core.api.util.RiceConstants;
36  import org.kuali.rice.core.api.util.RiceKeyConstants;
37  import org.kuali.rice.core.api.util.io.SerializationUtils;
38  import org.kuali.rice.kew.api.exception.WorkflowException;
39  import org.kuali.rice.kim.api.KimConstants;
40  import org.kuali.rice.kim.api.group.Group;
41  import org.kuali.rice.kim.api.identity.Person;
42  import org.kuali.rice.kim.api.identity.principal.Principal;
43  import org.kuali.rice.kim.api.role.Role;
44  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
45  import org.kuali.rice.kim.bo.ui.KimDocumentRoleMember;
46  import org.kuali.rice.kim.bo.ui.KimDocumentRolePermission;
47  import org.kuali.rice.kim.bo.ui.KimDocumentRoleQualifier;
48  import org.kuali.rice.kim.bo.ui.KimDocumentRoleResponsibility;
49  import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMember;
50  import org.kuali.rice.kim.bo.ui.RoleDocumentDelegationMemberQualifier;
51  import org.kuali.rice.kim.document.IdentityManagementRoleDocument;
52  import org.kuali.rice.kim.impl.responsibility.AddResponsibilityEvent;
53  import org.kuali.rice.kim.impl.responsibility.ResponsibilityBo;
54  import org.kuali.rice.kim.impl.type.KimTypeLookupableHelperServiceImpl;
55  import org.kuali.rice.kim.rule.event.ui.AddDelegationMemberEvent;
56  import org.kuali.rice.kim.rule.event.ui.AddMemberEvent;
57  import org.kuali.rice.kim.rule.event.ui.AddPermissionEvent;
58  import org.kuali.rice.kim.web.struts.form.IdentityManagementRoleDocumentForm;
59  import org.kuali.rice.kns.question.ConfirmationQuestion;
60  import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
61  import org.kuali.rice.kns.web.struts.form.KualiTableRenderFormMetadata;
62  import org.kuali.rice.krad.data.KradDataServiceLocator;
63  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
64  import org.kuali.rice.krad.util.GlobalVariables;
65  import org.kuali.rice.krad.util.KRADConstants;
66  
67  /**
68   * @author Kuali Rice Team (rice.collab@kuali.org)
69   */
70  public class IdentityManagementRoleDocumentAction extends IdentityManagementDocumentActionBase {
71  
72      public static final String CHANGE_DEL_ROLE_MEMBER_METHOD_TO_CALL = "changeDelegationRoleMember";
73      public static final String SWITCH_TO_ROLE_MEMBER_METHOD_TO_CALL = "jumpToRoleMember";
74      public static final String REMOVE_AFFECTED_DELEGATES_QUESTION_ID = "RemoveAffectedDelegates";
75  
76      protected List<String> methodToCallToUncheckedList = new ArrayList<String>();
77  
78      /**
79       * This method doesn't actually sort the column - it's just that we need a sort method in
80       * order to exploit the existing methodToCall logic. The sorting is handled in the execute
81       * method below, and delegated to the KualiTableRenderFormMetadata object.
82       *
83       * @param mapping
84       * @param form
85       * @param request
86       * @param response
87       * @return
88       * @throws Exception
89       */
90      {
91          methodToCallToUncheckedList.add(CHANGE_DEL_ROLE_MEMBER_METHOD_TO_CALL);
92          methodToCallToUncheckedList.add(CHANGE_MEMBER_TYPE_CODE_METHOD_TO_CALL);
93          methodToCallToUncheckedList.add(CHANGE_NAMESPACE_METHOD_TO_CALL);
94          methodToCallToUncheckedList.add(SWITCH_TO_ROLE_MEMBER_METHOD_TO_CALL);
95      }
96  
97      /**
98       * This constructs a ...
99       */
100     public IdentityManagementRoleDocumentAction() {
101         super();
102         for (String methodToCallToUncheck : methodToCallToUncheckedList) {
103             addMethodToCallToUncheckedList(methodToCallToUncheck);
104         }
105     }
106 
107     public ActionForward sort(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
108         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
109         KualiTableRenderFormMetadata memberTableMetadata = roleDocumentForm.getMemberTableMetadata();
110         memberTableMetadata.setSwitchToPageNumber(0);
111         return mapping.findForward(RiceConstants.MAPPING_BASIC);
112     }
113 
114     @Override
115     public ActionForward execute(ActionMapping mapping, ActionForm form,
116             HttpServletRequest request, HttpServletResponse response) throws Exception {
117         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
118         if (roleDocumentForm.getRoleId() == null) {
119             String roleId = request.getParameter(KimConstants.PrimaryKeyConstants.SUB_ROLE_ID);
120             roleDocumentForm.setRoleId(roleId);
121         }
122 
123         KualiTableRenderFormMetadata memberTableMetadata = roleDocumentForm.getMemberTableMetadata();
124         if (roleDocumentForm.getRoleDocument()!=null && roleDocumentForm.getMemberRows() != null) {
125             memberTableMetadata.jumpToPage(memberTableMetadata.getViewedPageNumber(), roleDocumentForm.getMemberRows().size(), roleDocumentForm.getRecordsPerPage());
126             // KULRICE-3972: need to be able to sort by column header like on lookups when editing large roles and groups
127             memberTableMetadata.sort(roleDocumentForm.getMemberRows(), roleDocumentForm.getRecordsPerPage());
128         }
129 
130         // KULRICE-4762: active delegates of "inactivated" role members cause validation problems
131         ActionForward forward = promptForAffectedDelegates(mapping, form, request, response,
132                 roleDocumentForm);
133         // if we need to prompt the user due to affected delegates, do so:
134         if (forward != null) { return forward; }
135 
136         forward = super.execute(mapping, roleDocumentForm, request, response);
137 
138         roleDocumentForm.setCanAssignRole(validAssignRole(roleDocumentForm.getRoleDocument()));
139         if (KimTypeLookupableHelperServiceImpl.hasDerivedRoleTypeService(roleDocumentForm.getRoleDocument().getKimType())) {
140             roleDocumentForm.setCanModifyAssignees(false);
141         }
142         GlobalVariables.getUserSession().addObject(KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_SHORT_KEY, roleDocumentForm.getRoleDocument());
143         return forward;
144     }
145 
146     /**
147      * This overridden method ...
148      *
149      * @see org.kuali.rice.krad.web.struts.action.KualiDocumentActionBase#loadDocument(org.kuali.rice.krad.web.struts.form.KualiDocumentFormBase)
150      */
151     @Override
152     protected void loadDocument(KualiDocumentFormBase form)
153             throws WorkflowException {
154         super.loadDocument(form);
155 
156         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
157         setKimType(roleDocumentForm.getRoleDocument().getRoleTypeId(), roleDocumentForm);
158 
159         getUiDocumentService().setDelegationMembersInDocument(roleDocumentForm.getRoleDocument());
160         getUiDocumentService().setMembersInDocument(roleDocumentForm.getRoleDocument());
161 
162         roleDocumentForm.setMember(roleDocumentForm.getRoleDocument().getBlankMember());
163         roleDocumentForm.setDelegationMember(roleDocumentForm.getRoleDocument().getBlankDelegationMember());
164 
165         KualiTableRenderFormMetadata memberTableMetadata = roleDocumentForm.getMemberTableMetadata();
166         if (roleDocumentForm.getMemberRows() != null) {
167             memberTableMetadata.jumpToFirstPage(roleDocumentForm.getMemberRows().size(), roleDocumentForm.getRecordsPerPage());
168         }
169     }
170 
171     /**
172      * This overridden method ...
173      *
174      * @see org.kuali.rice.krad.web.struts.action.KualiDocumentActionBase#createDocument(org.kuali.rice.krad.web.struts.form.KualiDocumentFormBase)
175      */
176     @Override
177     protected void createDocument(KualiDocumentFormBase form)
178             throws WorkflowException {
179         super.createDocument(form);
180         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
181 
182         if (roleDocumentForm.getRoleId() == null) {
183             roleDocumentForm.getRoleDocument().setKimType(roleDocumentForm.getKimType());
184             roleDocumentForm.getRoleDocument().initializeDocumentForNewRole();
185             roleDocumentForm.setRoleId(roleDocumentForm.getRoleDocument().getRoleId());
186             //roleDocumentForm.setKimType(KimApiServiceLocator.getKimTypeInfoService().getKimType(roleDocumentForm.getRoleDocument().getRoleTypeId()));
187         } else {
188             loadRoleIntoDocument(roleDocumentForm.getRoleId(), roleDocumentForm);
189         }
190 
191         roleDocumentForm.setMember(roleDocumentForm.getRoleDocument().getBlankMember());
192         roleDocumentForm.setDelegationMember(roleDocumentForm.getRoleDocument().getBlankDelegationMember());
193 
194         KualiTableRenderFormMetadata memberTableMetadata = roleDocumentForm.getMemberTableMetadata();
195         if (roleDocumentForm.getMemberRows() != null) {
196             memberTableMetadata.jumpToFirstPage(roleDocumentForm.getMemberRows().size(), roleDocumentForm.getRecordsPerPage());
197         }
198     }
199 
200     protected void setKimType(String kimTypeId, IdentityManagementRoleDocumentForm roleDocumentForm) {
201         if (StringUtils.isNotBlank(kimTypeId)) {
202             roleDocumentForm.setKimType(KimApiServiceLocator.getKimTypeInfoService().getKimType(kimTypeId));
203             if (roleDocumentForm.getRoleDocument() != null) {
204                 roleDocumentForm.getRoleDocument().setKimType(roleDocumentForm.getKimType());
205             }
206         } else if (roleDocumentForm.getRoleDocument() != null && StringUtils.isNotBlank(roleDocumentForm.getRoleDocument().getRoleTypeId())) {
207             roleDocumentForm.setKimType(KimApiServiceLocator.getKimTypeInfoService().getKimType(
208                     roleDocumentForm.getRoleDocument().getRoleTypeId()));
209             roleDocumentForm.getRoleDocument().setKimType(roleDocumentForm.getKimType());
210         }
211     }
212 
213     protected void loadRoleIntoDocument(String roleId, IdentityManagementRoleDocumentForm roleDocumentForm) {
214         Role role = KimApiServiceLocator.getRoleService().getRole(roleId);
215         roleDocumentForm.getRoleDocument().setMemberMetaDataTypeToSort(roleDocumentForm.getMemberTableMetadata().getColumnToSortIndex());
216         getUiDocumentService().loadRoleDoc(roleDocumentForm.getRoleDocument(), role);
217     }
218 
219     /**
220      * @see org.kuali.rice.kim.web.struts.action.IdentityManagementDocumentActionBase#getActionName()
221      */
222     @Override
223     public String getActionName() {
224         return KimConstants.KimUIConstants.KIM_ROLE_DOCUMENT_ACTION;
225     }
226 
227     protected boolean validAssignRole(IdentityManagementRoleDocument document) {
228         boolean rulePassed = true;
229         if (StringUtils.isNotEmpty(document.getRoleNamespace())) {
230             Map<String, String> additionalPermissionDetails = new HashMap<String, String>();
231             additionalPermissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, document.getRoleNamespace());
232             additionalPermissionDetails.put(KimConstants.AttributeConstants.ROLE_NAME, document.getRoleName());
233             if (!getDocumentHelperService().getDocumentAuthorizer(document).isAuthorizedByTemplate(
234                     document,
235                     KimConstants.NAMESPACE_CODE,
236                     KimConstants.PermissionTemplateNames.ASSIGN_ROLE,
237                     GlobalVariables.getUserSession().getPrincipalId(),
238                     additionalPermissionDetails, null)) {
239                 rulePassed = false;
240             }
241         }
242         return rulePassed;
243     }
244 
245     public ActionForward changeMemberTypeCode(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
246         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
247         roleDocumentForm.getMember().setMemberId("");
248         return refresh(mapping, roleDocumentForm, request, response);
249     }
250 
251     public ActionForward changeDelegationMemberTypeCode(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
252         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
253         KimDocumentRoleMember roleMember = roleDocumentForm.getRoleDocument().getMember(roleDocumentForm.getDelegationMember().getRoleMemberId());
254         if (roleMember != null) {
255             RoleDocumentDelegationMemberQualifier delegationMemberQualifier;
256             for (KimDocumentRoleQualifier roleQualifier : roleMember.getQualifiers()) {
257                 delegationMemberQualifier = roleDocumentForm.getDelegationMember().getQualifier(roleQualifier.getKimAttrDefnId());
258                 delegationMemberQualifier.setAttrVal(roleQualifier.getAttrVal());
259             }
260         }
261         return refresh(mapping, roleDocumentForm, request, response);
262     }
263 
264     public ActionForward addResponsibility(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
265         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
266         KimDocumentRoleResponsibility newResponsibility = roleDocumentForm.getResponsibility();
267         if (newResponsibility != null && StringUtils.isNotBlank(newResponsibility.getResponsibilityId())) {
268             ResponsibilityBo responsibilityImpl = KradDataServiceLocator.getDataObjectService().find(ResponsibilityBo.class, newResponsibility.getResponsibilityId());
269             newResponsibility.setKimResponsibility(responsibilityImpl);
270         }
271 
272         if (KRADServiceLocatorWeb.getKualiRuleService().applyRules(new AddResponsibilityEvent("", roleDocumentForm.getRoleDocument(), newResponsibility))) {
273             if (newResponsibility != null) {
274                 newResponsibility.setDocumentNumber(roleDocumentForm.getDocument().getDocumentNumber());
275             }
276             roleDocumentForm.getRoleDocument().addResponsibility(newResponsibility);
277             roleDocumentForm.setResponsibility(new KimDocumentRoleResponsibility());
278             roleDocumentForm.getRoleDocument().updateMembers(newResponsibility);
279         }
280         return mapping.findForward(RiceConstants.MAPPING_BASIC);
281     }
282 
283     public ActionForward deleteResponsibility(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
284         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
285         roleDocumentForm.getRoleDocument().getResponsibilities().remove(getLineToDelete(request));
286         roleDocumentForm.getRoleDocument().updateMembers(roleDocumentForm);
287         return mapping.findForward(RiceConstants.MAPPING_BASIC);
288     }
289 
290     public ActionForward addPermission(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
291         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
292         KimDocumentRolePermission newPermission = roleDocumentForm.getPermission();
293         if (KRADServiceLocatorWeb.getKualiRuleService().applyRules(new AddPermissionEvent("", roleDocumentForm.getRoleDocument(), newPermission))) {
294             newPermission.setDocumentNumber(roleDocumentForm.getDocument().getDocumentNumber());
295             newPermission.setRoleId(roleDocumentForm.getRoleDocument().getRoleId());
296             roleDocumentForm.getRoleDocument().getPermissions().add(newPermission);
297             roleDocumentForm.setPermission(new KimDocumentRolePermission());
298         }
299         return mapping.findForward(RiceConstants.MAPPING_BASIC);
300     }
301 
302     public ActionForward addMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
303         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
304         KimDocumentRoleMember newMember = roleDocumentForm.getMember();
305 
306         //See if possible to add with just Group Details filled in (not returned from lookup)
307         if ( StringUtils.equals(newMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.GROUP_MEMBER_TYPE.getCode())
308                 && StringUtils.isEmpty(newMember.getMemberId())
309                 && !newMember.isMemberNameNull()
310                 && !newMember.isMemberNameSpaceCodeNull() ) {
311             Group tempGroup = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(
312                     newMember.getMemberNamespaceCode(), newMember.getMemberName());
313             if (tempGroup != null) {
314                 newMember.setMemberId(tempGroup.getId());
315             }
316         }
317 
318         //See if possible to grab details for Principal
319         if ( StringUtils.equals(newMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode())
320                 && StringUtils.isEmpty(newMember.getMemberId())
321                 && StringUtils.isNotEmpty(newMember.getMemberName())) {
322             Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(newMember.getMemberName());
323             if (principal != null) {
324                 newMember.setMemberId(principal.getPrincipalId());
325                 String fullName = checkMemberFullName(principal.getPrincipalId());
326                 if (fullName != null) {
327                     newMember.setMemberFullName(fullName);
328                 }
329             }
330         } else if ( StringUtils.equals(newMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode())
331                 && StringUtils.isNotEmpty(newMember.getMemberId())
332                 && StringUtils.isNotEmpty(newMember.getMemberName())) {
333             String fullName = checkMemberFullName(newMember.getMemberId());
334             if (fullName != null) {
335                 newMember.setMemberFullName(fullName);
336             }
337         }
338 
339         if (checkKimDocumentRoleMember(newMember) &&
340                 KRADServiceLocatorWeb.getKualiRuleService().applyRules(new AddMemberEvent("", roleDocumentForm.getRoleDocument(), newMember))) {
341             newMember.setDocumentNumber(roleDocumentForm.getDocument().getDocumentNumber());
342             roleDocumentForm.getRoleDocument().addMember(newMember);
343             roleDocumentForm.setMember(roleDocumentForm.getRoleDocument().getBlankMember());
344         }
345         return mapping.findForward(RiceConstants.MAPPING_BASIC);
346     }
347 
348     protected String checkMemberFullName(String principalId) {
349         Principal principal = getIdentityService().getPrincipal(principalId);
350         if (principal != null) {
351             Person psn = KimApiServiceLocator.getPersonService().getPersonByPrincipalName(principal.getPrincipalName());
352             if (psn != null) {
353                 return psn.getFirstName() + " " + psn.getLastName();
354             }
355         }
356         return null;
357     }
358 
359     protected boolean checkKimDocumentRoleMember(KimDocumentRoleMember newMember) {
360         boolean memberExists = false;
361         String memberName = null;
362         String memberNamespace = null;
363 
364         if (StringUtils.isBlank(newMember.getMemberId())) {
365             GlobalVariables.getMessageMap().putError("document.member.memberId", RiceKeyConstants.ERROR_EMPTY_ENTRY,
366                     new String[]{"Member ID"});
367             return false;
368         }
369 
370         if (MemberType.PRINCIPAL.getCode().equals(newMember.getMemberTypeCode())) {
371             Principal pi = this.getIdentityService().getPrincipal(newMember.getMemberId());
372             if (pi != null) {
373                 memberExists = true;
374                 memberName = pi.getPrincipalName();
375                 memberNamespace = "";
376             }
377         } else if (MemberType.GROUP.getCode().equals(newMember.getMemberTypeCode())) {
378             Group gi = KimApiServiceLocator.getGroupService().getGroup(newMember.getMemberId());
379             if (gi != null) {
380                 memberExists = true;
381                 memberName = gi.getName();
382                 memberNamespace = gi.getNamespaceCode();
383             }
384         } else if (MemberType.ROLE.getCode().equals(newMember.getMemberTypeCode())) {
385             Role ri = KimApiServiceLocator.getRoleService().getRole(newMember.getMemberId());
386             if (!validateRole(newMember.getMemberId(), ri, "document.member.memberId", "Role")) {
387                 return false;
388             } else {
389                 memberExists = true;
390                 memberName = ri.getName();
391                 memberNamespace = ri.getNamespaceCode();
392             }
393         }
394 
395         if (!memberExists) {
396             GlobalVariables.getMessageMap().putError("document.member.memberId", RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
397                     new String[]{newMember.getMemberId()});
398             return false;
399         }
400         newMember.setMemberName(memberName);
401         newMember.setMemberNamespaceCode(memberNamespace);
402         return true;
403     }
404 
405     public ActionForward deleteMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
406         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
407         KimDocumentRoleMember inactivatedRoleMember = roleDocumentForm.getRoleDocument().getModifiedMembers().get(getLineToDelete(request));
408 
409         // KULRICE-4762: active delegates of "inactivated" role members cause validation problems
410         ActionForward forward = promptForAffectedDelegates(mapping, form, request, response,
411                 roleDocumentForm, /* we haven't actually inactivated them yet, so specify them here */ inactivatedRoleMember);
412         // if we need to prompt the user due to affected delegates, do so:
413         if (forward != null) {
414             return forward;
415         }
416 
417         Calendar cal = Calendar.getInstance();
418         inactivatedRoleMember.setActiveToDate(new Timestamp(cal.getTimeInMillis()));
419 
420         roleDocumentForm.getRoleDocument().getModifiedMembers().set(getLineToDelete(request), inactivatedRoleMember);
421         return mapping.findForward(RiceConstants.MAPPING_BASIC);
422     }
423 
424     public ActionForward editMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
425         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
426         KimDocumentRoleMember roleMemberToEdit = roleDocumentForm.getRoleDocument().getMembers().get(getLineToEdit(request));
427         KimDocumentRoleMember copiedMember = (KimDocumentRoleMember) SerializationUtils.deepCopy(roleMemberToEdit);
428         roleDocumentForm.getRoleDocument().getModifiedMembers().add(copiedMember);
429         roleDocumentForm.getRoleDocument().getMembers().remove(roleMemberToEdit);
430         return mapping.findForward(RiceConstants.MAPPING_BASIC);
431     }
432 
433     public ActionForward editSearchResultsMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
434         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
435         KimDocumentRoleMember roleMemberToEdit = roleDocumentForm.getRoleDocument().getSearchResultMembers().get(getLineToEdit(request));
436         KimDocumentRoleMember copiedMember = (KimDocumentRoleMember)SerializationUtils.deepCopy(roleMemberToEdit);
437         roleDocumentForm.getRoleDocument().getModifiedMembers().add(copiedMember);
438         roleDocumentForm.getRoleDocument().getSearchResultMembers().remove(roleMemberToEdit);
439         roleDocumentForm.getRoleDocument().getMembers().remove(roleMemberToEdit);
440         return mapping.findForward(RiceConstants.MAPPING_BASIC);
441     }
442 
443     public ActionForward search(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
444         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
445         String memberSearchValue = roleDocumentForm.getMemberSearchValue();
446         if (memberSearchValue != null && !memberSearchValue.isEmpty()) {
447             memberSearchValue = memberSearchValue.replaceAll("[%*]","");
448             getUiDocumentService().loadRoleMembersBasedOnSearch(roleDocumentForm.getRoleDocument(), memberSearchValue);
449         } else {
450             clear(mapping, form, request, response);
451         }
452         return mapping.findForward(RiceConstants.MAPPING_BASIC);
453     }
454 
455     public ActionForward clear(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
456         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
457         roleDocumentForm.setMemberSearchValue("");
458         getUiDocumentService().clearRestrictedRoleMembersSearchResults(roleDocumentForm.getRoleDocument());
459 
460         KualiTableRenderFormMetadata memberTableMetadata = roleDocumentForm.getMemberTableMetadata();
461         if (roleDocumentForm.getMemberRows() != null) {
462             memberTableMetadata.jumpToFirstPage(roleDocumentForm.getMemberRows().size(), roleDocumentForm.getRecordsPerPage());
463         }
464         return mapping.findForward(RiceConstants.MAPPING_BASIC);
465     }
466 
467     public ActionForward deletePermission(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
468         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
469         roleDocumentForm.getRoleDocument().getPermissions().remove(getLineToDelete(request));
470         return mapping.findForward(RiceConstants.MAPPING_BASIC);
471     }
472 
473     protected boolean checkDelegationMember(RoleDocumentDelegationMember newMember) {
474         if (StringUtils.isBlank(newMember.getMemberTypeCode()) || StringUtils.isBlank(newMember.getMemberId())) {
475             GlobalVariables.getMessageMap().putError("document.delegationMember.memberId", RiceKeyConstants.ERROR_EMPTY_ENTRY,
476                     new String[]{"Member Type Code and Member ID"});
477             return false;
478         }
479         if (MemberType.PRINCIPAL.getCode().equals(newMember.getMemberTypeCode())) {
480             Principal principalInfo = getIdentityService().getPrincipal(newMember.getMemberId());
481             if (principalInfo == null) {
482                 GlobalVariables.getMessageMap().putError("document.delegationMember.memberId", RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
483                         new String[]{newMember.getMemberId()});
484                 return false;
485             } else {
486                 newMember.setMemberName(principalInfo.getPrincipalName());
487             }
488         } else if (MemberType.GROUP.getCode().equals(newMember.getMemberTypeCode())) {
489             Group groupInfo = null;
490             groupInfo = getGroupService().getGroup(newMember.getMemberId());
491             if (groupInfo == null) {
492                 GlobalVariables.getMessageMap().putError("document.delegationMember.memberId", RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
493                         new String[]{newMember.getMemberId()});
494                 return false;
495             } else {
496                 newMember.setMemberName(groupInfo.getName());
497                 newMember.setMemberNamespaceCode(groupInfo.getNamespaceCode());
498             }
499         } else if (MemberType.ROLE.getCode().equals(newMember.getMemberTypeCode())) {
500             Role roleInfo = KimApiServiceLocator.getRoleService().getRole(newMember.getMemberId());
501             if (roleInfo == null) {
502                 GlobalVariables.getMessageMap().putError("document.delegationMember.memberId", RiceKeyConstants.ERROR_MEMBERID_MEMBERTYPE_MISMATCH,
503                         new String[]{newMember.getMemberId()});
504                 return false;
505             } else {
506                 newMember.setMemberName(roleInfo.getName());
507                 newMember.setMemberNamespaceCode(roleInfo.getNamespaceCode());
508             }
509         }
510         return true;
511     }
512 
513     public ActionForward addDelegationMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
514         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
515         RoleDocumentDelegationMember newDelegationMember = roleDocumentForm.getDelegationMember();
516 
517         //See if possible to add with just Group Details filled in (not returned from lookup)
518         if (StringUtils.isEmpty(newDelegationMember.getMemberId())
519                 && StringUtils.isNotEmpty(newDelegationMember.getMemberName())
520                 && StringUtils.isNotEmpty(newDelegationMember.getMemberNamespaceCode())
521                 && StringUtils.equals(newDelegationMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.GROUP_MEMBER_TYPE.getCode())) {
522             Group tempGroup = KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(
523                     newDelegationMember.getMemberNamespaceCode(), newDelegationMember.getMemberName());
524             if (tempGroup != null) {
525                 newDelegationMember.setMemberId(tempGroup.getId());
526             }
527         }
528 
529         //See if possible to grab details for Principal
530         if (StringUtils.isEmpty(newDelegationMember.getMemberId())
531                 && StringUtils.isNotEmpty(newDelegationMember.getMemberName())
532                 && StringUtils.equals(newDelegationMember.getMemberTypeCode(), KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode())) {
533             Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(newDelegationMember.getMemberName());
534             if (principal != null) {
535                 newDelegationMember.setMemberId(principal.getPrincipalId());
536             }
537         }
538 
539         if (checkDelegationMember(newDelegationMember) && KRADServiceLocatorWeb.getKualiRuleService().applyRules(
540                 new AddDelegationMemberEvent("", roleDocumentForm.getRoleDocument(), newDelegationMember))) {
541             newDelegationMember.setDocumentNumber(roleDocumentForm.getDocument().getDocumentNumber());
542             if (StringUtils.isEmpty(newDelegationMember.getDelegationTypeCode())) {
543                newDelegationMember.setDelegationTypeCode(DelegationType.SECONDARY.getCode());
544             }
545             roleDocumentForm.getRoleDocument().addDelegationMember(newDelegationMember);
546             roleDocumentForm.setDelegationMember(roleDocumentForm.getRoleDocument().getBlankDelegationMember());
547         }
548         return mapping.findForward(RiceConstants.MAPPING_BASIC);
549     }
550 
551     public ActionForward deleteDelegationMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
552         IdentityManagementRoleDocumentForm roleDocumentForm = (IdentityManagementRoleDocumentForm) form;
553         // Removing, not inactivating -- is this what we really want?
554         roleDocumentForm.getRoleDocument().getDelegationMembers().remove(getLineToDelete(request));
555         roleDocumentForm.setDelegationMember(roleDocumentForm.getRoleDocument().getBlankDelegationMember());
556         return mapping.findForward(RiceConstants.MAPPING_BASIC);
557     }
558 
559     /**
560      * @see org.kuali.rice.kns.web.struts.action.KualiTableRenderAction#switchToPage(org.apache.struts.action.ActionMapping,
561      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
562      */
563     public ActionForward jumpToRoleMember(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
564         IdentityManagementRoleDocumentForm idmForm = (IdentityManagementRoleDocumentForm) form;
565         String delegationRoleMemberId = getDelegationRoleMemberToJumpTo(request);
566         KualiTableRenderFormMetadata memberTableMetadata = idmForm.getMemberTableMetadata();
567         memberTableMetadata.jumpToPage(idmForm.getPageNumberOfRoleMemberId(delegationRoleMemberId),
568                 idmForm.getMemberRows().size(), idmForm.getRecordsPerPage());
569         memberTableMetadata.setColumnToSortIndex(memberTableMetadata.getPreviouslySortedColumnIndex());
570         idmForm.setAnchor(delegationRoleMemberId);
571         return mapping.findForward(RiceConstants.MAPPING_BASIC);
572     }
573 
574     protected String getDelegationRoleMemberToJumpTo(HttpServletRequest request) {
575         String delegationRoleMemberIdToJumpTo = "";
576         String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
577         if (StringUtils.isNotBlank(parameterName)) {
578             delegationRoleMemberIdToJumpTo = StringUtils.substringBetween(parameterName, ".dmrmi", ".");
579         }
580         return delegationRoleMemberIdToJumpTo;
581     }
582 
583 
584     /**
585      * Side-effecting method returns an ActionForward if needed for handling prompting of the user about automatically
586      * "inactivating" active delegates of inactive role members.  If the user has already responded "Yes", delegates are
587      * "inactivated" here, and a null forward is returned.  Otherwise, an appropriate forward is returned.
588      *
589      * @param roleMembersToConsiderInactive additional role members to consider inactive for the purposes of this computation
590      */
591     private ActionForward promptForAffectedDelegates(ActionMapping mapping,
592             ActionForm form, HttpServletRequest request,
593             HttpServletResponse response,
594             IdentityManagementRoleDocumentForm roleDocumentForm, KimDocumentRoleMember... roleMembersToConsiderInactive)
595             throws Exception {
596         // KULRICE-4762: Role: Removed an Assignee who has delegations associated with him and now the Role cannot be updated
597         // To solve this issue, prompt for confirmation if there are active delegates for the role member being "inactivated",
598         // and upon confirmation, "inactivate" the delegates too.
599         List<RoleDocumentDelegationMember> activeDelegatesOfInactiveRoleMembers =
600                 getActiveDelegatesOfInactiveRoleMembers(roleDocumentForm, roleMembersToConsiderInactive);
601         ActionForward forward = getAffectedDelegatesQuestionActionForward(activeDelegatesOfInactiveRoleMembers, mapping, form, request,
602                 response, roleDocumentForm);
603         // if the question logic gave us a forward, do it
604         if (forward != null) {
605             return forward;
606         }
607         // otherwise, inactivate affected delegates
608         if (activeDelegatesOfInactiveRoleMembers.size() > 0) {
609             Calendar cal = Calendar.getInstance();
610             // deactivate (inactivate?) delegates
611             for (RoleDocumentDelegationMember delegateToDeactivate : activeDelegatesOfInactiveRoleMembers) {
612                 delegateToDeactivate.setActiveToDate(new Timestamp(cal.getTimeInMillis()));
613             }
614         }
615         return null;
616     }
617 
618     /**
619      * <p>If there are active delegates of an "inactivated" role member, return an ActionForward to prompt the user
620      * letting them know that the delegates will be "inactivated" too if they proceed.
621      * <p>Also, if the user has already responded to the question and the response was (1) "Yes", then return null, signifying
622      * that we can go ahead and take the needed action to "inactivate" the delegates; or (2) "No", then return a basic forward that
623      * will cancel further action.
624      */
625     private ActionForward getAffectedDelegatesQuestionActionForward(List<RoleDocumentDelegationMember> activeDelegatesOfInactiveRoleMembers,
626             ActionMapping mapping, ActionForm form, HttpServletRequest request,
627             HttpServletResponse response,
628             IdentityManagementRoleDocumentForm roleDocumentForm)
629             throws Exception {
630 
631         if (activeDelegatesOfInactiveRoleMembers.size() > 0) {
632             Object question = getQuestion(request);
633             // logic for delegates question
634             if (question == null || !REMOVE_AFFECTED_DELEGATES_QUESTION_ID.equals(question)) {
635                 return performQuestionWithoutInput(mapping, form, request, response, REMOVE_AFFECTED_DELEGATES_QUESTION_ID,
636                         getKualiConfigurationService().getPropertyValueAsString(
637                                 RiceKeyConstants.QUESTION_ACTIVE_DELEGATES_FOR_INACTIVE_MEMBERS),
638                         KRADConstants.CONFIRMATION_QUESTION, roleDocumentForm.getMethodToCall(), StringUtils.EMPTY);
639             }
640             Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
641             if ((REMOVE_AFFECTED_DELEGATES_QUESTION_ID.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
642                 // the question was answered in the affirmative.
643                 // fall through, no special mapping to return
644             } else {
645                 // NO was clicked ... what to do?  Return basic mapping without "inactivating" anything
646                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
647             }
648         }
649 
650         return null;
651     }
652 
653     /**
654      * This method returns a list of all active delegates for role members that are inactive
655      *
656      * @param roleDocumentForm              form bean
657      * @param roleMembersToConsiderInactive additional role members to consider inactive for the purposes of this computation
658      * @return the active delegates of inactive role members
659      */
660     private List<RoleDocumentDelegationMember> getActiveDelegatesOfInactiveRoleMembers(
661             IdentityManagementRoleDocumentForm roleDocumentForm, KimDocumentRoleMember... roleMembersToConsiderInactive) {
662         List<KimDocumentRoleMember> roleMembers = roleDocumentForm.getMemberRows();
663         List<KimDocumentRoleMember> inactiveRoleMembers = new ArrayList<KimDocumentRoleMember>();
664         List<RoleDocumentDelegationMember> activeDelegatesOfInactivatedRoleMembers = new ArrayList<RoleDocumentDelegationMember>();
665 
666         inactiveRoleMembers.addAll(Arrays.asList(roleMembersToConsiderInactive));
667 
668         if (roleMembers != null) {
669             for (KimDocumentRoleMember roleMember : roleMembers) {
670                 if (roleMember != null) {
671                     if (!roleMember.isActive()) {
672                         inactiveRoleMembers.add(roleMember);
673                     }
674                 }
675             }
676         }
677 
678         for (KimDocumentRoleMember inactiveRoleMember : inactiveRoleMembers) {
679             // check if there are delegates for the member being removed
680             List<RoleDocumentDelegationMember> delegationMembers = roleDocumentForm.getRoleDocument().getDelegationMembers();
681             if (delegationMembers != null) {
682                 for (RoleDocumentDelegationMember delegationMember : delegationMembers) {
683                     if (delegationMember != null && delegationMember.isActive()) {
684                         // if the roleMember for this delegation is the same as the inactivatedRoleMember
685                         if (delegationMember.getRoleMemberId().equals(inactiveRoleMember.getRoleMemberId())) {
686                             activeDelegatesOfInactivatedRoleMembers.add(delegationMember);
687                         }
688                     }
689                 }
690             }
691         }
692         return activeDelegatesOfInactivatedRoleMembers;
693     }
694 
695     /**
696      * This method overrides validateRole() from IdentityManagementDocumentActionBase.
697      * The difference with this method is that it allows derived roles.
698      * The base implementation returns false if the role is a derived role.
699      *
700      */
701     @Override
702     protected boolean validateRole(String roleId, Role role, String propertyName, String message) {
703         if (role == null) {
704             GlobalVariables.getMessageMap().putError(propertyName, RiceKeyConstants.ERROR_INVALID_ROLE, roleId);
705             return false;
706         }
707         return true;
708     }
709 
710 
711 }