View Javadoc

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