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.kns.web.struts.action;
17  
18  import org.apache.commons.collections.MapUtils;
19  import org.apache.commons.lang.ArrayUtils;
20  import org.apache.commons.lang.StringUtils;
21  import org.apache.ojb.broker.OptimisticLockException;
22  import org.apache.struts.action.ActionForm;
23  import org.apache.struts.action.ActionForward;
24  import org.apache.struts.action.ActionMapping;
25  import org.apache.struts.upload.FormFile;
26  import org.kuali.rice.core.api.config.property.ConfigurationService;
27  import org.kuali.rice.core.api.util.ConcreteKeyValue;
28  import org.kuali.rice.core.api.util.KeyValue;
29  import org.kuali.rice.core.api.util.RiceConstants;
30  import org.kuali.rice.core.api.util.RiceKeyConstants;
31  import org.kuali.rice.coreservice.framework.parameter.ParameterConstants;
32  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
33  import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
34  import org.kuali.rice.kew.api.KewApiServiceLocator;
35  import org.kuali.rice.kew.api.WorkflowDocument;
36  import org.kuali.rice.kew.api.action.ActionRequest;
37  import org.kuali.rice.kew.api.action.ActionRequestType;
38  import org.kuali.rice.kew.api.action.DocumentActionParameters;
39  import org.kuali.rice.kew.api.action.WorkflowDocumentActionsService;
40  import org.kuali.rice.kew.api.doctype.DocumentType;
41  import org.kuali.rice.kew.api.exception.WorkflowException;
42  import org.kuali.rice.kew.api.KewApiConstants;
43  import org.kuali.rice.kim.api.KimConstants;
44  import org.kuali.rice.kim.api.group.Group;
45  import org.kuali.rice.kim.api.group.GroupService;
46  import org.kuali.rice.kim.api.identity.Person;
47  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
48  import org.kuali.rice.kns.datadictionary.KNSDocumentEntry;
49  import org.kuali.rice.kns.document.MaintenanceDocument;
50  import org.kuali.rice.kns.document.authorization.DocumentAuthorizer;
51  import org.kuali.rice.kns.document.authorization.DocumentAuthorizerBase;
52  import org.kuali.rice.kns.document.authorization.DocumentPresentationController;
53  import org.kuali.rice.kns.question.ConfirmationQuestion;
54  import org.kuali.rice.kns.question.RecallQuestion;
55  import org.kuali.rice.kns.rule.PromptBeforeValidation;
56  import org.kuali.rice.kns.rule.event.PromptBeforeValidationEvent;
57  import org.kuali.rice.kns.service.BusinessObjectAuthorizationService;
58  import org.kuali.rice.kns.service.BusinessObjectMetaDataService;
59  import org.kuali.rice.kns.service.DataDictionaryService;
60  import org.kuali.rice.kns.service.DocumentHelperService;
61  import org.kuali.rice.kns.service.KNSServiceLocator;
62  import org.kuali.rice.kns.util.KNSGlobalVariables;
63  import org.kuali.rice.kns.util.WebUtils;
64  import org.kuali.rice.kns.web.struts.form.BlankFormFile;
65  import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
66  import org.kuali.rice.kns.web.struts.form.KualiForm;
67  import org.kuali.rice.kns.web.struts.form.KualiMaintenanceForm;
68  import org.kuali.rice.krad.UserSession;
69  import org.kuali.rice.krad.UserSessionUtils;
70  import org.kuali.rice.krad.bo.AdHocRoutePerson;
71  import org.kuali.rice.krad.bo.AdHocRouteRecipient;
72  import org.kuali.rice.krad.bo.AdHocRouteWorkgroup;
73  import org.kuali.rice.krad.bo.Attachment;
74  import org.kuali.rice.krad.bo.DocumentHeader;
75  import org.kuali.rice.krad.bo.Note;
76  import org.kuali.rice.krad.bo.PersistableBusinessObject;
77  import org.kuali.rice.krad.datadictionary.DataDictionary;
78  import org.kuali.rice.krad.document.Document;
79  import org.kuali.rice.krad.document.authorization.PessimisticLock;
80  import org.kuali.rice.krad.exception.AuthorizationException;
81  import org.kuali.rice.krad.exception.DocumentAuthorizationException;
82  import org.kuali.rice.krad.exception.UnknownDocumentIdException;
83  import org.kuali.rice.krad.rules.rule.event.AddAdHocRoutePersonEvent;
84  import org.kuali.rice.krad.rules.rule.event.AddAdHocRouteWorkgroupEvent;
85  import org.kuali.rice.krad.rules.rule.event.AddNoteEvent;
86  import org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent;
87  import org.kuali.rice.krad.rules.rule.event.SendAdHocRequestsEvent;
88  import org.kuali.rice.krad.service.AttachmentService;
89  import org.kuali.rice.krad.service.BusinessObjectService;
90  import org.kuali.rice.krad.service.DocumentService;
91  import org.kuali.rice.krad.service.KRADServiceLocator;
92  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
93  import org.kuali.rice.krad.service.KualiRuleService;
94  import org.kuali.rice.krad.service.NoteService;
95  import org.kuali.rice.krad.service.PessimisticLockService;
96  import org.kuali.rice.krad.util.GlobalVariables;
97  import org.kuali.rice.krad.util.KRADConstants;
98  import org.kuali.rice.krad.util.KRADPropertyConstants;
99  import org.kuali.rice.krad.util.KRADUtils;
100 import org.kuali.rice.krad.util.NoteType;
101 import org.kuali.rice.krad.util.ObjectUtils;
102 import org.kuali.rice.krad.util.SessionTicket;
103 import org.kuali.rice.krad.util.UrlFactory;
104 import org.kuali.rice.ksb.api.KsbApiServiceLocator;
105 import org.springmodules.orm.ojb.OjbOperationException;
106 
107 import javax.persistence.EntityManagerFactory;
108 import javax.servlet.http.HttpServletRequest;
109 import javax.servlet.http.HttpServletResponse;
110 import javax.xml.namespace.QName;
111 
112 import java.io.ByteArrayOutputStream;
113 import java.io.IOException;
114 import java.util.ArrayList;
115 import java.util.Enumeration;
116 import java.util.HashMap;
117 import java.util.Iterator;
118 import java.util.List;
119 import java.util.Map;
120 import java.util.Properties;
121 import java.util.Set;
122 
123 
124 /**
125  * This class handles all of the document handling related actions in terms of passing them from here at a central point to the
126  * distributed transactions that actually implement document handling.
127  */
128 public class KualiDocumentActionBase extends KualiAction {
129     private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(KualiDocumentActionBase.class);
130 
131     // COMMAND constants which cause docHandler to load an existing document instead of creating a new one
132     protected static final String[] DOCUMENT_LOAD_COMMANDS = {
133             KewApiConstants.ACTIONLIST_COMMAND,
134             KewApiConstants.DOCSEARCH_COMMAND,
135             KewApiConstants.SUPERUSER_COMMAND,
136             KewApiConstants.HELPDESK_ACTIONLIST_COMMAND};
137 
138     private DataDictionaryService dataDictionaryService;
139     private DocumentHelperService documentHelperService;
140     private DocumentService documentService;
141     private ConfigurationService kualiConfigurationService;
142     private ParameterService parameterService;
143     private PessimisticLockService pessimisticLockService;
144     private KualiRuleService kualiRuleService;
145     private GroupService groupService;
146     private AttachmentService attachmentService;
147     private NoteService noteService;
148     private BusinessObjectAuthorizationService businessObjectAuthorizationService;
149     private BusinessObjectService businessObjectService;
150     private BusinessObjectMetaDataService businessObjectMetaDataService;
151     private EntityManagerFactory entityManagerFactory;
152 
153     @Override
154     protected void checkAuthorization(ActionForm form, String methodToCall) throws AuthorizationException {
155         if (!(form instanceof KualiDocumentFormBase)) {
156             super.checkAuthorization(form, methodToCall);
157         }
158     }
159 
160     /**
161      * Entry point to all actions.
162      * <p/>
163      * NOTE: No need to hook into execute for handling framwork setup anymore. Just implement the methodToCall for the framework
164      * setup, Constants.METHOD_REQUEST_PARAMETER will contain the full parameter, which can be sub stringed for getting framework
165      * parameters.
166      *
167      * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
168      *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
169      */
170     @Override
171     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
172         ActionForward returnForward = mapping.findForward(RiceConstants.MAPPING_BASIC);
173 
174         // if found methodToCall, pass control to that method
175         try {
176             returnForward = super.execute(mapping, form, request, response);
177         } catch (OjbOperationException e) {
178             // special handling for OptimisticLockExceptions
179             OjbOperationException ooe = e;
180 
181             Throwable cause = ooe.getCause();
182             if (cause instanceof OptimisticLockException) {
183                 OptimisticLockException ole = (OptimisticLockException) cause;
184                 GlobalVariables.getMessageMap().putError(KRADConstants.DOCUMENT_ERRORS, RiceKeyConstants.ERROR_OPTIMISTIC_LOCK);
185                 logOjbOptimisticLockException(ole);
186             } else {
187                 // if exceptions are from 'save'
188                 throw e;
189             }
190         } finally {
191             if (form instanceof KualiDocumentFormBase) {
192                 ((KualiDocumentFormBase) form).setMessageMapFromPreviousRequest(GlobalVariables.getMessageMap());
193             }
194         }
195 
196         if (form instanceof KualiDocumentFormBase
197                 && ((KualiDocumentFormBase) form).isHasWorkflowDocument()) {
198             KualiDocumentFormBase formBase = (KualiDocumentFormBase) form;
199             Document document = formBase.getDocument();
200 
201             //KULRICE-2210 fix location of document header population
202             WorkflowDocument workflowDocument = formBase.getDocument().getDocumentHeader().getWorkflowDocument();
203             formBase.populateHeaderFields(workflowDocument);
204             formBase.setDocId(document.getDocumentNumber());
205             //End of KULRICE-2210 fix
206 
207             // check to see if document is a pessimistic lock document
208             if (isFormRepresentingLockObject(formBase)) {
209                 // form represents a document using the BO class PessimisticLock so we need to skip the authorizations in the next logic check
210                 if (LOG.isDebugEnabled()) {
211                     LOG.debug("Form " + formBase + " represents a PessimisticLock BO object");
212                 }
213             } else {
214                 // populates authorization-related fields in KualiDocumentFormBase instances, which are derived from
215                 // information which is contained in the form but which may be unavailable until this point
216                 //DocumentAuthorizer documentAuthorizer = KRADServiceLocatorInternal.getDocumentAuthorizationService().getDocumentAuthorizer(document);
217                 //formBase.populateAuthorizationFields(documentAuthorizer);
218                 populateAuthorizationFields(formBase);
219                 populateAdHocActionRequestCodes(formBase);
220 
221                 //set the formBase into userSession if the document is a session document
222                 UserSession userSession = (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY);
223 
224                 if (WebUtils.isDocumentSession(document, formBase)) {
225                     String formKey = formBase.getFormKey();
226                     if (StringUtils.isBlank(formBase.getFormKey()) || userSession.retrieveObject(formBase.getFormKey()) == null) {
227                         // generate doc form key here if it does not exist
228                         formKey = GlobalVariables.getUserSession().addObjectWithGeneratedKey(form);
229                         formBase.setFormKey(formKey);
230                     }
231                 }
232 
233 
234                 // below used by KualiHttpSessionListener to handle lock expiration
235                 request.getSession().setAttribute(KRADConstants.DOCUMENT_HTTP_SESSION_KEY, document.getDocumentNumber());
236                 // set returnToActionList flag, if needed
237                 if ("displayActionListView".equals(formBase.getCommand())) {
238                     formBase.setReturnToActionList(true);
239                 }
240 
241                 String attachmentEnabled =
242                         getKualiConfigurationService().getPropertyValueAsString(KRADConstants.NOTE_ATTACHMENT_ENABLED);
243                 // Override the document entry
244                 if (attachmentEnabled != null) {
245                     // This is a hack for KULRICE-1602 since the document entry is modified by a
246                     // global configuration that overrides the document templates without some sort
247                     // of rules or control
248                     //DataDictionary dataDictionary = getDataDictionaryService().getDataDictionary();
249                     DataDictionary dataDictionary = getDataDictionaryService().getDataDictionary();
250 
251                     org.kuali.rice.krad.datadictionary.DocumentEntry entry = (org.kuali.rice.krad.datadictionary.DocumentEntry) dataDictionary.getDocumentEntry(document.getClass().getName());
252                     entry.setAllowsNoteAttachments(Boolean.parseBoolean(attachmentEnabled));
253                 }
254                 //the request attribute will be used in KualiRequestProcess#processActionPerform
255                 if (exitingDocument()) {
256                     request.setAttribute(KRADConstants.EXITING_DOCUMENT, Boolean.TRUE);
257                 }
258 
259                 // pessimistic locking
260                 String methodCalledViaDispatch = (String) GlobalVariables.getUserSession().retrieveObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_OBJECT_KEY);
261                 if ((StringUtils.isNotBlank(methodCalledViaDispatch)) && (exitingDocument())) {
262                     GlobalVariables.getUserSession().removeObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY);
263                     attemptLockRelease(document, methodCalledViaDispatch);
264                 }
265                 setupPessimisticLockMessages(document, request);
266                 if (!document.getPessimisticLocks().isEmpty()) {
267                     String warningMinutes = getParameterService().getParameterValueAsString(KRADConstants.KNS_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_DETAIL_TYPE, KRADConstants.SESSION_TIMEOUT_WARNING_MESSAGE_TIME_PARM_NM);
268                     request.setAttribute(KRADConstants.SESSION_TIMEOUT_WARNING_MINUTES, warningMinutes);
269                     request.setAttribute(KRADConstants.SESSION_TIMEOUT_WARNING_MILLISECONDS, (request.getSession().getMaxInactiveInterval() - (Integer.valueOf(warningMinutes) * 60)) * 1000);
270                 }
271             }
272             // Pull in the pending action requests for the document and attach them to the form
273             List<ActionRequest> actionRequests = KewApiServiceLocator.getWorkflowDocumentService().getPendingActionRequests(formBase.getDocId());
274             formBase.setActionRequests(actionRequests);
275         }
276 
277 
278         
279         return returnForward;
280     }
281 
282     protected boolean isFormRepresentingLockObject(KualiDocumentFormBase form) throws Exception {
283         if (form instanceof KualiMaintenanceForm) {
284             KualiMaintenanceForm maintForm = (KualiMaintenanceForm) form;
285             if (ObjectUtils.isNotNull(maintForm.getBusinessObjectClassName())) {
286                 return PessimisticLock.class.isAssignableFrom(Class.forName(((KualiMaintenanceForm) form).getBusinessObjectClassName()));
287             }
288         }
289         return false;
290     }
291 
292     protected void attemptLockRelease(Document document, String methodToCall) {
293         if ((document != null) && (!document.getPessimisticLocks().isEmpty())) {
294             releaseLocks(document, methodToCall);
295             // refresh pessimistic locks in case custom add/remove changes were made
296             document.refreshPessimisticLocks();
297         }
298     }
299 
300     protected void releaseLocks(Document document, String methodToCall) {
301         // first check if the method to call is listed as required lock clearing
302         if (document.getLockClearningMethodNames().contains(methodToCall)) {
303             // find all locks for the current user and remove them
304             getPessimisticLockService().releaseAllLocksForUser(document.getPessimisticLocks(), GlobalVariables.getUserSession().getPerson());
305         }
306     }
307 
308     protected void setupPessimisticLockMessages(Document document, HttpServletRequest request) {
309         List<String> lockMessages = new ArrayList<String>();
310         for (PessimisticLock lock : document.getPessimisticLocks()) {
311             // if lock is owned by current user, do not display message for it
312             if (!lock.isOwnedByUser(GlobalVariables.getUserSession().getPerson())) {
313                 lockMessages.add(generatePessimisticLockMessage(lock));
314             }
315         }
316         request.setAttribute(KRADConstants.PESSIMISTIC_LOCK_MESSAGES, lockMessages);
317     }
318 
319     protected String generatePessimisticLockMessage(PessimisticLock lock) {
320         String descriptor = (lock.getLockDescriptor() != null) ? lock.getLockDescriptor() : "";
321         // TODO: this should be pulled into a properties file
322         return "This document currently has a " + descriptor + " lock owned by " + lock.getOwnedByUser().getName() + " as of " + RiceConstants.getDefaultTimeFormat().format(lock.getGeneratedTimestamp()) + " on " + RiceConstants.getDefaultDateFormat().format(lock.getGeneratedTimestamp());
323     }
324 
325 //    private void saveMessages(HttpServletRequest request) {
326 //        if (!GlobalVariables.getMessageList().isEmpty()) {
327 //            request.setAttribute(KRADConstants.GLOBAL_MESSAGES, GlobalVariables.getMessageList());
328 //        }
329 //    }
330 
331     /**
332      * This method may be used to funnel all document handling through, we could do useful things like log and record various
333      * openings and status Additionally it may be nice to have a single dispatcher that can know how to dispatch to a redirect url
334      * for document specific handling but we may not need that as all we should need is the document to be able to load itself based
335      * on document id and then which actionforward or redirect is pertinent for the document type.
336      *
337      * @param mapping
338      * @param form
339      * @param request
340      * @param response
341      * @return ActionForward
342      * @throws Exception
343      */
344     public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
345         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
346         String command = kualiDocumentFormBase.getCommand();
347 
348         if (kualiDocumentFormBase.getDocId()!= null && getDocumentService().getByDocumentHeaderId(kualiDocumentFormBase.getDocId()) == null) {
349             ConfigurationService kualiConfigurationService = KRADServiceLocator.getKualiConfigurationService();
350             StringBuffer sb = new StringBuffer();
351             sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_URL_KEY));
352             sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_INITIATED_DOCUMENT_URL_KEY));
353             response.sendRedirect(sb.toString());
354             return new ActionForward(KRADConstants.KRAD_INITIATED_DOCUMENT_VIEW_NAME, sb.toString() ,true);
355         }
356         // in all of the following cases we want to load the document
357         if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, command) && kualiDocumentFormBase.getDocId() != null) {
358             loadDocument(kualiDocumentFormBase);
359         } else if (KewApiConstants.INITIATE_COMMAND.equals(command)) {
360             createDocument(kualiDocumentFormBase);
361         } else {
362             LOG.error("docHandler called with invalid parameters");
363             throw new IllegalArgumentException("docHandler called with invalid parameters");
364         }
365 
366         // attach any extra JS from the data dictionary
367         if (LOG.isDebugEnabled()) {
368             LOG.debug("kualiDocumentFormBase.getAdditionalScriptFiles(): " + kualiDocumentFormBase.getAdditionalScriptFiles());
369         }
370         if (kualiDocumentFormBase.getAdditionalScriptFiles().isEmpty()) {
371             KNSDocumentEntry docEntry = (KNSDocumentEntry) getDataDictionaryService().getDataDictionary().getDocumentEntry(kualiDocumentFormBase.getDocument().getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
372             kualiDocumentFormBase.getAdditionalScriptFiles().addAll(docEntry.getWebScriptFiles());
373         }
374         if (KewApiConstants.SUPERUSER_COMMAND.equalsIgnoreCase(command)) {
375             kualiDocumentFormBase.setSuppressAllButtons(true);
376         }
377         return mapping.findForward(RiceConstants.MAPPING_BASIC);
378     }
379 
380     /**
381      * This method loads the document by its provided document header id. This has been abstracted out so that it can be overridden
382      * in children if the need arises.
383      *
384      * @param kualiDocumentFormBase
385      * @throws org.kuali.rice.kew.api.exception.WorkflowException
386      */
387     protected void loadDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
388         String docId = kualiDocumentFormBase.getDocId();
389         Document doc = null;
390         doc = getDocumentService().getByDocumentHeaderId(docId);
391         if (doc == null) {
392             throw new UnknownDocumentIdException("Document no longer exists.  It may have been cancelled before being saved.");
393         }
394         WorkflowDocument workflowDocument = doc.getDocumentHeader().getWorkflowDocument();
395         if (!getDocumentHelperService().getDocumentAuthorizer(doc).canOpen(doc, GlobalVariables.getUserSession().getPerson())) {
396             throw buildAuthorizationException("open", doc);
397         }
398         // re-retrieve the document using the current user's session - remove the system user from the WorkflowDcument object
399         if (workflowDocument != doc.getDocumentHeader().getWorkflowDocument()) {
400             LOG.warn("Workflow document changed via canOpen check");
401             doc.getDocumentHeader().setWorkflowDocument(workflowDocument);
402         }
403         kualiDocumentFormBase.setDocument(doc);
404         WorkflowDocument workflowDoc = doc.getDocumentHeader().getWorkflowDocument();
405         kualiDocumentFormBase.setDocTypeName(workflowDoc.getDocumentTypeName());
406 
407         // KualiDocumentFormBase.populate() needs this updated in the session
408         UserSessionUtils.addWorkflowDocument(GlobalVariables.getUserSession(), workflowDoc);
409     }
410 
411 
412     /**
413      * This method creates a new document of the type specified by the docTypeName property of the given form. This has been
414      * abstracted out so that it can be overridden in children if the need arises.
415      *
416      * @param kualiDocumentFormBase
417      * @throws WorkflowException
418      */
419     protected void createDocument(KualiDocumentFormBase kualiDocumentFormBase) throws WorkflowException {
420         Document doc = getDocumentService().getNewDocument(kualiDocumentFormBase.getDocTypeName());
421         UserSessionUtils.addWorkflowDocument(GlobalVariables.getUserSession(),
422                 doc.getDocumentHeader().getWorkflowDocument());
423 
424         kualiDocumentFormBase.setDocument(doc);
425         kualiDocumentFormBase.setDocTypeName(doc.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
426     }
427 
428     /**
429      * This method will insert the new ad hoc person from the from into the list of ad hoc person recipients, put a new new record
430      * in place and return like normal.
431      *
432      * @param mapping
433      * @param form
434      * @param request
435      * @param response
436      * @return ActionForward
437      * @throws Exception
438      */
439     public ActionForward insertAdHocRoutePerson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
440         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
441         Document document = kualiDocumentFormBase.getDocument();
442 
443 
444         // check authorization for adding ad hoc route person
445         DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
446         if (!documentAuthorizer.canSendAdHocRequests(document, kualiDocumentFormBase.getNewAdHocRoutePerson().getActionRequested(), GlobalVariables.getUserSession().getPerson())) {
447             throw buildAuthorizationException("ad-hoc route", document);
448         }
449 
450         // check business rules
451         boolean rulePassed = getKualiRuleService().applyRules(new AddAdHocRoutePersonEvent(document, kualiDocumentFormBase.getNewAdHocRoutePerson()));
452 
453         // if the rule evaluation passed, let's add the ad hoc route person
454         if (rulePassed) {
455             // uppercase userid for consistency
456 //            kualiDocumentFormBase.getNewAdHocRoutePerson().setId(StringUtils.upperCase(kualiDocumentFormBase.getNewAdHocRoutePerson().getId()));
457             kualiDocumentFormBase.getNewAdHocRoutePerson().setId(kualiDocumentFormBase.getNewAdHocRoutePerson().getId());
458             kualiDocumentFormBase.getAdHocRoutePersons().add(kualiDocumentFormBase.getNewAdHocRoutePerson());
459             AdHocRoutePerson person = new AdHocRoutePerson();
460             kualiDocumentFormBase.setNewAdHocRoutePerson(person);
461         }
462 
463         return mapping.findForward(RiceConstants.MAPPING_BASIC);
464     }
465 
466     /**
467      * This method will delete one of the ad hoc persons from the list of ad hoc persons to route to based on the line number of the
468      * delete button that was clicked. then it will return to the form.
469      *
470      * @param mapping
471      * @param form
472      * @param request
473      * @param response
474      * @return ActionForward
475      * @throws Exception
476      */
477     public ActionForward deleteAdHocRoutePerson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
478         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
479 
480 
481         kualiDocumentFormBase.getAdHocRoutePersons().remove(this.getLineToDelete(request));
482         return mapping.findForward(RiceConstants.MAPPING_BASIC);
483     }
484 
485     /**
486      * This method will insert the new ad hoc workgroup into the list of ad hoc workgroup recipients put a nuew record in place and
487      * then return like normal.
488      *
489      * @param mapping
490      * @param form
491      * @param request
492      * @param response
493      * @return ActionForward
494      * @throws Exception
495      */
496     public ActionForward insertAdHocRouteWorkgroup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
497         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
498         Document document = kualiDocumentFormBase.getDocument();
499 
500         // check authorization for add ad hoc route workgroup
501         DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
502         if (!documentAuthorizer.canSendAdHocRequests(document, kualiDocumentFormBase.getNewAdHocRouteWorkgroup().getActionRequested(), GlobalVariables.getUserSession().getPerson())) {
503             throw buildAuthorizationException("ad-hoc route", document);
504         }
505 
506         // check business rules
507         boolean rulePassed = getKualiRuleService().applyRules(new AddAdHocRouteWorkgroupEvent(document, kualiDocumentFormBase.getNewAdHocRouteWorkgroup()));
508 
509         // if the rule evaluation passed, let's add the ad hoc route workgroup
510         if (rulePassed) {
511             //fill id if not already filled
512             AdHocRouteWorkgroup newWorkgroup = kualiDocumentFormBase.getNewAdHocRouteWorkgroup();
513             if (newWorkgroup.getId() == null) {
514                 newWorkgroup.setId(KimApiServiceLocator.getGroupService().getGroupByNamespaceCodeAndName(
515                         newWorkgroup.getRecipientNamespaceCode(), newWorkgroup.getRecipientName()).getId());
516             }
517             kualiDocumentFormBase.getAdHocRouteWorkgroups().add(newWorkgroup);
518             AdHocRouteWorkgroup workgroup = new AdHocRouteWorkgroup();
519             kualiDocumentFormBase.setNewAdHocRouteWorkgroup(workgroup);
520         }
521 
522         return mapping.findForward(RiceConstants.MAPPING_BASIC);
523     }
524 
525     /**
526      * This method will delete one of the ad hoc workgroups from the list of ad hoc workgroups to route to based on the line number
527      * of the delete button that was clicked. then it will return
528      *
529      * @param mapping
530      * @param form
531      * @param request
532      * @param response
533      * @return ActionForward
534      * @throws Exception
535      */
536     public ActionForward deleteAdHocRouteWorkgroup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
537         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
538 
539         kualiDocumentFormBase.getAdHocRouteWorkgroups().remove(this.getLineToDelete(request));
540         return mapping.findForward(RiceConstants.MAPPING_BASIC);
541     }
542 
543     public ActionForward sendAdHocRequests(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
544         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
545         Document document = kualiDocumentFormBase.getDocument();
546 
547         boolean rulePassed = getKualiRuleService().applyRules(new SendAdHocRequestsEvent(document));
548 
549         if (rulePassed) {
550             getDocumentService().sendAdHocRequests(document, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
551             KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_SEND_AD_HOC_REQUESTS_SUCCESSFUL);
552         }
553 
554         return mapping.findForward(RiceConstants.MAPPING_BASIC);
555     }
556 
557     /**
558      * This method will reload the document.
559      *
560      * @param mapping
561      * @param form
562      * @param request
563      * @param response
564      * @return ActionForward
565      * @throws Exception
566      */
567     public ActionForward reload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
568         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
569         Document document = kualiDocumentFormBase.getDocument();
570 
571         // prepare for the reload action - set doc id and command
572         kualiDocumentFormBase.setDocId(document.getDocumentNumber());
573         kualiDocumentFormBase.setCommand(DOCUMENT_LOAD_COMMANDS[1]);
574 
575         // forward off to the doc handler
576         ActionForward actionForward = docHandler(mapping, form, request, response);
577 
578         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_RELOADED);
579         // TODO: remove this when further testing passed
580 //        if (form instanceof KualiDocumentFormBase) {
581 //            UserSession userSession = (UserSession) request.getSession().getAttribute(RiceConstants.USER_SESSION_KEY);
582 //            // force to recreate formkey in execute method
583 //            if (document instanceof SessionDocumentService && userSession.retrieveObject(kualiDocumentFormBase.getFormKey()) != null) {
584 //        	userSession.removeObject(kualiDocumentFormBase.getFormKey());;
585 //            }
586 //        }
587 
588         return actionForward;
589     }
590 
591     /**
592      * This method will save the document, which will then be available via the action list for the person who saved the document.
593      *
594      * @param mapping
595      * @param form
596      * @param request
597      * @param response
598      * @return ActionForward
599      * @throws Exception
600      */
601     public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
602         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
603         doProcessingAfterPost(kualiDocumentFormBase, request);
604         //get any possible changes to to adHocWorkgroups
605         refreshAdHocRoutingWorkgroupLookups(request, kualiDocumentFormBase);
606         Document document = kualiDocumentFormBase.getDocument();
607 
608         ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "save", "");
609         if (forward != null) {
610             return forward;
611         }
612 
613         // save in workflow
614         getDocumentService().saveDocument(document);
615 
616         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_SAVED);
617         kualiDocumentFormBase.setAnnotation("");
618 
619         // TODO: remove this when further testing passed
620 //        if (form instanceof KualiDocumentFormBase) {
621 //            UserSession userSession = (UserSession) request.getSession().getAttribute(RiceConstants.USER_SESSION_KEY);
622 //            // force to recreate formkey in execute method
623 //            if (document instanceof SessionDocumentService && userSession.retrieveObject(kualiDocumentFormBase.getFormKey()) != null) {
624 //        	userSession.removeObject(kualiDocumentFormBase.getFormKey());;
625 //            }
626 //        }
627 
628         return mapping.findForward(RiceConstants.MAPPING_BASIC);
629     }
630 
631     /**
632      * Checks if the given value matches patterns that indicate sensitive data and if configured to give a warning for sensitive data will
633      * prompt the user to continue
634      *
635      * @param mapping
636      * @param form
637      * @param request
638      * @param response
639      * @param fieldName  - name of field with value being checked
640      * @param fieldValue - value to check for sensitive data
641      * @param caller     - method that should be called back from question
642      * @param context    - additional context that needs to be passed back with the question response
643      * @return ActionForward which contains the question forward, or basic forward if user select no to prompt, otherwise will return null
644      *         to indicate processing should continue
645      * @throws Exception
646      */
647     protected ActionForward checkAndWarnAboutSensitiveData(ActionMapping mapping, ActionForm form,
648                                                            HttpServletRequest request, HttpServletResponse response, String fieldName, String fieldValue, String caller, String context)
649             throws Exception {
650         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
651         Document document = kualiDocumentFormBase.getDocument();
652 
653         boolean containsSensitiveData = KRADUtils.containsSensitiveDataPatternMatch(fieldValue);
654 
655         // check if warning is configured in which case we will prompt, or if not business rules will thrown an error
656         boolean warnForSensitiveData = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(
657                 KRADConstants.KNS_NAMESPACE, ParameterConstants.ALL_COMPONENT,
658                 KRADConstants.SystemGroupParameterNames.SENSITIVE_DATA_PATTERNS_WARNING_IND);
659 
660         // determine if the question has been asked yet
661         Map<String, String> ticketContext = new HashMap<String, String>();
662         ticketContext.put(KRADPropertyConstants.DOCUMENT_NUMBER, document.getDocumentNumber());
663         ticketContext.put(KRADConstants.CALLING_METHOD, caller);
664         ticketContext.put(KRADPropertyConstants.NAME, fieldName);
665 
666         boolean questionAsked = GlobalVariables.getUserSession().hasMatchingSessionTicket(
667                 KRADConstants.SENSITIVE_DATA_QUESTION_SESSION_TICKET, ticketContext);
668 
669         // start in logic for confirming the sensitive data
670         if (containsSensitiveData && warnForSensitiveData && !questionAsked) {
671             Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
672             if (question == null || !KRADConstants.DOCUMENT_SENSITIVE_DATA_QUESTION.equals(question)) {
673 
674                 // question hasn't been asked, prompt to continue
675                 return this.performQuestionWithoutInput(mapping, form, request, response,
676                         KRADConstants.DOCUMENT_SENSITIVE_DATA_QUESTION, getKualiConfigurationService()
677                         .getPropertyValueAsString(RiceKeyConstants.QUESTION_SENSITIVE_DATA_DOCUMENT),
678                         KRADConstants.CONFIRMATION_QUESTION, caller, context);
679             }
680 
681             Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
682             if (question != null && KRADConstants.DOCUMENT_SENSITIVE_DATA_QUESTION.equals(question)) {
683                 // if no button clicked just reload the doc
684                 if (ConfirmationQuestion.NO.equals(buttonClicked)) {
685 
686                     return mapping.findForward(RiceConstants.MAPPING_BASIC);
687                 }
688 
689                 // answered yes, create session ticket so we not to ask question again if there are further question requests
690                 SessionTicket ticket = new SessionTicket(KRADConstants.SENSITIVE_DATA_QUESTION_SESSION_TICKET);
691                 ticket.setTicketContext(ticketContext);
692                 GlobalVariables.getUserSession().putSessionTicket(ticket);
693             }
694         }
695 
696         // return null to indicate processing should continue (no redirect)
697         return null;
698     }
699 
700     /**
701      * This method will verify that the form is representing a {@link PessimisticLock} object and delete it if possible
702      *
703      * @param mapping
704      * @param form
705      * @param request
706      * @param response
707      * @return ActionForward
708      * @throws Exception
709      */
710     public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
711         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
712         if (isFormRepresentingLockObject(kualiDocumentFormBase)) {
713             String idValue = request.getParameter(KRADPropertyConstants.ID);
714             getPessimisticLockService().delete(idValue);
715             return returnToSender(request, mapping, kualiDocumentFormBase);
716         }
717         throw buildAuthorizationException(KRADConstants.DELETE_METHOD, kualiDocumentFormBase.getDocument());
718     }
719 
720     /**
721      * route the document using the document service
722      *
723      * @param mapping
724      * @param form
725      * @param request
726      * @param response
727      * @return ActionForward
728      * @throws Exception
729      */
730     public ActionForward performRouteReport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
731         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
732 
733         kualiDocumentFormBase.setDerivedValuesOnForm(request);
734         ActionForward preRulesForward = promptBeforeValidation(mapping, form, request, response);
735         if (preRulesForward != null) {
736             return preRulesForward;
737         }
738 
739         Document document = kualiDocumentFormBase.getDocument();
740         // check authorization for reloading document
741         //DocumentActionFlags flags = getDocumentActionFlags(document);
742         if (!kualiDocumentFormBase.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_PERFORM_ROUTE_REPORT)) {
743             throw buildAuthorizationException("perform route report", document);
744         }
745 
746         String backUrlBase = getReturnLocation(request, mapping);
747         String globalVariableFormKey = GlobalVariables.getUserSession().addObjectWithGeneratedKey(form);
748         // setup back form variables
749         request.setAttribute("backUrlBase", backUrlBase);
750         List<KeyValue> backFormParameters = new ArrayList<KeyValue>();
751         backFormParameters.add(new ConcreteKeyValue(KRADConstants.DISPATCH_REQUEST_PARAMETER, KRADConstants.RETURN_METHOD_TO_CALL));
752         backFormParameters.add(new ConcreteKeyValue(KRADConstants.DOC_FORM_KEY, globalVariableFormKey));
753         request.setAttribute("backFormHiddenVariables", backFormParameters);
754 
755         // setup route report form variables
756         request.setAttribute("workflowRouteReportUrl", getKualiConfigurationService().getPropertyValueAsString(
757                 KRADConstants.WORKFLOW_URL_KEY) + "/" + KewApiConstants.DOCUMENT_ROUTING_REPORT_PAGE);
758         List<KeyValue> generalRouteReportFormParameters = new ArrayList<KeyValue>();
759         generalRouteReportFormParameters.add(new ConcreteKeyValue(KewApiConstants.INITIATOR_ID_ATTRIBUTE_NAME, document.getDocumentHeader().getWorkflowDocument().getDocument().getInitiatorPrincipalId()));
760         generalRouteReportFormParameters.add(new ConcreteKeyValue(KewApiConstants.DOCUMENT_TYPE_NAME_ATTRIBUTE_NAME, document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName()));
761         // prepareForRouteReport() method should populate document header workflow document application content xml
762         String xml = document.getXmlForRouteReport();
763         if (LOG.isDebugEnabled()) {
764             LOG.debug("XML being used for Routing Report is: " + xml);
765         }
766         generalRouteReportFormParameters.add(new ConcreteKeyValue(KewApiConstants.DOCUMENT_CONTENT_ATTRIBUTE_NAME, xml));
767 
768         // set up the variables for the form if java script is working (includes a close button variable and no back url)
769         List<KeyValue> javaScriptFormParameters = new ArrayList<KeyValue>();
770         javaScriptFormParameters.addAll(generalRouteReportFormParameters);
771         javaScriptFormParameters.add(new ConcreteKeyValue(KewApiConstants.DISPLAY_CLOSE_BUTTON_ATTRIBUTE_NAME, KewApiConstants.DISPLAY_CLOSE_BUTTON_TRUE_VALUE));
772         request.setAttribute("javaScriptFormVariables", javaScriptFormParameters);
773 
774         // set up the variables for the form if java script is NOT working (includes a back url but no close button)
775         List<KeyValue> noJavaScriptFormParameters = new ArrayList<KeyValue>();
776         noJavaScriptFormParameters.addAll(generalRouteReportFormParameters);
777         Properties parameters = new Properties();
778         for (KeyValue pair : backFormParameters) {
779             parameters.put(pair.getKey(), pair.getValue());
780         }
781         noJavaScriptFormParameters.add(new ConcreteKeyValue(KewApiConstants.RETURN_URL_ATTRIBUTE_NAME, UrlFactory.parameterizeUrl(backUrlBase, parameters)));
782         request.setAttribute("noJavaScriptFormVariables", noJavaScriptFormParameters);
783 
784         return mapping.findForward(KRADConstants.MAPPING_ROUTE_REPORT);
785     }
786 
787     /**
788      * route the document using the document service
789      *
790      * @param mapping
791      * @param form
792      * @param request
793      * @param response
794      * @return ActionForward
795      * @throws Exception
796      */
797     public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
798         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
799         doProcessingAfterPost(kualiDocumentFormBase, request);
800 
801         kualiDocumentFormBase.setDerivedValuesOnForm(request);
802         ActionForward preRulesForward = promptBeforeValidation(mapping, form, request, response);
803         if (preRulesForward != null) {
804             return preRulesForward;
805         }
806 
807         Document document = kualiDocumentFormBase.getDocument();
808 
809         ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "route", "");
810         if (forward != null) {
811             return forward;
812         }
813 
814         getDocumentService().routeDocument(document, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
815         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL);
816         kualiDocumentFormBase.setAnnotation("");
817 
818 //        GlobalVariables.getUserSession().addObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY,Boolean.TRUE);
819         return mapping.findForward(RiceConstants.MAPPING_BASIC);
820     }
821 
822     /**
823      * Calls the document service to blanket approve the document
824      *
825      * @param mapping
826      * @param form
827      * @param request
828      * @param response
829      * @return ActionForward
830      * @throws Exception
831      */
832     public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
833         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
834         doProcessingAfterPost(kualiDocumentFormBase, request);
835 
836         kualiDocumentFormBase.setDerivedValuesOnForm(request);
837         ActionForward preRulesForward = promptBeforeValidation(mapping, form, request, response);
838         if (preRulesForward != null) {
839             return preRulesForward;
840         }
841 
842         Document document = kualiDocumentFormBase.getDocument();
843 
844         ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "blanketApprove", "");
845         if (forward != null) {
846             return forward;
847         }
848 
849         getDocumentService().blanketApproveDocument(document, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
850         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_APPROVED);
851         kualiDocumentFormBase.setAnnotation("");
852         return returnToSender(request, mapping, kualiDocumentFormBase);
853     }
854 
855     /**
856      * Calls the document service to approve the document
857      *
858      * @param mapping
859      * @param form
860      * @param request
861      * @param response
862      * @return ActionForward
863      * @throws Exception
864      */
865     public ActionForward approve(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
866         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
867         doProcessingAfterPost(kualiDocumentFormBase, request);
868 
869         kualiDocumentFormBase.setDerivedValuesOnForm(request);
870         ActionForward preRulesForward = promptBeforeValidation(mapping, form, request, response);
871         if (preRulesForward != null) {
872             return preRulesForward;
873         }
874 
875         Document document = kualiDocumentFormBase.getDocument();
876 
877         ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "approve", "");
878         if (forward != null) {
879             return forward;
880         }
881 
882         getDocumentService().approveDocument(document, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
883         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_APPROVED);
884         kualiDocumentFormBase.setAnnotation("");
885         return returnToSender(request, mapping, kualiDocumentFormBase);
886     }
887 
888     /**
889      * Calls the document service to disapprove the document
890      *
891      * @param mapping
892      * @param form
893      * @param request
894      * @param response
895      * @return ActionForward
896      * @throws Exception
897      */
898     public ActionForward disapprove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
899                                     HttpServletResponse response) throws Exception {
900 
901         ReasonPrompt prompt = new ReasonPrompt(KRADConstants.DOCUMENT_DISAPPROVE_QUESTION, RiceKeyConstants.QUESTION_DISAPPROVE_DOCUMENT, KRADConstants.CONFIRMATION_QUESTION, RiceKeyConstants.ERROR_DOCUMENT_DISAPPROVE_REASON_REQUIRED, KRADConstants.MAPPING_DISAPPROVE, ConfirmationQuestion.NO, RiceKeyConstants.MESSAGE_DISAPPROVAL_NOTE_TEXT_INTRO);
902         ReasonPrompt.Response resp = prompt.ask(mapping, form, request, response);
903 
904         if (resp.forward != null) {
905             return resp.forward;
906         }
907 
908         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
909         doProcessingAfterPost(kualiDocumentFormBase, request);
910         getDocumentService().disapproveDocument(kualiDocumentFormBase.getDocument(), resp.reason);
911         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_DISAPPROVED);
912         kualiDocumentFormBase.setAnnotation("");
913 
914         return returnToSender(request, mapping, kualiDocumentFormBase);
915     }
916 
917     /**
918      * Calls the document service to cancel the document
919      *
920      * @param mapping
921      * @param form
922      * @param request
923      * @param response
924      * @return ActionForward
925      * @throws Exception
926      */
927     public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
928         Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
929         // this should probably be moved into a private instance variable
930         // logic for cancel question
931         if (question == null) {
932             // ask question if not already asked
933             return this.performQuestionWithoutInput(mapping, form, request, response, KRADConstants.DOCUMENT_CANCEL_QUESTION, getKualiConfigurationService().getPropertyValueAsString(
934                     "document.question.cancel.text"), KRADConstants.CONFIRMATION_QUESTION, KRADConstants.MAPPING_CANCEL, "");
935         } else {
936             Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
937             if ((KRADConstants.DOCUMENT_CANCEL_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) {
938                 // if no button clicked just reload the doc
939                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
940             }
941             // else go to cancel logic below
942         }
943 
944         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
945         doProcessingAfterPost(kualiDocumentFormBase, request);
946         // KULRICE-4447 Call cancelDocument() only if the document exists
947         if (getDocumentService().documentExists(kualiDocumentFormBase.getDocId())) {
948             getDocumentService().cancelDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation());
949         }
950 
951         return returnToSender(request, mapping, kualiDocumentFormBase);
952     }
953 
954     /**
955      * Calls the document service to disapprove the document
956      *
957      * @param mapping
958      * @param form
959      * @param request
960      * @param response
961      * @return ActionForward
962      * @throws Exception
963      */
964     public ActionForward recall(ActionMapping mapping, ActionForm form, HttpServletRequest request,
965             HttpServletResponse response) throws Exception {
966         
967         ReasonPrompt prompt = new ReasonPrompt(KRADConstants.DOCUMENT_RECALL_QUESTION, RiceKeyConstants.QUESTION_RECALL_DOCUMENT, KRADConstants.RECALL_QUESTION, RiceKeyConstants.ERROR_DOCUMENT_RECALL_REASON_REQUIRED, KRADConstants.MAPPING_RECALL, null, RiceKeyConstants.MESSAGE_RECALL_NOTE_TEXT_INTRO);
968         ReasonPrompt.Response resp = prompt.ask(mapping, form, request, response);
969 
970         if (resp.forward != null) {
971             return resp.forward;
972         }
973         
974         boolean cancel = !((KRADConstants.DOCUMENT_RECALL_QUESTION.equals(resp.question)) && RecallQuestion.RECALL_TO_ACTIONLIST.equals(resp.button));
975 
976         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
977         doProcessingAfterPost(kualiDocumentFormBase, request);
978         getDocumentService().recallDocument(kualiDocumentFormBase.getDocument(), resp.reason, cancel);
979 
980         // just return to doc view
981         return mapping.findForward(RiceConstants.MAPPING_BASIC);
982     }
983 
984     /**
985      * Close the document and take the user back to the index; only after asking the user if they want to save the document first.
986      * Only users who have the "canSave()" permission are given this option.
987      *
988      * @param mapping
989      * @param form
990      * @param request
991      * @param response
992      * @return ActionForward
993      * @throws Exception
994      */
995     public ActionForward close(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
996         KualiDocumentFormBase docForm = (KualiDocumentFormBase) form;
997         doProcessingAfterPost(docForm, request);
998         Document document = docForm.getDocument();
999         // only want to prompt them to save if they already can save
1000         if (canSave(docForm)) {
1001 
1002             Object question = getQuestion(request);
1003             // logic for close question
1004             if (question == null) {
1005                 // KULRICE-7306: Unconverted Values not carried through during a saveOnClose action.
1006                 // Stash the unconverted values to populate errors if the user elects to save
1007                 saveUnconvertedValuesToSession(request, docForm);
1008 
1009                 // ask question if not already asked
1010                 return this.performQuestionWithoutInput(mapping, form, request, response, KRADConstants.DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION, getKualiConfigurationService().getPropertyValueAsString(
1011                         RiceKeyConstants.QUESTION_SAVE_BEFORE_CLOSE), KRADConstants.CONFIRMATION_QUESTION, KRADConstants.MAPPING_CLOSE, "");
1012             } else {
1013                 Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
1014 
1015                 // KULRICE-7306: Unconverted Values not carried through during a saveOnClose action.
1016                 // Side effecting in that it clears the session attribute that holds the unconverted values.
1017                 Map<String, Object> unconvertedValues = restoreUnconvertedValuesFromSession(request, docForm);
1018 
1019                 if ((KRADConstants.DOCUMENT_SAVE_BEFORE_CLOSE_QUESTION.equals(question)) && ConfirmationQuestion.YES.equals(buttonClicked)) {
1020                     // if yes button clicked - save the doc
1021 
1022                     // KULRICE-7306: Unconverted Values not carried through during a saveOnClose action.
1023                     // If there were values that couldn't be converted, we attempt to populate them so that the
1024                     // the appropriate errors get set on those fields
1025                     if (MapUtils.isNotEmpty(unconvertedValues)) for (Map.Entry<String, Object> entry : unconvertedValues.entrySet()) {
1026                         docForm.populateForProperty(entry.getKey(), entry.getValue(), unconvertedValues);
1027                     }
1028 
1029                     ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "save", "");
1030                     if (forward != null) {
1031                         return forward;
1032                     }
1033 
1034                     getDocumentService().saveDocument(docForm.getDocument());
1035                 }
1036                 // else go to close logic below
1037             }
1038         }
1039 
1040         return returnToSender(request, mapping, docForm);
1041     }
1042 
1043     // stash unconvertedValues in the session
1044     private void saveUnconvertedValuesToSession(HttpServletRequest request, KualiDocumentFormBase docForm) {
1045         if (MapUtils.isNotEmpty(docForm.getUnconvertedValues())) {
1046             request.getSession().setAttribute(getUnconvertedValuesSessionAttributeKey(docForm), new HashMap(docForm.getUnconvertedValues()));
1047         }
1048     }
1049 
1050     // SIDE EFFECTING: clears out unconverted values from the Session and restores them to the form
1051     private Map<String, Object> restoreUnconvertedValuesFromSession(HttpServletRequest request,
1052             KualiDocumentFormBase docForm) {// first restore unconvertedValues and clear out of session
1053         Map<String, Object> unconvertedValues =
1054                 (Map<String, Object>)request.getSession().getAttribute(getUnconvertedValuesSessionAttributeKey(docForm));
1055         if (MapUtils.isNotEmpty(unconvertedValues)) {
1056             request.getSession().removeAttribute(getUnconvertedValuesSessionAttributeKey(docForm));
1057             docForm.setUnconvertedValues(unconvertedValues); // setting them here just for good measure
1058         }
1059         return unconvertedValues;
1060     }
1061 
1062     // create the key based on docId for stashing/retrieving unconvertedValues in the session
1063     private String getUnconvertedValuesSessionAttributeKey(KualiDocumentFormBase docForm) {
1064         return "preCloseUnconvertedValues." + docForm.getDocId();
1065     }
1066 
1067     protected boolean canSave(ActionForm form) {
1068         KualiDocumentFormBase docForm = (KualiDocumentFormBase) form;
1069         return docForm.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_CAN_SAVE);
1070     }
1071 
1072     protected Object getQuestion(HttpServletRequest request) {
1073         return request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
1074     }
1075 
1076     /**
1077      * call the document service to clear the fyis
1078      *
1079      * @param mapping
1080      * @param form
1081      * @param request
1082      * @param response
1083      * @return ActionForward
1084      * @throws Exception
1085      */
1086     public ActionForward fyi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1087         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1088         doProcessingAfterPost(kualiDocumentFormBase, request);
1089         getDocumentService().clearDocumentFyi(kualiDocumentFormBase.getDocument(), combineAdHocRecipients(kualiDocumentFormBase));
1090         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_FYIED);
1091         kualiDocumentFormBase.setAnnotation("");
1092         return returnToSender(request, mapping, kualiDocumentFormBase);
1093     }
1094 
1095     /**
1096      * call the document service to acknowledge
1097      *
1098      * @param mapping
1099      * @param form
1100      * @param request
1101      * @param response
1102      * @return ActionForward
1103      * @throws Exception
1104      */
1105     public ActionForward acknowledge(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1106         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1107         doProcessingAfterPost(kualiDocumentFormBase, request);
1108         getDocumentService().acknowledgeDocument(kualiDocumentFormBase.getDocument(), kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
1109         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_ACKNOWLEDGED);
1110         kualiDocumentFormBase.setAnnotation("");
1111         return returnToSender(request, mapping, kualiDocumentFormBase);
1112     }
1113 
1114     /**
1115      * redirect to the supervisor functions that exist.
1116      *
1117      * @param mapping
1118      * @param form
1119      * @param request
1120      * @param response
1121      * @return ActionForward
1122      * @throws Exception
1123      */
1124     public ActionForward supervisorFunctions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1125         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1126 
1127 
1128         String workflowSuperUserUrl = getKualiConfigurationService().getPropertyValueAsString(
1129                 KRADConstants.WORKFLOW_URL_KEY) + "/SuperUser.do?methodToCall=displaySuperUserDocument&documentId=" + kualiDocumentFormBase.getDocument().getDocumentHeader().getDocumentNumber();
1130         response.sendRedirect(workflowSuperUserUrl);
1131 
1132         return null;
1133     }
1134 
1135     /**
1136      * Convenience method to combine the two lists of ad hoc recipients into one which should be done before calling any of the
1137      * document service methods that expect a list of ad hoc recipients
1138      *
1139      * @param kualiDocumentFormBase
1140      * @return List
1141      */
1142     protected List<AdHocRouteRecipient> combineAdHocRecipients(KualiDocumentFormBase kualiDocumentFormBase) {
1143         List<AdHocRouteRecipient> adHocRecipients = new ArrayList<AdHocRouteRecipient>();
1144         adHocRecipients.addAll(kualiDocumentFormBase.getAdHocRoutePersons());
1145         adHocRecipients.addAll(kualiDocumentFormBase.getAdHocRouteWorkgroups());
1146         return adHocRecipients;
1147     }
1148 
1149     /**
1150      * if the action desires to retain error messages generated by the rules framework for save/submit/etc. validation after returning from a lookup.
1151      *
1152      * @see KualiAction#refresh(org.apache.struts.action.ActionMapping,
1153      *      org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1154      */
1155     @Override
1156     public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1157         KualiDocumentFormBase kualiForm = (KualiDocumentFormBase) form;
1158         kualiForm.setDerivedValuesOnForm(request);
1159 
1160         super.refresh(mapping, form, request, response);
1161         refreshAdHocRoutingWorkgroupLookups(request, kualiForm);
1162 
1163         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1164     }
1165 
1166     /**
1167      * special refresh needed to get the workgroups populated correctly when coming back from workgroup lookups
1168      *
1169      * @param request
1170      * @param kualiForm
1171      * @throws WorkflowException
1172      */
1173     @SuppressWarnings("unchecked")
1174     protected void refreshAdHocRoutingWorkgroupLookups(HttpServletRequest request, KualiDocumentFormBase kualiForm) throws WorkflowException {
1175         for (Enumeration<String> i = request.getParameterNames(); i.hasMoreElements();) {
1176             String parameterName = i.nextElement();
1177             if (parameterName.equals("newAdHocRouteWorkgroup.recipientName") && !"".equals(request.getParameter(parameterName))) {
1178                 //check for namespace
1179                 String namespace = KimConstants.KIM_GROUP_DEFAULT_NAMESPACE_CODE;
1180                 if (request.getParameter("newAdHocRouteWorkgroup.recipientNamespaceCode") != null && !"".equals(request.getParameter("newAdHocRouteWorkgroup.recipientNamespaceCode").trim())) {
1181                     namespace = request.getParameter("newAdHocRouteWorkgroup.recipientNamespaceCode").trim();
1182                 }
1183                 Group group = getGroupService().getGroupByNamespaceCodeAndName(namespace, request.getParameter(
1184                         parameterName));
1185                 if (group != null) {
1186                     kualiForm.getNewAdHocRouteWorkgroup().setId(group.getId());
1187                     kualiForm.getNewAdHocRouteWorkgroup().setRecipientName(group.getName());
1188                     kualiForm.getNewAdHocRouteWorkgroup().setRecipientNamespaceCode(group.getNamespaceCode());
1189                 } else {
1190                     GlobalVariables.getMessageMap().putError("newAdHocRouteWorkgroup.recipientNamespaceCode", RiceKeyConstants.ERROR_INVALID_ADHOC_WORKGROUP_NAMESPACECODE);
1191                     return;
1192                 }
1193             }
1194             if (parameterName.startsWith("adHocRouteWorkgroup[") && !"".equals(request.getParameter(parameterName))) {
1195                 if (parameterName.endsWith(".recipientName")) {
1196                     int lineNumber = Integer.parseInt(StringUtils.substringBetween(parameterName, "[", "]"));
1197                     //check for namespace
1198                     String namespaceParam = "adHocRouteWorkgroup[" + lineNumber + "].recipientNamespaceCode";
1199                     String namespace = KimConstants.KIM_GROUP_DEFAULT_NAMESPACE_CODE;
1200                     if (request.getParameter(namespaceParam) != null && !"".equals(request.getParameter(namespaceParam).trim())) {
1201                         namespace = request.getParameter(namespaceParam).trim();
1202                     }
1203                     Group group = getGroupService().getGroupByNamespaceCodeAndName(namespace, request.getParameter(
1204                             parameterName));
1205                     if (group != null) {
1206                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setId(group.getId());
1207                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setRecipientName(group.getName());
1208                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setRecipientNamespaceCode(group.getNamespaceCode());
1209                     } else {
1210                         GlobalVariables.getMessageMap().putError(namespaceParam, RiceKeyConstants.ERROR_INVALID_ADHOC_WORKGROUP_NAMESPACECODE);
1211                         return;
1212                     }
1213                 }
1214             }
1215             /*
1216             if (parameterName.startsWith("newAdHocRouteWorkgroup[") && !"".equals(request.getParameter(parameterName))) {
1217                 if (parameterName.endsWith(".recipientName")) {
1218                     int lineNumber = Integer.parseInt(StringUtils.substringBetween(parameterName, "[", "]"));
1219                   //check for namespace
1220                     String namespaceParam = "newAdHocRouteWorkgroup[" + lineNumber + "].recipientNamespaceCode";
1221                     String namespace = KimApiConstants.KIM_GROUP_DEFAULT_NAMESPACE_CODE;
1222                     if (request.getParameter(namespaceParam) != null && !"".equals(request.getParameter(namespaceParam).trim())) {
1223                         namespace = request.getParameter(namespaceParam).trim();
1224                     }
1225                     KimGroup group = getIdentityManagementService().getGroupByNamespaceCodeAndName(namespace, request.getParameter(parameterName));
1226                     if (group != null) {
1227                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setId(group.getGroupId());
1228                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setRecipientName(group.getGroupName());
1229                         kualiForm.getAdHocRouteWorkgroup(lineNumber).setRecipientNamespaceCode(group.getNamespaceCode());
1230                     } else {
1231                         throw new RuntimeException("Invalid workgroup id passed as parameter.");
1232                     }
1233                 }
1234             }
1235             */
1236         }
1237     }
1238 
1239 
1240     /**
1241      * Cancels the pending attachment, if any.
1242      *
1243      * @param mapping
1244      * @param form
1245      * @param request
1246      * @param response
1247      * @return ActionForward
1248      * @throws Exception
1249      */
1250     public ActionForward cancelBOAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1251         KualiDocumentFormBase documentForm = (KualiDocumentFormBase) form;
1252 
1253         // blank current attachmentFile
1254         documentForm.setAttachmentFile(new BlankFormFile());
1255 
1256         // remove current attachment, if any
1257         Note note = documentForm.getNewNote();
1258         note.removeAttachment();
1259         documentForm.setNewNote(note);
1260 
1261         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1262     }
1263 
1264     /**
1265      * Handy method to stream the byte array to response object
1266      *
1267      * @param fileContents
1268      * @param fileName
1269      * @param fileContentType
1270      * @param response
1271      * @throws Exception
1272      */
1273     protected void streamToResponse(byte[] fileContents, String fileName, String fileContentType, HttpServletResponse response) throws Exception {
1274         ByteArrayOutputStream baos = null;
1275         try {
1276             baos = new ByteArrayOutputStream(fileContents.length);
1277             baos.write(fileContents);
1278             WebUtils.saveMimeOutputStreamAsFile(response, fileContentType, baos, fileName);
1279         } finally {
1280             try {
1281                 if (baos != null) {
1282                     baos.close();
1283                     baos = null;
1284                 }
1285             } catch (IOException ioEx) {
1286                 LOG.error("Error while downloading attachment");
1287                 throw new RuntimeException("IOException occurred while downloading attachment", ioEx);
1288             }
1289         }
1290     }
1291 
1292     /**
1293      * Downloads the selected attachment to the user's browser
1294      *
1295      * @param mapping
1296      * @param form
1297      * @param request
1298      * @param response
1299      * @return ActionForward
1300      * @throws Exception
1301      */
1302     public ActionForward downloadBOAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1303         KualiDocumentFormBase documentForm = (KualiDocumentFormBase) form;
1304 
1305         int attachmentIndex = selectedAttachmentIndex(request);
1306         if (attachmentIndex >= 0) {
1307             Note note = documentForm.getDocument().getNote(attachmentIndex);
1308             Attachment attachment = note.getAttachment();
1309             //make sure attachment is setup with backwards reference to note (rather then doing this we could also just call the attachment service (with a new method that took in the note)
1310             attachment.setNote(note);
1311 
1312             // since we're downloading a file, all of the editable properties from the previous request will continue to be editable.
1313             documentForm.copyPopulateEditablePropertiesToActionEditableProperties();
1314 
1315             WebUtils.saveMimeInputStreamAsFile(response, attachment.getAttachmentMimeTypeCode(), attachment.getAttachmentContents(), attachment.getAttachmentFileName(), attachment.getAttachmentFileSize().intValue());
1316             return null;
1317         }
1318 
1319         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1320     }
1321 
1322 
1323     /**
1324      * @param request
1325      * @return index of the attachment whose download button was just pressed
1326      */
1327     protected int selectedAttachmentIndex(HttpServletRequest request) {
1328         int attachmentIndex = -1;
1329 
1330         String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
1331         if (StringUtils.isNotBlank(parameterName)) {
1332             String attachmentIndexParam = StringUtils.substringBetween(parameterName, ".attachment[", "].");
1333 
1334             try {
1335                 attachmentIndex = Integer.parseInt(attachmentIndexParam);
1336             } catch (NumberFormatException ignored) {
1337             }
1338         }
1339 
1340         return attachmentIndex;
1341     }
1342 
1343 
1344     /**
1345      * insert a note into the document
1346      *
1347      * @param mapping
1348      * @param form
1349      * @param request
1350      * @param response
1351      * @return ActionForward
1352      * @throws Exception
1353      */
1354     public ActionForward insertBONote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1355         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1356         Document document = kualiDocumentFormBase.getDocument();
1357         Note newNote = kualiDocumentFormBase.getNewNote();
1358         newNote.setNotePostedTimestampToCurrent();
1359 
1360         String attachmentTypeCode = null;
1361 
1362         FormFile attachmentFile = kualiDocumentFormBase.getAttachmentFile();
1363         if (attachmentFile == null) {
1364             GlobalVariables.getMessageMap().putError(
1365                     String.format("%s.%s",
1366                             KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
1367                             KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME),
1368                     RiceKeyConstants.ERROR_UPLOADFILE_NULL);
1369             // This line was removed in order to continue to validates other
1370             // return mapping.findForward(RiceConstants.MAPPING_BASIC);
1371         }
1372 
1373         if (newNote.getAttachment() != null) {
1374             attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode();
1375         }
1376 
1377         // check authorization for adding notes
1378         DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
1379         if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode, GlobalVariables.getUserSession().getPerson())) {
1380             throw buildAuthorizationException("annotate", document);
1381         }
1382 
1383         // create the attachment first, so that failure-to-create-attachment can be treated as a validation failure
1384 
1385         Attachment attachment = null;
1386         if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getFileName())) {
1387             if (attachmentFile.getFileSize() == 0) {
1388                 GlobalVariables.getMessageMap().putError(
1389                         String.format("%s.%s",
1390                                 KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
1391                                 KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME),
1392                         RiceKeyConstants.ERROR_UPLOADFILE_EMPTY,
1393                         attachmentFile.getFileName());
1394                 // This line was removed in order to continue to validates other
1395 //                return mapping.findForward(RiceConstants.MAPPING_BASIC);
1396             } else {
1397                 String attachmentType = null;
1398                 Attachment newAttachment = kualiDocumentFormBase.getNewNote().getAttachment();
1399                 if (newAttachment != null) {
1400                     attachmentType = newAttachment.getAttachmentTypeCode();
1401                 }
1402                 attachment = getAttachmentService().createAttachment(document.getNoteTarget(), attachmentFile.getFileName(), attachmentFile.getContentType(), attachmentFile.getFileSize(), attachmentFile.getInputStream(), attachmentType);
1403             }
1404         }
1405 
1406         DataDictionary dataDictionary = getDataDictionaryService().getDataDictionary();
1407         org.kuali.rice.krad.datadictionary.DocumentEntry entry = dataDictionary.getDocumentEntry(document.getClass().getName());
1408 
1409         if (entry.getDisplayTopicFieldInNotes()) {
1410             String topicText = kualiDocumentFormBase.getNewNote().getNoteTopicText();
1411             if (StringUtils.isBlank(topicText)) {
1412                 GlobalVariables.getMessageMap().putError(
1413                         String.format("%s.%s",
1414                                 KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
1415                                 KRADConstants.NOTE_TOPIC_TEXT_PROPERTY_NAME),
1416                         RiceKeyConstants.ERROR_REQUIRED,
1417                         "Note Topic (Note Topic)");
1418             }
1419         }
1420 
1421         // create a new note from the data passed in
1422         // TODO gah! this is awful
1423         Person kualiUser = GlobalVariables.getUserSession().getPerson();
1424         if (kualiUser == null) {
1425             throw new IllegalStateException("Current UserSession has a null Person.");
1426         }
1427         Note tmpNote = getNoteService().createNote(newNote, document.getNoteTarget(), kualiUser.getPrincipalId());
1428 
1429         ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response, KRADPropertyConstants.NOTE, tmpNote.getNoteText(), "insertBONote", "");
1430         if (forward != null) {
1431             return forward;
1432         }
1433 
1434         // validate the note
1435         boolean rulePassed = getKualiRuleService().applyRules(new AddNoteEvent(document, tmpNote));
1436 
1437         // if the rule evaluation passed, let's add the note
1438         if (rulePassed) {
1439             tmpNote.refresh();
1440 
1441 
1442             DocumentHeader documentHeader = document.getDocumentHeader();
1443 
1444             // associate note with object now
1445             document.addNote(tmpNote);
1446 
1447             // persist the note if the document is already saved the getObjectId check is to get around a bug with certain documents where
1448             // "saved" doesn't really persist, if you notice any problems with missing notes check this line
1449             //maintenance document BO note should only be saved into table when document is in the PROCESSED workflow status
1450             if (!documentHeader.getWorkflowDocument().isInitiated() && StringUtils.isNotEmpty(document.getNoteTarget().getObjectId())
1451                     && !(document instanceof MaintenanceDocument && NoteType.BUSINESS_OBJECT.getCode().equals(tmpNote.getNoteTypeCode()))
1452                     ) {
1453                 getNoteService().save(tmpNote);
1454             }
1455             // adding the attachment after refresh gets called, since the attachment record doesn't get persisted
1456             // until the note does (and therefore refresh doesn't have any attachment to autoload based on the id, nor does it
1457             // autopopulate the id since the note hasn't been persisted yet)
1458             if (attachment != null) {
1459                 tmpNote.addAttachment(attachment);
1460                 // save again for attachment, note this is because sometimes the attachment is added first to the above then ojb tries to save
1461                 //without the PK on the attachment I think it is safer then trying to get the sequence manually
1462                 if (!documentHeader.getWorkflowDocument().isInitiated() && StringUtils.isNotEmpty(document.getNoteTarget().getObjectId())
1463                         && !(document instanceof MaintenanceDocument && NoteType.BUSINESS_OBJECT.getCode().equals(tmpNote.getNoteTypeCode()))
1464                         ) {
1465                     getNoteService().save(tmpNote);
1466                 }
1467             }
1468 
1469 
1470             // reset the new note back to an empty one
1471             kualiDocumentFormBase.setNewNote(new Note());
1472         }
1473 
1474 
1475         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1476     }
1477 
1478     /**
1479      * delete a note from the document
1480      *
1481      * @param mapping
1482      * @param form
1483      * @param request
1484      * @param response
1485      * @return ActionForward
1486      * @throws Exception
1487      */
1488     public ActionForward deleteBONote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1489         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1490         Document document = kualiDocumentFormBase.getDocument();
1491 
1492 
1493 //        DataDictionary dataDictionary = getDataDictionaryService().getDataDictionary();
1494 //        DocumentEntry entry = dataDictionary.getDocumentEntry(document.getClass().getName());
1495 
1496         // check authorization for adding notes
1497         //DocumentActionFlags flags = getDocumentActionFlags(document);
1498         //if (!kualiDocumentFormBase.getDocumentActions().containsKey(KRADConstants.KUALI_ACTION_CAN_ANNOTATE)) {
1499         //    buildAuthorizationException("annotate", document);
1500         //    return mapping.findForward(RiceConstants.MAPPING_BASIC);
1501         //}
1502 
1503         // ok to delete the note/attachment
1504         // derive the note property from the newNote on the form
1505         Note newNote = kualiDocumentFormBase.getNewNote();
1506         Note note = document.getNote(getLineToDelete(request));
1507         Attachment attachment = note.getAttachment();
1508         String attachmentTypeCode = null;
1509         if (attachment != null) {
1510             attachmentTypeCode = attachment.getAttachmentTypeCode();
1511         }
1512         String authorUniversalIdentifier = note.getAuthorUniversalIdentifier();
1513         if (!WebUtils.canDeleteNoteAttachment(document, attachmentTypeCode, authorUniversalIdentifier)) {
1514             throw buildAuthorizationException("annotate", document);
1515         }
1516 
1517         if (attachment != null) { // only do this if the note has been persisted
1518             //KFSMI-798 - refresh() changed to refreshNonUpdateableReferences()
1519             //All references for the business object Attachment are auto-update="none",
1520             //so refreshNonUpdateableReferences() should work the same as refresh()
1521             if (note.getNoteIdentifier() != null) { // KULRICE-2343 don't blow away note reference if the note wasn't persisted
1522                 attachment.refreshNonUpdateableReferences();
1523             }
1524             getAttachmentService().deleteAttachmentContents(attachment);
1525         }
1526         // delete the note if the document is already saved
1527         if (!document.getDocumentHeader().getWorkflowDocument().isInitiated()) {
1528             getNoteService().deleteNote(note);
1529         }
1530         document.removeNote(note);
1531 
1532         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1533     }
1534 
1535     /**
1536      * Override this to customize which routing action to take when sending a note.  This method reads the system parameter
1537      * KR-NS/Document/SEND_NOTE_WORKFLOW_NOTIFICATION_ACTIONS to determine which action to take
1538      *
1539      * @param request
1540      * @param note
1541      * @return a value from {@link KewApiConstants}
1542      */
1543     protected String determineNoteWorkflowNotificationAction(HttpServletRequest request, KualiDocumentFormBase kualiDocumentFormBase, Note note) {
1544         return getParameterService().getParameterValueAsString(KRADConstants.KNS_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_DETAIL_TYPE, KRADConstants.SEND_NOTE_WORKFLOW_NOTIFICATION_ACTIONS_PARM_NM);
1545     }
1546 
1547     public ActionForward sendNoteWorkflowNotification(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1548         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1549         Document document = kualiDocumentFormBase.getDocument();
1550 
1551         Note note = document.getNote(getSelectedLine(request));
1552 
1553         // verify recipient was specified
1554         if (StringUtils.isBlank(note.getAdHocRouteRecipient().getId())) {
1555             GlobalVariables.getMessageMap().putError(KRADPropertyConstants.NEW_DOCUMENT_NOTE, RiceKeyConstants.ERROR_SEND_NOTE_NOTIFICATION_RECIPIENT);
1556             return mapping.findForward(RiceConstants.MAPPING_BASIC);
1557         }
1558         // check recipient is valid
1559         else {
1560             note.getAdHocRouteRecipient().setActionRequested(determineNoteWorkflowNotificationAction(request, kualiDocumentFormBase, note));
1561 
1562             boolean rulePassed = getKualiRuleService().applyRules(new AddAdHocRoutePersonEvent(KRADPropertyConstants.NEW_DOCUMENT_NOTE, document, (AdHocRoutePerson) note.getAdHocRouteRecipient()));
1563             if (!rulePassed) {
1564                 return mapping.findForward(RiceConstants.MAPPING_BASIC);
1565             }
1566         }
1567 
1568         // if document is saved, send notification
1569         if (!document.getDocumentHeader().getWorkflowDocument().isInitiated()) {
1570             getDocumentService().sendNoteRouteNotification(document, note, GlobalVariables.getUserSession().getPerson());
1571 
1572             // add success message
1573             KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_SEND_NOTE_NOTIFICATION_SUCCESSFUL);
1574         } else {
1575             GlobalVariables.getMessageMap().putError(KRADPropertyConstants.NEW_DOCUMENT_NOTE, RiceKeyConstants.ERROR_SEND_NOTE_NOTIFICATION_DOCSTATUS);
1576         }
1577 
1578         return mapping.findForward(RiceConstants.MAPPING_BASIC);
1579     }
1580 
1581 
1582     /**
1583      * Generates detailed log messages for OptimisticLockExceptions
1584      *
1585      * @param e
1586      */
1587     private final void logOjbOptimisticLockException(OptimisticLockException e) {
1588         if (LOG.isInfoEnabled()) {
1589             StringBuffer message = new StringBuffer("caught OptimisticLockException, caused by ");
1590             Object sourceObject = e.getSourceObject();
1591             String infix = null;
1592             try {
1593                 // try to add instance details
1594                 infix = sourceObject.toString();
1595             } catch (Exception e2) {
1596                 // just use the class name
1597                 infix = sourceObject.getClass().getName();
1598             }
1599             message.append(infix);
1600 
1601             if (sourceObject instanceof PersistableBusinessObject) {
1602                 PersistableBusinessObject persistableObject = (PersistableBusinessObject) sourceObject;
1603                 message.append(" [versionNumber = ").append(persistableObject.getVersionNumber()).append("]");
1604             }
1605 
1606             LOG.info(message.toString(), e);
1607         }
1608     }
1609 
1610 
1611     /**
1612      * Makes calls to the PromptBeforeValidation specified for the document. If the class returns an actionforward, that forward
1613      * will be returned (thus controlling how execution occurs), or null.
1614      *
1615      * @param mapping
1616      * @param form
1617      * @param request
1618      * @param response
1619      * @return
1620      * @throws Exception
1621      */
1622     public ActionForward promptBeforeValidation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1623         return promptBeforeValidation(mapping, form, request, response, "route");
1624     }
1625 
1626     /**
1627      * Makes calls to the PromptBeforeValidation specified for the document. If the class returns an actionforward, that forward
1628      * will be returned (thus controlling how execution occurs), or null.
1629      *
1630      * @param mapping
1631      * @param form
1632      * @param request
1633      * @param response
1634      * @param methodToCall
1635      * @return
1636      * @throws Exception
1637      */
1638     public ActionForward promptBeforeValidation(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String methodToCall) throws Exception {
1639         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
1640 
1641         /* callback to any pre rules check class */
1642         Class<? extends PromptBeforeValidation> promptBeforeValidationClass = getDataDictionaryService().getPromptBeforeValidationClass(kualiDocumentFormBase.getDocTypeName());
1643         if (LOG.isDebugEnabled()) {
1644             LOG.debug("PromptBeforeValidationClass: " + promptBeforeValidationClass);
1645         }
1646         if (promptBeforeValidationClass != null) {
1647             PromptBeforeValidation promptBeforeValidation = promptBeforeValidationClass.newInstance();
1648             PromptBeforeValidationEvent event = new PromptBeforeValidationEvent("Pre Maint route Check", "", kualiDocumentFormBase.getDocument());
1649             boolean continueRoute = promptBeforeValidation.processPrompts(form, request, event);
1650             if (!continueRoute) {
1651                 if (event.isPerformQuestion()) {
1652                     return super.performQuestionWithoutInput(mapping, kualiDocumentFormBase, request, response, event.getQuestionId(), event.getQuestionText(), event.getQuestionType(), methodToCall, event.getQuestionContext());
1653                 } else {
1654                     // This error section is here to avoid a silent and very confusing failure. If the PreRule
1655                     // instance returns a null for the processPreRuleChecks above, but does not set an
1656                     // ActionForwardName on the event, processing will just silently fail here, and the user
1657                     // will be presented with a blank frame.
1658                     //
1659                     // If the processPreRuleCheck() returns a false, an ActionForwardName needs to be set before hand
1660                     // by the PreRule class.
1661                     ActionForward actionForward = mapping.findForward(event.getActionForwardName());
1662                     if (actionForward == null) {
1663                         throw new RuntimeException("No ActionForwardName defined on this Event, no further actions will be processed.");
1664                     }
1665                     return actionForward;
1666                 }
1667             }
1668         }
1669 
1670         return null;
1671     }
1672 
1673 
1674     /**
1675      * Convenience method for building authorization exceptions
1676      *
1677      * @param action
1678      * @param document
1679      */
1680     protected DocumentAuthorizationException buildAuthorizationException(String action, Document document) {
1681         return new DocumentAuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), action, document.getDocumentNumber());
1682     }
1683 
1684     protected boolean exitingDocument() {
1685     	String methodCalledViaDispatch = (String) GlobalVariables.getUserSession().retrieveObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_OBJECT_KEY);
1686         String methodCompleted = (String) GlobalVariables.getUserSession().retrieveObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY);
1687         return StringUtils.isNotEmpty(methodCompleted) && StringUtils.isNotEmpty(methodCalledViaDispatch) && methodCompleted.startsWith(methodCalledViaDispatch);
1688     }
1689 
1690     protected void setupDocumentExit() {
1691     	String methodCalledViaDispatch = (String) GlobalVariables.getUserSession().retrieveObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_OBJECT_KEY);
1692     	if(StringUtils.isNotEmpty(methodCalledViaDispatch)) {
1693     		GlobalVariables.getUserSession().addObject(DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_OBJECT_KEY, (Object) (methodCalledViaDispatch + DocumentAuthorizerBase.USER_SESSION_METHOD_TO_CALL_COMPLETE_MARKER));
1694     	}
1695     }
1696 
1697     /**
1698      * If the given form has returnToActionList set to true, this method returns an ActionForward that should take the user back to
1699      * their action list; otherwise, it returns them to the portal.
1700      *
1701      * @param form
1702      * @return
1703      */
1704     protected ActionForward returnToSender(HttpServletRequest request, ActionMapping mapping, KualiDocumentFormBase form) {
1705         final ActionForward dest;
1706         if (form.isReturnToActionList()) {
1707             String workflowBase = getKualiConfigurationService().getPropertyValueAsString(
1708                     KRADConstants.WORKFLOW_URL_KEY);
1709             String actionListUrl = workflowBase + "/ActionList.do";
1710 
1711             dest = new ActionForward(actionListUrl, true);
1712         } else if (StringUtils.isNotBlank(form.getBackLocation())) {
1713             dest = new ActionForward(form.getBackLocation(), true);
1714         } else {
1715             dest = mapping.findForward(KRADConstants.MAPPING_PORTAL);
1716         }
1717 
1718         setupDocumentExit();
1719         return dest;
1720     }
1721 
1722     @SuppressWarnings("unchecked")
1723     protected void populateAuthorizationFields(KualiDocumentFormBase formBase) {
1724         if (formBase.isFormDocumentInitialized()) {
1725             Document document = formBase.getDocument();
1726             Person user = GlobalVariables.getUserSession().getPerson();
1727             DocumentPresentationController documentPresentationController = KNSServiceLocator
1728                     .getDocumentHelperService().getDocumentPresentationController(document);
1729             DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
1730             Set<String> documentActions = documentPresentationController.getDocumentActions(document);
1731             documentActions = documentAuthorizer.getDocumentActions(document, user, documentActions);
1732 
1733             if (getDataDictionaryService().getDataDictionary().getDocumentEntry(document.getClass().getName()).getUsePessimisticLocking()) {
1734                 documentActions = getPessimisticLockService().getDocumentActions(document, user, documentActions);
1735             }
1736 
1737             //DocumentActionFlags flags = new DocumentActionFlags();
1738             formBase.setDocumentActions(convertSetToMap(documentActions));
1739 
1740         }
1741     }
1742 
1743     protected void populateAdHocActionRequestCodes(KualiDocumentFormBase formBase) {
1744         Document document = formBase.getDocument();
1745         DocumentAuthorizer documentAuthorizer = getDocumentHelperService().getDocumentAuthorizer(document);
1746         Map<String, String> adHocActionRequestCodes = new HashMap<String, String>();
1747 
1748         if (documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_FYI_REQ, GlobalVariables.getUserSession().getPerson())) {
1749             adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_FYI_REQ, KewApiConstants.ACTION_REQUEST_FYI_REQ_LABEL);
1750         }
1751         if (!document.getDocumentHeader().getWorkflowDocument().isFinal() && documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, GlobalVariables.getUserSession().getPerson())) {
1752             adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ_LABEL);
1753         }
1754         if (!(document.getDocumentHeader().getWorkflowDocument().isApproved() || document.getDocumentHeader().getWorkflowDocument().isProcessed() || document.getDocumentHeader().getWorkflowDocument().isFinal()) && documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_APPROVE_REQ, GlobalVariables.getUserSession().getPerson())) {
1755             adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_APPROVE_REQ, KewApiConstants.ACTION_REQUEST_APPROVE_REQ_LABEL);
1756         }
1757 
1758         if ((document.getDocumentHeader().getWorkflowDocument().isInitiated() || document.getDocumentHeader().getWorkflowDocument().isSaved())
1759                 && documentAuthorizer.canSendAdHocRequests(document, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ, GlobalVariables.getUserSession().getPerson())) {
1760             // Check if there is already a request for completion pending for the document.
1761             adHocActionRequestCodes.put(KewApiConstants.ACTION_REQUEST_COMPLETE_REQ, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ_LABEL);
1762         }
1763         formBase.setAdHocActionRequestCodes(adHocActionRequestCodes);
1764 
1765     }
1766 
1767 
1768     @SuppressWarnings("unchecked")
1769     protected Map convertSetToMap(Set s) {
1770         Map map = new HashMap();
1771         Iterator i = s.iterator();
1772         while (i.hasNext()) {
1773             Object key = i.next();
1774             map.put(key, KRADConstants.KUALI_DEFAULT_TRUE_VALUE);
1775         }
1776         return map;
1777     }
1778 
1779     /**
1780      * @return the dataDictionaryService
1781      */
1782     protected DataDictionaryService getDataDictionaryService() {
1783         if (dataDictionaryService == null) {
1784             dataDictionaryService = KNSServiceLocator.getDataDictionaryService();
1785         }
1786         return dataDictionaryService;
1787     }
1788 
1789     protected DocumentHelperService getDocumentHelperService() {
1790         if (documentHelperService == null) {
1791             documentHelperService = KNSServiceLocator.getDocumentHelperService();
1792         }
1793         return this.documentHelperService;
1794     }
1795 
1796     protected DocumentService getDocumentService() {
1797         if (documentService == null) {
1798             documentService = KRADServiceLocatorWeb.getDocumentService();
1799         }
1800         return this.documentService;
1801     }
1802 
1803     protected ConfigurationService getKualiConfigurationService() {
1804         if (kualiConfigurationService == null) {
1805             kualiConfigurationService = KRADServiceLocator.getKualiConfigurationService();
1806         }
1807         return this.kualiConfigurationService;
1808     }
1809 
1810     protected ParameterService getParameterService() {
1811         if (parameterService == null) {
1812             parameterService = CoreFrameworkServiceLocator.getParameterService();
1813         }
1814         return this.parameterService;
1815     }
1816 
1817     protected PessimisticLockService getPessimisticLockService() {
1818         if (pessimisticLockService == null) {
1819             pessimisticLockService = KRADServiceLocatorWeb.getPessimisticLockService();
1820         }
1821         return this.pessimisticLockService;
1822     }
1823 
1824     protected KualiRuleService getKualiRuleService() {
1825         if (kualiRuleService == null) {
1826             kualiRuleService = KRADServiceLocatorWeb.getKualiRuleService();
1827         }
1828         return this.kualiRuleService;
1829     }
1830 
1831     protected GroupService getGroupService() {
1832         if (groupService == null) {
1833             groupService = KimApiServiceLocator.getGroupService();
1834         }
1835         return this.groupService;
1836     }
1837 
1838     protected AttachmentService getAttachmentService() {
1839         if (attachmentService == null) {
1840             attachmentService = KRADServiceLocator.getAttachmentService();
1841         }
1842         return this.attachmentService;
1843     }
1844 
1845     protected NoteService getNoteService() {
1846         if (noteService == null) {
1847             noteService = KRADServiceLocator.getNoteService();
1848         }
1849         return this.noteService;
1850     }
1851 
1852     protected BusinessObjectService getBusinessObjectService() {
1853         if (businessObjectService == null) {
1854             businessObjectService = KRADServiceLocator.getBusinessObjectService();
1855         }
1856         return this.businessObjectService;
1857     }
1858 
1859     @Override
1860     protected BusinessObjectAuthorizationService getBusinessObjectAuthorizationService() {
1861         if (businessObjectAuthorizationService == null) {
1862             businessObjectAuthorizationService = KNSServiceLocator.getBusinessObjectAuthorizationService();
1863         }
1864         return businessObjectAuthorizationService;
1865     }
1866 
1867     public BusinessObjectMetaDataService getBusinessObjectMetaDataService() {
1868         if (businessObjectMetaDataService == null) {
1869             businessObjectMetaDataService = KNSServiceLocator.getBusinessObjectMetaDataService();
1870         }
1871         return this.businessObjectMetaDataService;
1872     }
1873 
1874     public EntityManagerFactory getEntityManagerFactory() {
1875         if (entityManagerFactory == null) {
1876             entityManagerFactory = KRADServiceLocator.getApplicationEntityManagerFactory();
1877         }
1878         return this.entityManagerFactory;
1879     }
1880 
1881     /**
1882      * @see KualiAction#hideAllTabs(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1883      */
1884     @Override
1885     public ActionForward hideAllTabs(ActionMapping mapping, ActionForm form,
1886                                      HttpServletRequest request, HttpServletResponse response)
1887             throws Exception {
1888         if (form instanceof KualiDocumentFormBase) {
1889             WebUtils.reuseErrorMapFromPreviousRequest((KualiDocumentFormBase) form);
1890         }
1891         return super.hideAllTabs(mapping, form, request, response);
1892     }
1893 
1894     /**
1895      * @see KualiAction#showAllTabs(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1896      */
1897     @Override
1898     public ActionForward showAllTabs(ActionMapping mapping, ActionForm form,
1899                                      HttpServletRequest request, HttpServletResponse response)
1900             throws Exception {
1901         if (form instanceof KualiDocumentFormBase) {
1902             WebUtils.reuseErrorMapFromPreviousRequest((KualiDocumentFormBase) form);
1903         }
1904         return super.showAllTabs(mapping, form, request, response);
1905     }
1906 
1907     /**
1908      * @see KualiAction#toggleTab(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
1909      */
1910     @Override
1911     public ActionForward toggleTab(ActionMapping mapping, ActionForm form,
1912                                    HttpServletRequest request, HttpServletResponse response)
1913             throws Exception {
1914         if (form instanceof KualiDocumentFormBase) {
1915             WebUtils.reuseErrorMapFromPreviousRequest((KualiDocumentFormBase) form);
1916         }
1917         return super.toggleTab(mapping, form, request, response);
1918     }
1919 
1920     @Override
1921     protected void doProcessingAfterPost(KualiForm form, HttpServletRequest request) {
1922         super.doProcessingAfterPost(form, request);
1923         if (form instanceof KualiDocumentFormBase) {
1924             Document document = ((KualiDocumentFormBase) form).getDocument();
1925 
1926             getBusinessObjectService().linkUserFields(document);
1927         }
1928     }
1929 
1930     /**
1931      * Class that encapsulates the workflow for obtaining an reason from an action prompt.
1932      */
1933     private class ReasonPrompt {
1934         final String questionId;
1935         final String questionTextKey;
1936         final String questionType;
1937         final String missingReasonKey;
1938         final String questionCallerMapping;
1939         final String abortButton;
1940         final String noteIntroKey;
1941 
1942         private class Response {
1943             final String question;
1944             final ActionForward forward;
1945             final String reason;
1946             final String button;
1947             Response(String question, ActionForward forward) {
1948                 this(question, forward, null, null);
1949             }
1950             Response(String question, String reason, String button) {
1951                 this(question, null, reason, button);
1952             }
1953             private Response(String question, ActionForward forward, String reason, String button) {
1954                 this.question = question;
1955                 this.forward = forward;
1956                 this.reason = reason;
1957                 this.button = button;
1958             }
1959         }
1960 
1961         /**
1962          * @param questionId the question id/instance, 
1963          * @param questionTextKey application resources key for question text
1964          * @param questionType the {@link org.kuali.rice.kns.question.Question} question type
1965          * @param questionCallerMapping mapping of original action
1966          * @param abortButton button value considered to abort the prompt and return (optional, may be null)
1967          * @param noteIntroKey application resources key for quesiton text prefix (optional, may be null)
1968          */
1969         private ReasonPrompt(String questionId, String questionTextKey, String questionType, String missingReasonKey, String questionCallerMapping, String abortButton, String noteIntroKey) {
1970             this.questionId = questionId;
1971             this.questionTextKey = questionTextKey;
1972             this.questionType = questionType;
1973             this.questionCallerMapping = questionCallerMapping;
1974             this.abortButton = abortButton;
1975             this.noteIntroKey = noteIntroKey;
1976             this.missingReasonKey = missingReasonKey;
1977         }
1978 
1979         /**
1980          * Obtain a validated reason and button value via a Question prompt.  Reason is validated against
1981          * sensitive data patterns, and max Note text length
1982          * @param mapping Struts mapping
1983          * @param form Struts form
1984          * @param request http request
1985          * @param response http response
1986          * @return Response object representing *either*: 1) an ActionForward due to error or abort 2) a reason and button clicked
1987          * @throws Exception
1988          */
1989         public Response ask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
1990             String question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
1991             String reason = request.getParameter(KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME);
1992 
1993             if (StringUtils.isBlank(reason)) {
1994                 String context = request.getParameter(KRADConstants.QUESTION_CONTEXT);
1995                 if (context != null && StringUtils.contains(context, KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME + "=")) {
1996                     reason = StringUtils.substringAfter(context, KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME + "=");
1997                 }
1998             }
1999 
2000             String disapprovalNoteText = "";
2001 
2002             // start in logic for confirming the disapproval
2003             if (question == null) {
2004                 // ask question if not already asked
2005                 return new Response(question, performQuestionWithInput(mapping, form, request, response,
2006                         this.questionId,
2007                         getKualiConfigurationService().getPropertyValueAsString(this.questionTextKey),
2008                         this.questionType, this.questionCallerMapping, ""));
2009             }
2010 
2011             String buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
2012             if (this.questionId.equals(question) && abortButton != null && abortButton.equals(buttonClicked)) {
2013                 // if no button clicked just reload the doc
2014                 return new Response(question, mapping.findForward(RiceConstants.MAPPING_BASIC));
2015             }
2016 
2017             // have to check length on value entered
2018             String introNoteMessage = "";
2019             if (noteIntroKey != null) {
2020                 introNoteMessage = getKualiConfigurationService().getPropertyValueAsString(this.noteIntroKey) + KRADConstants.BLANK_SPACE;
2021             }
2022 
2023             // build out full message
2024             disapprovalNoteText = introNoteMessage + reason;
2025 
2026             // check for sensitive data in note
2027             boolean warnForSensitiveData = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(
2028                     KRADConstants.KNS_NAMESPACE, ParameterConstants.ALL_COMPONENT,
2029                     KRADConstants.SystemGroupParameterNames.SENSITIVE_DATA_PATTERNS_WARNING_IND);
2030             if (warnForSensitiveData) {
2031                 String context = KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME + "=" + reason;
2032                 ActionForward forward = checkAndWarnAboutSensitiveData(mapping, form, request, response,
2033                         KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, disapprovalNoteText, this.questionCallerMapping, context);
2034                 if (forward != null) {
2035                     return new Response(question, forward);
2036                 }
2037             } else {
2038                 if (KRADUtils.containsSensitiveDataPatternMatch(disapprovalNoteText)) {
2039                     return new Response(question, performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response,
2040                             this.questionId, getKualiConfigurationService().getPropertyValueAsString(this.questionTextKey),
2041                             this.questionType, this.questionCallerMapping, "", reason,
2042                             RiceKeyConstants.ERROR_DOCUMENT_FIELD_CONTAINS_POSSIBLE_SENSITIVE_DATA,
2043                             KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, "reason"));
2044                 }
2045             }
2046 
2047             int disapprovalNoteTextLength = disapprovalNoteText.length();
2048 
2049             // get note text max length from DD
2050             int noteTextMaxLength = getDataDictionaryService().getAttributeMaxLength(Note.class, KRADConstants.NOTE_TEXT_PROPERTY_NAME);
2051 
2052             if (StringUtils.isBlank(reason) || (disapprovalNoteTextLength > noteTextMaxLength)) {
2053 
2054                 if (reason == null) {
2055                     // prevent a NPE by setting the reason to a blank string
2056                     reason = "";
2057                 }
2058                 return new Response(question, performQuestionWithInputAgainBecauseOfErrors(mapping, form, request, response,
2059                         this.questionId,
2060                         getKualiConfigurationService().getPropertyValueAsString(this.questionTextKey),
2061                         this.questionType, this.questionCallerMapping, "", reason,
2062                         this.missingReasonKey,
2063                         KRADConstants.QUESTION_REASON_ATTRIBUTE_NAME, Integer.toString(noteTextMaxLength)));
2064             }
2065 
2066             return new Response(question, disapprovalNoteText, buttonClicked);
2067         }
2068     }
2069 
2070     public ActionForward takeSuperUserActions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
2071         KualiDocumentFormBase documentForm = (KualiDocumentFormBase)form;
2072         if(StringUtils.isBlank(documentForm.getSuperUserAnnotation())) {
2073             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.takeactions.annotation.missing", "");
2074             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2075         } else if(documentForm.getSelectedActionRequests().isEmpty()) {
2076             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.takeactions.none.selected", "");
2077             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2078         }  else if (!documentForm.isStateAllowsApproveSingleActionRequest()) {
2079             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.takeactions.not.allowed", "");
2080             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2081         }
2082 
2083         for(String actionRequestId : documentForm.getSelectedActionRequests()) {
2084             ActionRequest actionRequest = null;
2085             for(ActionRequest pendingActionRequest : documentForm.getActionRequests()) {
2086                 if(StringUtils.equals(pendingActionRequest.getId(), actionRequestId)) {
2087                     actionRequest = pendingActionRequest;
2088                     break;
2089                 }
2090             }
2091             if(actionRequest == null) {
2092                 // If the action request isn't pending then skip it
2093                 continue;
2094             }
2095             if (StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.COMPLETE.getCode()) ||
2096                 StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.APPROVE.getCode())) {
2097                     getDocumentService().validateAndPersistDocument(documentForm.getDocument(), new RouteDocumentEvent(documentForm.getDocument()));
2098             }
2099 
2100             WorkflowDocumentActionsService documentActions = getWorkflowDocumentActionsService(documentForm.getWorkflowDocument().getDocumentTypeId());
2101             DocumentActionParameters parameters = DocumentActionParameters.create(documentForm.getDocId(), GlobalVariables.getUserSession().getPrincipalId(), documentForm.getSuperUserAnnotation());
2102             documentActions.superUserTakeRequestedAction(parameters, true, actionRequestId);
2103             String messageString;
2104             if (StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.ACKNOWLEDGE.getCode())) {
2105                 messageString = "general.routing.superuser.actionRequestAcknowledged";
2106             } else if (StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.FYI.getCode())) {
2107                 messageString = "general.routing.superuser.actionRequestFYI";
2108             } else if (StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.COMPLETE.getCode())) {
2109                 messageString = "general.routing.superuser.actionRequestCompleted";
2110             } else if (StringUtils.equals(actionRequest.getActionRequested().getCode(), ActionRequestType.APPROVE.getCode())) {
2111                 messageString = "general.routing.superuser.actionRequestApproved";
2112             } else {
2113                 messageString = "general.routing.superuser.actionRequestApproved";
2114             }
2115             GlobalVariables.getMessageMap().putInfo("document", messageString, documentForm.getDocId(), actionRequestId);
2116         }
2117         documentForm.setSuperUserAnnotation("");
2118         return mapping.findForward(RiceConstants.MAPPING_BASIC);
2119     }
2120 
2121     public ActionForward superUserDisapprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
2122     	KualiDocumentFormBase documentForm = (KualiDocumentFormBase)form;
2123     	if(StringUtils.isBlank(documentForm.getSuperUserAnnotation())) {
2124     		GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.disapprove.annotation.missing", "");
2125     		return mapping.findForward(RiceConstants.MAPPING_BASIC);
2126     	} else if (!documentForm.getSelectedActionRequests().isEmpty()) {
2127             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.disapprove.when.actions.checked", "");
2128             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2129         } else if (!documentForm.isStateAllowsApproveOrDisapprove()) {
2130             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.disapprove.not.allowed", "");
2131             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2132         }
2133 
2134         WorkflowDocumentActionsService documentActions = getWorkflowDocumentActionsService(documentForm.getWorkflowDocument().getDocumentTypeId());
2135         DocumentActionParameters parameters = DocumentActionParameters.create(documentForm.getDocId(), GlobalVariables.getUserSession().getPrincipalId(), documentForm.getSuperUserAnnotation());
2136         documentActions.superUserDisapprove(parameters, true);
2137         GlobalVariables.getMessageMap().putInfo("document", "general.routing.superuser.disapproved", documentForm.getDocId());
2138         documentForm.setSuperUserAnnotation("");
2139         return mapping.findForward(RiceConstants.MAPPING_BASIC);
2140     }
2141 
2142     public ActionForward superUserApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
2143         KualiDocumentFormBase documentForm = (KualiDocumentFormBase)form;
2144         if(StringUtils.isBlank(documentForm.getSuperUserAnnotation())) {
2145             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.approve.annotation.missing", "");
2146             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2147         } else if (!documentForm.getSelectedActionRequests().isEmpty()) {
2148             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.approve.when.actions.checked", "");
2149             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2150         } else if (!documentForm.isStateAllowsApproveOrDisapprove()) {
2151             GlobalVariables.getMessageMap().putErrorForSectionId("superuser.errors", "superuser.approve.not.allowed", "");
2152             return mapping.findForward(RiceConstants.MAPPING_BASIC);
2153         }
2154 
2155         WorkflowDocumentActionsService documentActions = getWorkflowDocumentActionsService(documentForm.getWorkflowDocument().getDocumentTypeId());
2156         DocumentActionParameters parameters = DocumentActionParameters.create(documentForm.getDocId(), GlobalVariables.getUserSession().getPrincipalId(), documentForm.getSuperUserAnnotation());
2157         documentActions.superUserBlanketApprove(parameters, true);
2158         GlobalVariables.getMessageMap().putInfo("document", "general.routing.superuser.approved", documentForm.getDocId());
2159         documentForm.setSuperUserAnnotation("");
2160         return mapping.findForward(RiceConstants.MAPPING_BASIC);
2161     }
2162 
2163     private WorkflowDocumentActionsService getWorkflowDocumentActionsService(String documentTypeId) {
2164         DocumentType documentType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeById(documentTypeId);
2165         String applicationId = documentType.getApplicationId();
2166         QName serviceName = new QName(KewApiConstants.Namespaces.KEW_NAMESPACE_2_0,
2167                 KewApiConstants.ServiceNames.WORKFLOW_DOCUMENT_ACTIONS_SERVICE_SOAP);
2168         WorkflowDocumentActionsService service = (WorkflowDocumentActionsService) KsbApiServiceLocator.getServiceBus()
2169                 .getService(serviceName, applicationId);
2170         if (service == null) {
2171             service = KewApiServiceLocator.getWorkflowDocumentActionsService();
2172         }
2173         return service;
2174     }
2175     
2176     /**
2177      * Complete document action
2178      * 
2179      * @param mapping
2180      * @param form
2181      * @param request
2182      * @param response
2183      * @return
2184      * @throws Exception
2185      */
2186     public ActionForward complete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
2187         KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form;
2188         doProcessingAfterPost(kualiDocumentFormBase, request);
2189 
2190         kualiDocumentFormBase.setDerivedValuesOnForm(request);
2191         ActionForward preRulesForward = promptBeforeValidation(mapping, form, request, response);
2192         if (preRulesForward != null) {
2193             return preRulesForward;
2194         }
2195 
2196         Document document = kualiDocumentFormBase.getDocument();
2197 
2198         getDocumentService().completeDocument(document, kualiDocumentFormBase.getAnnotation(), combineAdHocRecipients(kualiDocumentFormBase));
2199         KNSGlobalVariables.getMessageList().add(RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL);
2200         kualiDocumentFormBase.setAnnotation("");
2201 
2202         return mapping.findForward(RiceConstants.MAPPING_BASIC);
2203     }
2204     
2205 }
2206