View Javadoc

1   /**
2    * Copyright 2005-2013 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.krad.web.controller;
17  
18  import org.apache.commons.lang.ArrayUtils;
19  import org.apache.commons.lang.StringUtils;
20  import org.kuali.rice.core.api.CoreApiServiceLocator;
21  import org.kuali.rice.core.api.config.property.ConfigurationService;
22  import org.kuali.rice.core.api.exception.RiceRuntimeException;
23  import org.kuali.rice.core.api.util.RiceKeyConstants;
24  import org.kuali.rice.kew.api.KewApiConstants;
25  import org.kuali.rice.kew.api.WorkflowDocument;
26  import org.kuali.rice.kew.api.exception.WorkflowException;
27  import org.kuali.rice.kim.api.identity.Person;
28  import org.kuali.rice.krad.UserSessionUtils;
29  import org.kuali.rice.krad.bo.AdHocRouteRecipient;
30  import org.kuali.rice.krad.bo.Attachment;
31  import org.kuali.rice.krad.bo.DocumentHeader;
32  import org.kuali.rice.krad.bo.Note;
33  import org.kuali.rice.krad.document.Document;
34  import org.kuali.rice.krad.document.DocumentAuthorizer;
35  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
36  import org.kuali.rice.krad.exception.DocumentAuthorizationException;
37  import org.kuali.rice.krad.exception.UnknownDocumentIdException;
38  import org.kuali.rice.krad.exception.ValidationException;
39  import org.kuali.rice.krad.rules.rule.event.AddNoteEvent;
40  import org.kuali.rice.krad.service.AttachmentService;
41  import org.kuali.rice.krad.service.BusinessObjectService;
42  import org.kuali.rice.krad.service.DataDictionaryService;
43  import org.kuali.rice.krad.service.DocumentDictionaryService;
44  import org.kuali.rice.krad.service.DocumentService;
45  import org.kuali.rice.krad.service.KRADServiceLocator;
46  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
47  import org.kuali.rice.krad.service.NoteService;
48  import org.kuali.rice.krad.uif.UifConstants.WorkflowAction;
49  import org.kuali.rice.krad.uif.UifParameters;
50  import org.kuali.rice.krad.uif.UifPropertyPaths;
51  import org.kuali.rice.krad.uif.container.CollectionGroup;
52  import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
53  import org.kuali.rice.krad.util.GlobalVariables;
54  import org.kuali.rice.krad.util.KRADConstants;
55  import org.kuali.rice.krad.util.NoteType;
56  import org.kuali.rice.krad.web.form.DocumentFormBase;
57  import org.kuali.rice.krad.web.form.UifFormBase;
58  import org.springframework.util.FileCopyUtils;
59  import org.springframework.validation.BindingResult;
60  import org.springframework.web.bind.ServletRequestBindingException;
61  import org.springframework.web.bind.annotation.ModelAttribute;
62  import org.springframework.web.bind.annotation.RequestMapping;
63  import org.springframework.web.bind.annotation.RequestMethod;
64  import org.springframework.web.multipart.MultipartFile;
65  import org.springframework.web.servlet.ModelAndView;
66  
67  import javax.servlet.http.HttpServletRequest;
68  import javax.servlet.http.HttpServletResponse;
69  import java.io.FileNotFoundException;
70  import java.io.IOException;
71  import java.io.InputStream;
72  import java.util.ArrayList;
73  import java.util.List;
74  import java.util.Properties;
75  
76  /**
77   * Base controller class for all KRAD <code>DocumentView</code> screens working
78   * with <code>Document</code> models
79   *
80   * <p>
81   * Provides default controller implementations for the standard document actions including: doc handler
82   * (retrieve from doc search and action list), save, route (and other KEW actions)
83   * </p>
84   *
85   * @author Kuali Rice Team (rice.collab@kuali.org)
86   */
87  public abstract class DocumentControllerBase extends UifControllerBase {
88      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentControllerBase.class);
89  
90      // COMMAND constants which cause docHandler to load an existing document
91      // instead of creating a new one
92      protected static final String[] DOCUMENT_LOAD_COMMANDS =
93              {KewApiConstants.ACTIONLIST_COMMAND, KewApiConstants.DOCSEARCH_COMMAND, KewApiConstants.SUPERUSER_COMMAND,
94                      KewApiConstants.HELPDESK_ACTIONLIST_COMMAND};
95  
96      private BusinessObjectService businessObjectService;
97      private DataDictionaryService dataDictionaryService;
98      private DocumentService documentService;
99      private DocumentDictionaryService documentDictionaryService;
100     private AttachmentService attachmentService;
101     private NoteService noteService;
102 
103     /**
104      * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
105      */
106     @Override
107     protected abstract DocumentFormBase createInitialForm(HttpServletRequest request);
108 
109     /**
110      * Used to funnel all document handling through, we could do useful things
111      * like log and record various openings and status Additionally it may be
112      * nice to have a single dispatcher that can know how to dispatch to a
113      * redirect url for document specific handling but we may not need that as
114      * all we should need is the document to be able to load itself based on
115      * document id and then which action forward or redirect is pertinent for
116      * the document type.
117      */
118     @RequestMapping(params = "methodToCall=docHandler")
119     public ModelAndView docHandler(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
120             HttpServletRequest request, HttpServletResponse response) throws Exception {
121         String command = form.getCommand();
122 
123         // in all of the following cases we want to load the document
124         if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, command) && form.getDocId() != null) {
125             loadDocument(form);
126         } else if (KewApiConstants.INITIATE_COMMAND.equals(command)) {
127             createDocument(form);
128         } else {
129             LOG.error("docHandler called with invalid parameters");
130             throw new IllegalArgumentException("docHandler called with invalid parameters");
131         }
132 
133         // TODO: authorization on document actions
134         // if (KEWConstants.SUPERUSER_COMMAND.equalsIgnoreCase(command)) {
135         // form.setSuppressAllButtons(true);
136         // }
137 
138         return getUIFModelAndView(form);
139     }
140 
141     /**
142      * Loads the document by its provided document header id. This has been abstracted out so that
143      * it can be overridden in children if the need arises
144      *
145      * @param form - form instance that contains the doc id parameter and where
146      * the retrieved document instance should be set
147      */
148     protected void loadDocument(DocumentFormBase form) throws WorkflowException {
149         String docId = form.getDocId();
150 
151         LOG.debug("Loading document" + docId);
152 
153         Document doc = null;
154         doc = getDocumentService().getByDocumentHeaderId(docId);
155         if (doc == null) {
156             throw new UnknownDocumentIdException(
157                     "Document no longer exists.  It may have been cancelled before being saved.");
158         }
159 
160         WorkflowDocument workflowDocument = doc.getDocumentHeader().getWorkflowDocument();
161         if (!getDocumentDictionaryService().getDocumentAuthorizer(doc).canOpen(doc,
162                 GlobalVariables.getUserSession().getPerson())) {
163             throw buildAuthorizationException("open", doc);
164         }
165 
166         // re-retrieve the document using the current user's session - remove
167         // the system user from the WorkflowDcument object
168         if (workflowDocument != doc.getDocumentHeader().getWorkflowDocument()) {
169             LOG.warn("Workflow document changed via canOpen check");
170             doc.getDocumentHeader().setWorkflowDocument(workflowDocument);
171         }
172 
173         form.setDocument(doc);
174         WorkflowDocument workflowDoc = doc.getDocumentHeader().getWorkflowDocument();
175         form.setDocTypeName(workflowDoc.getDocumentTypeName());
176 
177         UserSessionUtils.addWorkflowDocument(GlobalVariables.getUserSession(), workflowDoc);
178     }
179 
180     /**
181      * Creates a new document of the type specified by the docTypeName property of the given form.
182      * This has been abstracted out so that it can be overridden in children if the need arises.
183      *
184      * @param form - form instance that contains the doc type parameter and where
185      * the new document instance should be set
186      */
187     protected void createDocument(DocumentFormBase form) throws WorkflowException {
188         LOG.debug("Creating new document instance for doc type: " + form.getDocTypeName());
189         Document doc = getDocumentService().getNewDocument(form.getDocTypeName());
190 
191         form.setDocument(doc);
192         form.setDocTypeName(doc.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
193     }
194 
195     /**
196      * Reloads the document contained on the form from the database
197      *
198      * @param form - document form base containing the document instance from which the document number will
199      * be retrieved and used to fetch the document from the database
200      * @return ModelAndView
201      */
202     @RequestMapping(params = "methodToCall=reload")
203     public ModelAndView reload(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
204             HttpServletRequest request, HttpServletResponse response) throws Exception {
205         Document document = form.getDocument();
206 
207         // prepare for the reload action - set doc id and command
208         form.setDocId(document.getDocumentNumber());
209         form.setCommand(DOCUMENT_LOAD_COMMANDS[1]);
210 
211         GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_MESSAGES, RiceKeyConstants.MESSAGE_RELOADED);
212 
213         // forward off to the doc handler
214         return docHandler(form, result, request, response);
215     }
216 
217     /**
218      * Prompts user to confirm the cancel action then if confirmed cancels the document instance
219      * contained on the form
220      *
221      * @param form - document form base containing the document instance that will be cancelled
222      * @return ModelAndView
223      */
224     @RequestMapping(params = "methodToCall=cancel")
225     @Override
226     public ModelAndView cancel(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
227             HttpServletRequest request, HttpServletResponse response) {
228         DocumentFormBase documentForm = (DocumentFormBase) form;
229 
230         // TODO: prompt user to confirm the cancel, need question framework
231 
232         performWorkflowAction(documentForm, WorkflowAction.CANCEL, false);
233 
234         return returnToPrevious(form);
235     }
236 
237     /**
238      * Saves the document instance contained on the form
239      *
240      * @param form - document form base containing the document instance that will be saved
241      * @return ModelAndView
242      */
243     @RequestMapping(params = "methodToCall=save")
244     public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
245             HttpServletRequest request, HttpServletResponse response) throws Exception {
246         performWorkflowAction(form, WorkflowAction.SAVE, true);
247 
248         return getUIFModelAndView(form);
249     }
250 
251     /**
252      * Completes the document instance contained on the form
253      *
254      * @param form - document form base containing the document instance that will be completed
255      * @return ModelAndView
256      */
257     @RequestMapping(params = "methodToCall=complete")
258     public ModelAndView complete(@ModelAttribute("KualiForm")
259     DocumentFormBase form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
260         performWorkflowAction(form, WorkflowAction.COMPLETE, true);
261 
262         return getUIFModelAndView(form);
263     }
264 
265     /**
266      * Routes the document instance contained on the form
267      *
268      * @param form - document form base containing the document instance that will be routed
269      * @return ModelAndView
270      */
271     @RequestMapping(params = "methodToCall=route")
272     public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
273             HttpServletRequest request, HttpServletResponse response) {
274         performWorkflowAction(form, WorkflowAction.ROUTE, true);
275 
276         return getUIFModelAndView(form);
277     }
278 
279     /**
280      * Performs the blanket approve workflow action on the form document instance
281      *
282      * @param form - document form base containing the document instance that will be blanket approved
283      * @return ModelAndView
284      */
285     @RequestMapping(params = "methodToCall=blanketApprove")
286     public ModelAndView blanketApprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
287             HttpServletRequest request, HttpServletResponse response) throws Exception {
288         performWorkflowAction(form, WorkflowAction.BLANKETAPPROVE, true);
289 
290         return getUIFModelAndView(form);
291     }
292 
293     /**
294      * Performs the approve workflow action on the form document instance
295      *
296      * @param form - document form base containing the document instance that will be approved
297      * @return ModelAndView
298      */
299     @RequestMapping(params = "methodToCall=approve")
300     public ModelAndView approve(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
301             HttpServletRequest request, HttpServletResponse response) throws Exception {
302         performWorkflowAction(form, WorkflowAction.APPROVE, true);
303 
304         return returnToPrevious(form);
305     }
306 
307     /**
308      * Performs the disapprove workflow action on the form document instance
309      *
310      * @param form - document form base containing the document instance that will be disapproved
311      * @return ModelAndView
312      */
313     @RequestMapping(params = "methodToCall=disapprove")
314     public ModelAndView disapprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
315             HttpServletRequest request, HttpServletResponse response) throws Exception {
316         // TODO: need to prompt for disapproval note text
317         performWorkflowAction(form, WorkflowAction.DISAPPROVE, true);
318 
319         return returnToPrevious(form);
320     }
321 
322     /**
323      * Performs the fyi workflow action on the form document instance
324      *
325      * @param form - document form base containing the document instance the fyi will be taken on
326      * @return ModelAndView
327      */
328     @RequestMapping(params = "methodToCall=fyi")
329     public ModelAndView fyi(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
330             HttpServletRequest request, HttpServletResponse response) throws Exception {
331         performWorkflowAction(form, WorkflowAction.FYI, false);
332 
333         return returnToPrevious(form);
334     }
335 
336     /**
337      * Performs the acknowledge workflow action on the form document instance
338      *
339      * @param form - document form base containing the document instance the acknowledge will be taken on
340      * @return ModelAndView
341      */
342     @RequestMapping(params = "methodToCall=acknowledge")
343     public ModelAndView acknowledge(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
344             HttpServletRequest request, HttpServletResponse response) throws Exception {
345         performWorkflowAction(form, WorkflowAction.ACKNOWLEDGE, false);
346 
347         return returnToPrevious(form);
348     }
349 
350     /**
351      * Invokes the {@link DocumentService} to carry out a request workflow action and adds a success message, if
352      * requested a check for sensitive data is also performed
353      *
354      * @param form - document form instance containing the document for which the action will be taken on
355      * @param action - {@link WorkflowAction} enum indicating what workflow action to take
356      * @param checkSensitiveData - boolean indicating whether a check for sensitive data should occur
357      */
358     protected void performWorkflowAction(DocumentFormBase form, WorkflowAction action, boolean checkSensitiveData) {
359         Document document = form.getDocument();
360 
361         LOG.debug("Performing workflow action " + action.name() + "for document: " + document.getDocumentNumber());
362 
363         // TODO: need question and prompt framework
364         if (checkSensitiveData) {
365             //        String viewName = checkAndWarnAboutSensitiveData(form, request, response,
366             //                KRADPropertyConstants.DOCUMENT_EXPLANATION, document.getDocumentHeader().getExplanation(), "route", "");
367             //        if (viewName != null) {
368             //            return new ModelAndView(viewName);
369             //        }
370         }
371 
372         try {
373             String successMessageKey = null;
374             switch (action) {
375                 case SAVE:
376                     getDocumentService().saveDocument(document);
377                     successMessageKey = RiceKeyConstants.MESSAGE_SAVED;
378                     break;
379                 case ROUTE:
380                     getDocumentService().routeDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
381                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
382                     break;
383                 case BLANKETAPPROVE:
384                     getDocumentService().blanketApproveDocument(document, form.getAnnotation(), combineAdHocRecipients(
385                             form));
386                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_APPROVED;
387                     break;
388                 case APPROVE:
389                     getDocumentService().approveDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
390                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_APPROVED;
391                     break;
392                 case DISAPPROVE:
393                     // TODO: need to get disapprove note from user
394                     String disapprovalNoteText = "";
395                     getDocumentService().disapproveDocument(document, disapprovalNoteText);
396                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_DISAPPROVED;
397                     break;
398                 case FYI:
399                     getDocumentService().clearDocumentFyi(document, combineAdHocRecipients(form));
400                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_FYIED;
401                     break;
402                 case ACKNOWLEDGE:
403                     getDocumentService().acknowledgeDocument(document, form.getAnnotation(), combineAdHocRecipients(
404                             form));
405                     successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_ACKNOWLEDGED;
406                     break;
407                 case CANCEL:
408                     if (getDocumentService().documentExists(document.getDocumentNumber())) {
409                         getDocumentService().cancelDocument(document, form.getAnnotation());
410                         successMessageKey = RiceKeyConstants.MESSAGE_CANCELLED;
411                     }
412                     break;
413                 case COMPLETE:
414                     if (getDocumentService().documentExists(document.getDocumentNumber())) {
415                         getDocumentService().completeDocument(document, form.getAnnotation(), combineAdHocRecipients(form));
416                         successMessageKey = RiceKeyConstants.MESSAGE_ROUTE_SUCCESSFUL;
417                     }
418                     break;
419             }
420 
421             if (successMessageKey != null) {
422                 GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_MESSAGES, successMessageKey);
423             }
424         } catch (ValidationException e) {
425             // if errors in map, swallow exception so screen will draw with errors
426             // if not then throw runtime because something bad happened
427             if (GlobalVariables.getMessageMap().hasNoErrors()) {
428                 throw new RiceRuntimeException("Validation Exception with no error message.", e);
429             }
430         } catch (Exception e) {
431             throw new RiceRuntimeException(
432                     "Exception trying to invoke action " + action.name() + "for document: " + document
433                             .getDocumentNumber(), e);
434         }
435 
436         form.setAnnotation("");
437     }
438 
439     /**
440      * Redirects to the supervisor functions page
441      *
442      * @return ModelAndView - model and view configured for the redirect URL
443      */
444     @RequestMapping(params = "methodToCall=supervisorFunctions")
445     public ModelAndView supervisorFunctions(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
446             HttpServletRequest request, HttpServletResponse response) throws Exception {
447 
448         String workflowSuperUserUrl = getConfigurationService().getPropertyValueAsString(KRADConstants.WORKFLOW_URL_KEY)
449                 + "/" + KRADConstants.SUPERUSER_ACTION;
450 
451         Properties props = new Properties();
452         props.put(UifParameters.METHOD_TO_CALL, "displaySuperUserDocument");
453         props.put(UifPropertyPaths.DOCUMENT_ID, form.getDocument().getDocumentNumber());
454 
455         return performRedirect(form, workflowSuperUserUrl, props);
456     }
457 
458     /**
459      * Called by the add note action for adding a note. Method validates, saves attachment and adds the
460      * time stamp and author. Calls the UifControllerBase.addLine method to handle generic actions.
461      *
462      * @param uifForm - document form base containing the note instance that will be inserted into the document
463      * @return ModelAndView
464      */
465     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=insertNote")
466     public ModelAndView insertNote(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
467             HttpServletRequest request, HttpServletResponse response) {
468 
469         // Get the note add line
470         String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
471         CollectionGroup collectionGroup = uifForm.getPostedView().getViewIndex().getCollectionGroupByPath(
472                 selectedCollectionPath);
473         String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
474         Object addLine = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath);
475         Note newNote = (Note) addLine;
476         newNote.setNotePostedTimestampToCurrent();
477 
478         Document document = ((DocumentFormBase) uifForm).getDocument();
479 
480         newNote.setRemoteObjectIdentifier(document.getNoteTarget().getObjectId());
481 
482         // Get the attachment file
483         String attachmentTypeCode = null;
484         MultipartFile attachmentFile = uifForm.getAttachmentFile();
485         Attachment attachment = null;
486         if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getOriginalFilename())) {
487             if (attachmentFile.getSize() == 0) {
488                 GlobalVariables.getMessageMap().putError(String.format("%s.%s",
489                         KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME,
490                         KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME), RiceKeyConstants.ERROR_UPLOADFILE_EMPTY,
491                         attachmentFile.getOriginalFilename());
492             } else {
493                 if (newNote.getAttachment() != null) {
494                     attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode();
495                 }
496 
497                 DocumentAuthorizer documentAuthorizer = getDocumentDictionaryService().getDocumentAuthorizer(document);
498                 if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode,
499                         GlobalVariables.getUserSession().getPerson())) {
500                     throw buildAuthorizationException("annotate", document);
501                 }
502 
503                 try {
504                     String attachmentType = null;
505                     Attachment newAttachment = newNote.getAttachment();
506                     if (newAttachment != null) {
507                         attachmentType = newAttachment.getAttachmentTypeCode();
508                     }
509 
510                     attachment = getAttachmentService().createAttachment(document.getNoteTarget(),
511                             attachmentFile.getOriginalFilename(), attachmentFile.getContentType(),
512                             (int) attachmentFile.getSize(), attachmentFile.getInputStream(), attachmentType);
513                 } catch (IOException e) {
514                     throw new RiceRuntimeException("Unable to store attachment", e);
515                 }
516             }
517         }
518 
519         Person kualiUser = GlobalVariables.getUserSession().getPerson();
520         if (kualiUser == null) {
521             throw new IllegalStateException("Current UserSession has a null Person.");
522         }
523 
524         newNote.setAuthorUniversalIdentifier(kualiUser.getPrincipalId());
525 
526         // validate the note
527         boolean rulePassed = KRADServiceLocatorWeb.getKualiRuleService().applyRules(new AddNoteEvent(document,
528                 newNote));
529 
530         // if the rule evaluation passed, let's add the note
531         if (rulePassed) {
532             newNote.refresh();
533 
534             DocumentHeader documentHeader = document.getDocumentHeader();
535 
536             // adding the attachment after refresh gets called, since the attachment record doesn't get persisted
537             // until the note does (and therefore refresh doesn't have any attachment to autoload based on the id, nor does it
538             // autopopulate the id since the note hasn't been persisted yet)
539             if (attachment != null) {
540                 newNote.addAttachment(attachment);
541             }
542             // Save the note if the document is already saved
543             if (!documentHeader.getWorkflowDocument().isInitiated() && StringUtils.isNotEmpty(
544                     document.getNoteTarget().getObjectId()) && !(document instanceof MaintenanceDocument && NoteType
545                     .BUSINESS_OBJECT.getCode().equals(newNote.getNoteTypeCode()))) {
546 
547                 getNoteService().save(newNote);
548             }
549 
550         }
551 
552         return addLine(uifForm, result, request, response);
553     }
554 
555     /**
556      * Called by the delete note action for deleting a note.
557      * Calls the UifControllerBase.deleteLine method to handle
558      * generic actions.
559      */
560     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=deleteNote")
561     public ModelAndView deleteNote(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
562             HttpServletRequest request, HttpServletResponse response) {
563 
564         String selectedLineIndex = uifForm.getActionParamaterValue("selectedLineIndex");
565         Document document = ((DocumentFormBase) uifForm).getDocument();
566         Note note = document.getNote(Integer.parseInt(selectedLineIndex));
567 
568         Attachment attachment = note.getAttachment();
569         String attachmentTypeCode = null;
570         if (attachment != null) {
571             attachmentTypeCode = attachment.getAttachmentTypeCode();
572         }
573 
574         // check delete note authorization
575         Person user = GlobalVariables.getUserSession().getPerson();
576         String authorUniversalIdentifier = note.getAuthorUniversalIdentifier();
577         if (!getDocumentDictionaryService().getDocumentAuthorizer(document).canDeleteNoteAttachment(document,
578                 attachmentTypeCode, authorUniversalIdentifier, user)) {
579             throw buildAuthorizationException("annotate", document);
580         }
581 
582         if (attachment != null && attachment.isComplete()) { // only do this if the note has been persisted
583             //KFSMI-798 - refresh() changed to refreshNonUpdateableReferences()
584             //All references for the business object Attachment are auto-update="none",
585             //so refreshNonUpdateableReferences() should work the same as refresh()
586             if (note.getNoteIdentifier()
587                     != null) { // KULRICE-2343 don't blow away note reference if the note wasn't persisted
588                 attachment.refreshNonUpdateableReferences();
589             }
590             getAttachmentService().deleteAttachmentContents(attachment);
591         }
592         // delete the note if the document is already saved
593         if (!document.getDocumentHeader().getWorkflowDocument().isInitiated()) {
594             getNoteService().deleteNote(note);
595         }
596 
597         return deleteLine(uifForm, result, request, response);
598     }
599 
600     /**
601      * Called by the download attachment action on a note. Method
602      * gets the attachment input stream from the AttachmentService
603      * and writes it to the request output stream.
604      */
605     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=downloadAttachment")
606     public ModelAndView downloadAttachment(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
607             HttpServletRequest request,
608             HttpServletResponse response) throws ServletRequestBindingException, FileNotFoundException, IOException {
609         // Get the attachment input stream
610         String selectedLineIndex = uifForm.getActionParamaterValue("selectedLineIndex");
611         Note note = ((DocumentFormBase) uifForm).getDocument().getNote(Integer.parseInt(selectedLineIndex));
612         Attachment attachment = note.getAttachment();
613         InputStream is = getAttachmentService().retrieveAttachmentContents(attachment);
614 
615         // Set the response headers
616         response.setContentType(attachment.getAttachmentMimeTypeCode());
617         response.setContentLength(attachment.getAttachmentFileSize().intValue());
618         response.setHeader("Expires", "0");
619         response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
620         response.setHeader("Pragma", "public");
621         response.setHeader("Content-Disposition",
622                 "attachment; filename=\"" + attachment.getAttachmentFileName() + "\"");
623 
624         // Copy the input stream to the response
625         FileCopyUtils.copy(is, response.getOutputStream());
626         return null;
627     }
628 
629     /**
630      * Called by the cancel attachment action on a note. Method
631      * removes the attachment file from the form.
632      */
633     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=cancelAttachment")
634     public ModelAndView cancelAttachment(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
635             HttpServletRequest request, HttpServletResponse response) {
636         // Remove the attached file
637         uifForm.setAttachmentFile(null);
638         return getUIFModelAndView(uifForm);
639     }
640 
641     /**
642      * Checks if the given value matches patterns that indicate sensitive data
643      * and if configured to give a warning for sensitive data will prompt the
644      * user to continue.
645      *
646      * @param form
647      * @param request
648      * @param response
649      * @param fieldName - name of field with value being checked
650      * @param fieldValue - value to check for sensitive data
651      * @param caller - method that should be called back from question
652      * @param context - additional context that needs to be passed back with the
653      * question response
654      * @return - view for spring to forward to, or null if processing should
655      *         continue
656      * @throws Exception
657      */
658     protected String checkAndWarnAboutSensitiveData(DocumentFormBase form, HttpServletRequest request,
659             HttpServletResponse response, String fieldName, String fieldValue, String caller,
660             String context) throws Exception {
661 
662         String viewName = null;
663         Document document = form.getDocument();
664 
665         // TODO: need to move containsSensitiveDataPatternMatch to util class in krad
666 //        boolean containsSensitiveData = false;
667 //        //boolean containsSensitiveData = WebUtils.containsSensitiveDataPatternMatch(fieldValue);
668 //
669 //        // check if warning is configured in which case we will prompt, or if
670 //        // not business rules will thrown an error
671 //        boolean warnForSensitiveData = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(
672 //                KRADConstants.KRAD_NAMESPACE, ParameterConstants.ALL_COMPONENT,
673 //                KRADConstants.SystemGroupParameterNames.SENSITIVE_DATA_PATTERNS_WARNING_IND);
674 //
675 //        // determine if the question has been asked yet
676 //        Map<String, String> ticketContext = new HashMap<String, String>();
677 //        ticketContext.put(KRADPropertyConstants.DOCUMENT_NUMBER, document.getDocumentNumber());
678 //        ticketContext.put(KRADConstants.CALLING_METHOD, caller);
679 //        ticketContext.put(KRADPropertyConstants.NAME, fieldName);
680 //
681 //        boolean questionAsked = GlobalVariables.getUserSession().hasMatchingSessionTicket(
682 //                KRADConstants.SENSITIVE_DATA_QUESTION_SESSION_TICKET, ticketContext);
683 //
684 //        // start in logic for confirming the sensitive data
685 //        if (containsSensitiveData && warnForSensitiveData && !questionAsked) {
686 //            Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
687 //            if (question == null || !KRADConstants.DOCUMENT_SENSITIVE_DATA_QUESTION.equals(question)) {
688 //
689 //                // TODO not ready for question framework yet
690 //                /*
691 //                     * // question hasn't been asked, prompt to continue return
692 //                     * this.performQuestionWithoutInput(mapping, form, request,
693 //                     * response, KRADConstants.DOCUMENT_SENSITIVE_DATA_QUESTION,
694 //                     * getKualiConfigurationService()
695 //                     * .getPropertyValueAsString(RiceKeyConstants
696 //                     * .QUESTION_SENSITIVE_DATA_DOCUMENT),
697 //                     * KRADConstants.CONFIRMATION_QUESTION, caller, context);
698 //                     */
699 //                viewName = "ask_user_questions";
700 //            } else {
701 //                Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
702 //
703 //                // if no button clicked just reload the doc
704 //                if (ConfirmationQuestion.NO.equals(buttonClicked)) {
705 //                    // TODO figure out what to return
706 //                    viewName = "user_says_no";
707 //                }
708 //
709 //                // answered yes, create session ticket so we not to ask question
710 //                // again if there are further question requests
711 //                SessionTicket ticket = new SessionTicket(KRADConstants.SENSITIVE_DATA_QUESTION_SESSION_TICKET);
712 //                ticket.setTicketContext(ticketContext);
713 //                GlobalVariables.getUserSession().putSessionTicket(ticket);
714 //            }
715 //        }
716 
717         // returning null will indicate processing should continue (no redirect)
718         return viewName;
719     }
720 
721     /**
722      * Convenience method to combine the two lists of ad hoc recipients into one which should be done before
723      * calling any of the document service methods that expect a list of ad hoc recipients
724      *
725      * @param form - document form instance containing the ad hod lists
726      * @return List<AdHocRouteRecipient> combined ad hoc recipients
727      */
728     protected List<AdHocRouteRecipient> combineAdHocRecipients(DocumentFormBase form) {
729         Document document = form.getDocument();
730 
731         List<AdHocRouteRecipient> adHocRecipients = new ArrayList<AdHocRouteRecipient>();
732         adHocRecipients.addAll(document.getAdHocRoutePersons());
733         adHocRecipients.addAll(document.getAdHocRouteWorkgroups());
734 
735         return adHocRecipients;
736     }
737 
738     /**
739      * Convenience method for building authorization exceptions
740      *
741      * @param action - the action that was requested
742      * @param document - document instance the action was requested for
743      */
744     protected DocumentAuthorizationException buildAuthorizationException(String action, Document document) {
745         return new DocumentAuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(),
746                 action, document.getDocumentNumber());
747     }
748 
749     public BusinessObjectService getBusinessObjectService() {
750         if (this.businessObjectService == null) {
751             this.businessObjectService = KRADServiceLocator.getBusinessObjectService();
752         }
753         return this.businessObjectService;
754     }
755 
756     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
757         this.businessObjectService = businessObjectService;
758     }
759 
760     public DataDictionaryService getDataDictionaryService() {
761         if (this.dataDictionaryService == null) {
762             this.dataDictionaryService = KRADServiceLocatorWeb.getDataDictionaryService();
763         }
764         return this.dataDictionaryService;
765     }
766 
767     public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
768         this.dataDictionaryService = dataDictionaryService;
769     }
770 
771     public DocumentService getDocumentService() {
772         if (this.documentService == null) {
773             this.documentService = KRADServiceLocatorWeb.getDocumentService();
774         }
775         return this.documentService;
776     }
777 
778     public void setDocumentService(DocumentService documentService) {
779         this.documentService = documentService;
780     }
781 
782     public DocumentDictionaryService getDocumentDictionaryService() {
783         if (this.documentDictionaryService == null) {
784             this.documentDictionaryService = KRADServiceLocatorWeb.getDocumentDictionaryService();
785         }
786         return this.documentDictionaryService;
787     }
788 
789     public void setDocumentDictionaryService(DocumentDictionaryService documentDictionaryService) {
790         this.documentDictionaryService = documentDictionaryService;
791     }
792 
793     public AttachmentService getAttachmentService() {
794         if (attachmentService == null) {
795             attachmentService = KRADServiceLocator.getAttachmentService();
796         }
797         return this.attachmentService;
798     }
799 
800     public NoteService getNoteService() {
801         if (noteService == null) {
802             noteService = KRADServiceLocator.getNoteService();
803         }
804 
805         return this.noteService;
806     }
807 
808     public ConfigurationService getConfigurationService() {
809         return CoreApiServiceLocator.getKualiConfigurationService();
810     }
811 
812 }