View Javadoc
1   /**
2    * Copyright 2005-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.krad.web.controller;
17  
18  import javax.servlet.http.HttpServletRequest;
19  import javax.servlet.http.HttpServletResponse;
20  
21  import org.apache.commons.lang.ArrayUtils;
22  import org.apache.log4j.Logger;
23  import org.kuali.rice.core.api.CoreApiServiceLocator;
24  import org.kuali.rice.core.api.config.property.ConfigurationService;
25  import org.kuali.rice.core.api.util.RiceKeyConstants;
26  import org.kuali.rice.kew.api.KewApiConstants;
27  import org.kuali.rice.krad.bo.Attachment;
28  import org.kuali.rice.krad.bo.Note;
29  import org.kuali.rice.krad.bo.PersistableAttachment;
30  import org.kuali.rice.krad.bo.PersistableAttachmentList;
31  import org.kuali.rice.krad.bo.PersistableBusinessObject;
32  import org.kuali.rice.krad.datadictionary.DocumentEntry;
33  import org.kuali.rice.krad.exception.UnknownDocumentIdException;
34  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
35  import org.kuali.rice.krad.maintenance.Maintainable;
36  import org.kuali.rice.krad.maintenance.MaintenanceUtils;
37  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
38  import org.kuali.rice.krad.service.MaintenanceDocumentService;
39  import org.kuali.rice.krad.uif.UifConstants;
40  import org.kuali.rice.krad.uif.UifParameters;
41  import org.kuali.rice.krad.util.GlobalVariables;
42  import org.kuali.rice.krad.util.KRADConstants;
43  import org.kuali.rice.krad.util.KRADUtils;
44  import org.kuali.rice.krad.web.form.DocumentFormBase;
45  import org.kuali.rice.krad.web.form.InitiatedDocumentInfoForm;
46  import org.kuali.rice.krad.web.form.MaintenanceDocumentForm;
47  import org.kuali.rice.krad.web.form.UifFormBase;
48  import org.springframework.stereotype.Controller;
49  import org.springframework.validation.BindingResult;
50  import org.springframework.web.bind.ServletRequestBindingException;
51  import org.springframework.web.bind.annotation.ModelAttribute;
52  import org.springframework.web.bind.annotation.RequestMapping;
53  import org.springframework.web.bind.annotation.RequestMethod;
54  import org.springframework.web.servlet.ModelAndView;
55  
56  import java.io.ByteArrayInputStream;
57  import java.io.FileNotFoundException;
58  import java.io.IOException;
59  import java.util.Properties;
60  
61  /**
62   * Controller for <code>MaintenanceDocumentView</code> screens which operate on
63   * <code>MaintenanceDocument</code> instances
64   *
65   * @author Kuali Rice Team (rice.collab@kuali.org)
66   */
67  @Controller
68  @RequestMapping(value = "/maintenance")
69  public class MaintenanceDocumentController extends DocumentControllerBase {
70      protected static final Logger LOG = Logger.getLogger(MaintenanceDocumentController.class);
71  
72      /**
73       * @see org.kuali.rice.krad.web.controller.UifControllerBase#createInitialForm(javax.servlet.http.HttpServletRequest)
74       */
75      @Override
76      protected MaintenanceDocumentForm createInitialForm(HttpServletRequest request) {
77          return new MaintenanceDocumentForm();
78      }
79  
80      /**
81       * After the document is loaded calls method to setup the maintenance object
82       */
83      @Override
84      @MethodAccessible
85      @RequestMapping(params = "methodToCall=docHandler")
86      public ModelAndView docHandler(@ModelAttribute("KualiForm") DocumentFormBase formBase, BindingResult result,
87              HttpServletRequest request, HttpServletResponse response) throws Exception {
88  
89          // TODO getting double view if we call base, not sure how to handle
90          // so pasting in superclass code
91          // super.docHandler(formBase, request, response);
92          // * begin copy/paste from the base
93          MaintenanceDocumentForm form = (MaintenanceDocumentForm) formBase;
94  
95          // in all of the following cases we want to load the document
96          if (ArrayUtils.contains(DOCUMENT_LOAD_COMMANDS, form.getCommand()) && form.getDocId() != null) {
97              try {
98                  loadDocument(form);
99              } catch (UnknownDocumentIdException udie) {
100                 ConfigurationService kualiConfigurationService = CoreApiServiceLocator.getKualiConfigurationService();
101                 StringBuffer sb = new StringBuffer();
102                 sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_URL_KEY));
103                 sb.append(kualiConfigurationService.getPropertyValueAsString(KRADConstants.KRAD_INITIATED_DOCUMENT_URL_KEY));
104                 Properties props = new Properties();
105                 props.put(UifParameters.METHOD_TO_CALL, UifConstants.MethodToCallNames.START);
106                 GlobalVariables.getUifFormManager().removeSessionForm(form); // removeForm(form);
107                 return performRedirect(new InitiatedDocumentInfoForm(), sb.toString(), props);
108             }
109         } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
110             createDocument(form);
111         } else {
112             LOG.error("docHandler called with invalid parameters");
113             throw new IllegalArgumentException("docHandler called with invalid parameters");
114         }
115         // * end copy/paste from the base
116 
117         if (KewApiConstants.ACTIONLIST_COMMAND.equals(form.getCommand()) ||
118                 KewApiConstants.DOCSEARCH_COMMAND.equals(form.getCommand()) ||
119                 KewApiConstants.SUPERUSER_COMMAND.equals(form.getCommand()) ||
120                 KewApiConstants.HELPDESK_ACTIONLIST_COMMAND.equals(form.getCommand()) && form.getDocId() != null) {
121             // TODO: set state in view
122             // form.setReadOnly(true);
123             form.setMaintenanceAction((form.getDocument()).getNewMaintainableObject().getMaintenanceAction());
124 
125             // Retrieving the FileName from BO table
126             Maintainable tmpMaintainable = form.getDocument().getNewMaintainableObject();
127             if (tmpMaintainable.getDataObject() instanceof PersistableAttachment) {
128                 PersistableAttachment bo = (PersistableAttachment) getLegacyDataAdapter()
129                         .retrieve((PersistableBusinessObject) tmpMaintainable.getDataObject());
130                 if (bo != null) {
131                     request.setAttribute("fileName", bo.getFileName());
132                 }
133             }
134         } else if (KewApiConstants.INITIATE_COMMAND.equals(form.getCommand())) {
135             // form.setReadOnly(false);
136             setupMaintenance(form, request, KRADConstants.MAINTENANCE_NEW_ACTION);
137         } else {
138             LOG.error("We should never have gotten to here");
139             throw new IllegalArgumentException("docHandler called with invalid parameters");
140         }
141 
142         return getUIFModelAndView(form);
143     }
144 
145     /**
146      * Default method for controller that setups a new
147      * <code>MaintenanceDocumentView</code> with the default new action
148      */
149     @Override
150     @MethodAccessible
151     @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_NEW)
152     public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, HttpServletRequest request,
153             HttpServletResponse response) {
154         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
155 
156         //populate the field default values
157         form.setApplyDefaultValues(true);
158 
159         setupMaintenance(maintenanceForm, request, KRADConstants.MAINTENANCE_NEW_ACTION);
160 
161         return getUIFModelAndView(maintenanceForm);
162     }
163 
164     /**
165      * Setups a new <code>MaintenanceDocumentView</code> with the edit maintenance
166      * action
167      */
168     @MethodAccessible
169     @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_EDIT)
170     public ModelAndView maintenanceEdit(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
171             HttpServletRequest request, HttpServletResponse response) throws Exception {
172 
173         // when editing we do not want to apply default values and use the old dataObject values  instead
174         form.setApplyDefaultValues(false);
175         setupMaintenance(form, request, KRADConstants.MAINTENANCE_EDIT_ACTION);
176 
177         return getUIFModelAndView(form);
178     }
179 
180     /**
181      * Setups a new <code>MaintenanceDocumentView</code> with the copy maintenance
182      * action
183      */
184     @MethodAccessible
185     @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_COPY)
186     public ModelAndView maintenanceCopy(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
187             HttpServletRequest request, HttpServletResponse response) throws Exception {
188 
189         setupMaintenance(form, request, KRADConstants.MAINTENANCE_COPY_ACTION);
190 
191         return getUIFModelAndView(form);
192     }
193 
194     /**
195      * Setups a new <code>MaintenanceDocumentView</code> with the new with existing
196      * maintenance action
197      */
198     @MethodAccessible
199     @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_NEW_WITH_EXISTING)
200     public ModelAndView maintenanceNewWithExisting(@ModelAttribute("KualiForm") MaintenanceDocumentForm form,
201             BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
202 
203         setupMaintenance(form, request, KRADConstants.MAINTENANCE_NEWWITHEXISTING_ACTION);
204 
205         return getUIFModelAndView(form);
206     }
207 
208     /**
209      * Setups a new <code>MaintenanceDocumentView</code> with the delete maintenance
210      * action
211      */
212     @MethodAccessible
213     @RequestMapping(params = "methodToCall=" + KRADConstants.Maintenance.METHOD_TO_CALL_DELETE)
214     public ModelAndView maintenanceDelete(@ModelAttribute("KualiForm") MaintenanceDocumentForm form,
215             BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
216 
217         GlobalVariables.getMessageMap().putWarning(KRADConstants.GLOBAL_MESSAGES, RiceKeyConstants.MESSAGE_DELETE);
218 
219         setupMaintenance(form, request, KRADConstants.MAINTENANCE_DELETE_ACTION);
220 
221         return getUIFModelAndView(form);
222     }
223 
224     /**
225      * Sets up the <code>MaintenanceDocument</code> on initial get request
226      *
227      * <p>
228      * First step is to create a new document instance based on the query
229      * parameters (document type name or object class name). Then call the
230      * <code>Maintainable</code> to do setup on the object being maintained.
231      * </p>
232      *
233      * @param form - <code>MaintenanceDocumentForm</code> instance
234      * @param request - HTTP request object
235      * @param maintenanceAction - the maintenance action (new, new from existing, edit, copy)
236      * being request
237      * @throws Exception
238      */
239     protected void setupMaintenance(MaintenanceDocumentForm form, HttpServletRequest request, String maintenanceAction) {
240         MaintenanceDocument document = form.getDocument();
241 
242         // create a new document object, if required
243         if (document == null) {
244             document = getMaintenanceDocumentService()
245                     .setupNewMaintenanceDocument(form.getDataObjectClassName(), form.getDocTypeName(),
246                             maintenanceAction);
247 
248             form.setDocument(document);
249             form.setDocTypeName(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
250         }
251 
252         // set action on form
253         form.setMaintenanceAction(maintenanceAction);
254 
255         // invoke maintenance document service to setup the object for maintenance
256         getMaintenanceDocumentService().setupMaintenanceObject(document, maintenanceAction, request.getParameterMap());
257 
258         // for new maintainable check if a maintenance lock exists and if so
259         // warn the user
260         if (KRADConstants.MAINTENANCE_NEW_ACTION.equals(maintenanceAction)) {
261             MaintenanceUtils.checkForLockingDocument(document, false);
262         }
263 
264         // Retrieve notes topic display flag from data dictionary and add to
265         // document
266         // TODO: should be in the view as permission
267         DocumentEntry entry = KRADServiceLocatorWeb.getDocumentDictionaryService()
268                 .getMaintenanceDocumentEntry(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
269         document.setDisplayTopicFieldInNotes(entry.getDisplayTopicFieldInNotes());
270     }
271 
272     /**
273      * Override route to retrieve the maintenance object if it is an attachment
274      *
275      * {@inheritDoc}
276      */
277     @Override
278     @RequestMapping(params = "methodToCall=route")
279     public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
280             HttpServletRequest request, HttpServletResponse response) {
281 
282         ModelAndView modelAndView;
283 
284         modelAndView = super.route(form, result, request, response);
285 
286         MaintenanceDocument document = (MaintenanceDocument) form.getDocument();
287         if (document.getNewMaintainableObject().getDataObject() instanceof PersistableAttachment) {
288             PersistableAttachment bo = (PersistableAttachment) getLegacyDataAdapter()
289                     .retrieve((PersistableBusinessObject) document.getNewMaintainableObject().getDataObject());
290             request.setAttribute("fileName", bo.getFileName());
291         }
292 
293         modelAndView = getUIFModelAndView(form);
294 
295         return modelAndView;
296     }
297 
298     /**
299      * Downloads the attachment to the user's browser
300      *
301      * @param uifForm
302      * @param result
303      * @param request
304      * @param response
305      * @return ModelView
306      * @throws Exception
307      */
308     @Override
309     @RequestMapping(method = RequestMethod.POST, params = "methodToCall=downloadBOAttachment")
310     public ModelAndView downloadBOAttachment(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
311             HttpServletRequest request,
312             HttpServletResponse response) throws ServletRequestBindingException, FileNotFoundException, IOException {
313 
314         //first check if attachment connected to note
315         String noteIdentifierParameter = request.getParameter(KRADConstants.NOTE_IDENTIFIER);
316         if (noteIdentifierParameter != null) {
317             Long noteIdentifier = Long.valueOf(noteIdentifierParameter);
318             Note note = this.getNoteService().getNoteByNoteId(noteIdentifier);
319             if (note != null) {
320                 Attachment attachment = note.getAttachment();
321                 if (attachment != null) {
322 
323                     //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)
324                     attachment.setNote(note);
325 
326                     // Add attachment to response
327                     KRADUtils.addAttachmentToResponse(response, getAttachmentService().retrieveAttachmentContents(
328                             attachment), attachment.getAttachmentMimeTypeCode(), attachment.getAttachmentFileName(),
329                             attachment.getAttachmentFileSize());
330 
331                     return null;
332                 }
333             }
334         }
335 
336         MaintenanceDocumentForm form = (MaintenanceDocumentForm) uifForm;
337         MaintenanceDocument document = (MaintenanceDocument) form.getDocument();
338         Object dataObject = document.getDocumentDataObject();
339 
340         if (dataObject instanceof PersistableAttachment) {
341             PersistableAttachment attachment = (PersistableAttachment) dataObject;
342             byte[] attachmentContent = attachment.getAttachmentContent();
343             if (attachmentContent != null) {
344 
345                 ByteArrayInputStream inputStream = new ByteArrayInputStream(attachmentContent);
346                 KRADUtils.addAttachmentToResponse(response, inputStream, attachment.getContentType(),
347                         attachment.getFileName(), attachmentContent.length);
348                 return null;
349             }
350         } else if (dataObject instanceof PersistableAttachmentList) {
351             PersistableAttachmentList<PersistableAttachment> attachmentList =
352                     (PersistableAttachmentList<PersistableAttachment>) dataObject;
353             PersistableAttachmentList<PersistableAttachment> attachmentListBo =
354                     (PersistableAttachmentList<PersistableAttachment>) document.getNewMaintainableObject()
355                             .getDataObject();
356             PersistableAttachment attachment = (PersistableAttachment) attachmentListBo.getAttachments().get(
357                     Integer.parseInt(form.getActionParamaterValue("selectedLineIndex")));
358             byte[] attachmentContent = attachment.getAttachmentContent();
359             if (attachmentContent != null) {
360 
361                 ByteArrayInputStream inputStream = new ByteArrayInputStream(attachmentContent);
362                 KRADUtils.addAttachmentToResponse(response, inputStream, attachment.getContentType(),
363                         attachment.getFileName(), attachmentContent.length);
364                 return null;
365             }
366         }
367 
368         return null;
369     }
370 
371     protected MaintenanceDocumentService getMaintenanceDocumentService() {
372         return KRADServiceLocatorWeb.getMaintenanceDocumentService();
373     }
374 
375 }