001package org.kuali.ole.select.controller;
002
003import org.apache.log4j.Logger;
004import org.kuali.ole.OLEConstants;
005import org.kuali.ole.select.bo.OleCheckListBo;
006import org.kuali.ole.service.OleCheckListMaintenanceDocumentService;
007import org.kuali.rice.core.api.CoreApiServiceLocator;
008import org.kuali.rice.core.api.config.property.ConfigurationService;
009import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
010import org.kuali.rice.core.api.util.RiceKeyConstants;
011import org.kuali.rice.kim.api.identity.Person;
012import org.kuali.rice.krad.bo.PersistableAttachment;
013import org.kuali.rice.krad.bo.PersistableBusinessObject;
014import org.kuali.rice.krad.maintenance.MaintenanceDocument;
015import org.kuali.rice.krad.maintenance.MaintenanceUtils;
016import org.kuali.rice.krad.service.KRADServiceLocator;
017import org.kuali.rice.krad.util.GlobalVariables;
018import org.kuali.rice.krad.util.KRADConstants;
019import org.kuali.rice.krad.web.controller.MaintenanceDocumentController;
020import org.kuali.rice.krad.web.form.DocumentFormBase;
021import org.kuali.rice.krad.web.form.MaintenanceDocumentForm;
022import org.kuali.rice.krad.web.form.UifFormBase;
023import org.springframework.stereotype.Controller;
024import org.springframework.util.FileCopyUtils;
025import org.springframework.validation.BindingResult;
026import org.springframework.web.bind.annotation.ModelAttribute;
027import org.springframework.web.bind.annotation.RequestMapping;
028import org.springframework.web.multipart.MultipartFile;
029import org.springframework.web.servlet.ModelAndView;
030
031import javax.servlet.http.HttpServletRequest;
032import javax.servlet.http.HttpServletResponse;
033import java.io.*;
034import java.sql.Timestamp;
035import java.util.HashMap;
036import java.util.Map;
037import java.util.UUID;
038
039/**
040 * OleCheckListController is the controller class for CheckList Maintenance Document.
041 */
042@Controller
043@RequestMapping(value = "/oleCheckListMaintenance")
044public class OleCheckListController extends MaintenanceDocumentController {
045    protected static final Logger LOG = Logger.getLogger(OleCheckListController.class);
046
047    /**
048     * This method is used to download the attachment.
049     *
050     * @param form
051     * @param result
052     * @param request
053     * @param response
054     * @return ModelAndView
055     */
056    @RequestMapping(params = "methodToCall=downloadAttachment")
057    public ModelAndView downloadAttachment(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
058                                           HttpServletRequest request, HttpServletResponse response) {
059
060        String checkListId = request.getParameter("oleCheckListId");
061        Map criteriaMap = new HashMap();
062        criteriaMap.put("oleCheckListId", checkListId);
063        OleCheckListBo checkListBo = KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleCheckListBo.class, criteriaMap);
064        String fileName = "";
065        String objectId = "";
066        if (checkListBo != null) {
067            fileName = checkListBo.getFileName();
068            objectId = checkListBo.getObjectId();
069        }
070        String directory = getKualiConfigurationService().getPropertyValueAsString(
071                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + File.separator + "checkList" + File.separator + checkListBo.getRemoteObjectIdentifier();
072        if (LOG.isInfoEnabled()) {
073            LOG.info("file location : " + directory);
074        }
075
076        try {
077            File file = new File(directory);
078            response.setContentType(checkListBo.getMimeType());
079            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
080            response.setHeader("Expires", "0");
081            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
082            response.setHeader("Pragma", "public");
083            response.setContentLength((int) file.length());
084            InputStream fis = new BufferedInputStream(new FileInputStream(file));
085            FileCopyUtils.copy(fis, response.getOutputStream());
086        } catch (IOException e) {
087
088        }
089
090        return null;
091    }
092
093    /**
094     * This method invokes setupMaintenanceForDelete method to populate the document for deleting.
095     *
096     * @param form
097     * @param result
098     * @param request
099     * @param response
100     * @return ModelAndView
101     * @throws Exception
102     */
103    @RequestMapping(params = "methodToCall=" + "maintenanceDelete")
104    public ModelAndView maintenanceDelete(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
105                                          HttpServletRequest request, HttpServletResponse response) throws Exception {
106        setupMaintenanceForDelete(form, request, "Delete");
107        return getUIFModelAndView(form);
108    }
109
110    /**
111     * This method invokes deleteAttachment method to delete attachment and set the error accordingly ..
112     *
113     * @param form
114     * @param result
115     * @param request
116     * @param response
117     * @return ModelAndView
118     * @throws Exception
119     */
120    @RequestMapping(params = "methodToCall=" + "deleteDocument")
121    public ModelAndView deleteDocument(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
122                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
123        MaintenanceDocument document = form.getDocument();
124        OleCheckListBo oleCheckListBo = new OleCheckListBo();
125        if (document.getDocumentDataObject() != null) {
126            oleCheckListBo = (OleCheckListBo) document.getDocumentDataObject();
127            if (oleCheckListBo != null && oleCheckListBo.getRemoteObjectIdentifier() != null) {
128                boolean isDeleted = deleteAttachment(oleCheckListBo);
129                if (isDeleted) {
130                    KRADServiceLocator.getBusinessObjectService().delete(oleCheckListBo);
131                    GlobalVariables.getMessageMap().putInfoWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
132                            OLEConstants.OleLicenseRequest.MSG_DELETE_DOC);
133                } else {
134                    GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_MESSAGES, OLEConstants.OleLicenseRequest.ERROR_FILE_NOT_FOUND);
135                }
136            } else {
137                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_MESSAGES, OLEConstants.OleLicenseRequest.ERROR_CHECKLIST_NOT_FOUND);
138            }
139        }
140        return back(form, result, request, response);
141    }
142
143    /**
144     * This method populates confirmation to delete the document.
145     *
146     * @param form
147     * @param request
148     * @param maintenanceAction
149     */
150    protected void setupMaintenanceForDelete(MaintenanceDocumentForm form, HttpServletRequest request, String maintenanceAction) {
151        MaintenanceDocument document = form.getDocument();
152        if (document == null) {
153            document = getMaintenanceDocumentService()
154                    .setupNewMaintenanceDocument(form.getDataObjectClassName(), form.getDocTypeName(),
155                            maintenanceAction);
156
157            form.setDocument(document);
158            form.setDocTypeName(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
159        }
160
161        form.setMaintenanceAction(maintenanceAction);
162        getMaintenanceDocumentService().setupMaintenanceObjectForDelete(document, maintenanceAction, request.getParameterMap());
163        MaintenanceUtils.checkForLockingDocument(document, false);
164    }
165
166    /**
167     * This method is used to delete the attachment(checklist template) file.
168     *
169     * @param oleCheckListBo
170     * @return boolean
171     */
172    protected boolean deleteAttachment(OleCheckListBo oleCheckListBo) {
173        if (oleCheckListBo != null) {
174            String fullPathUniqueFileName = getKualiConfigurationService().getPropertyValueAsString(
175                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + File.separator + "checkList" + File.separator + oleCheckListBo.getRemoteObjectIdentifier();
176            File attachmentFile = new File(fullPathUniqueFileName);
177            return attachmentFile.delete();
178        }
179        return false;
180    }
181
182    @Override
183    protected OleCheckListMaintenanceDocumentService getMaintenanceDocumentService() {
184        return GlobalResourceLoader.getService("oleCheckListMaintenanceDocumentService");
185    }
186
187    public ConfigurationService getKualiConfigurationService() {
188        return GlobalResourceLoader.getService("kualiConfigurationService");
189    }
190
191    /**
192     * This method store the uploaded checklist template in the specified path and also populates the document
193     * for routing
194     *
195     * @param docForm
196     * @param result
197     * @param request
198     * @param response
199     * @return ModelAndView
200     */
201    @Override
202    @RequestMapping(params = "methodToCall=route")
203    public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase docForm, BindingResult result,
204                              HttpServletRequest request, HttpServletResponse response) {
205
206        ModelAndView modelAndView;
207        MaintenanceDocumentForm form = (MaintenanceDocumentForm) docForm;
208        MultipartFile attachmentFile = form.getAttachmentFile();
209        MaintenanceDocument document = form.getDocument();
210        OleCheckListBo oleCheckListBo = (OleCheckListBo) document.getNewMaintainableObject().getDataObject();
211        OleCheckListBo oleCheckListBoOld = (OleCheckListBo) document.getOldMaintainableObject().getDataObject();
212        Person kualiUser = GlobalVariables.getUserSession().getPerson();
213        if (kualiUser!=null){
214            oleCheckListBo.setAuthor(kualiUser.getPrincipalId());
215        }
216        oleCheckListBo.setLastModified((Timestamp) CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
217        if (form.getMaintenanceAction().equals("New")) {
218            try {
219                if (oleCheckListBo.getFileName() == null) {
220                    if ((attachmentFile.getSize() == 0 || (attachmentFile.getOriginalFilename().isEmpty() ||
221                            attachmentFile.getOriginalFilename().equalsIgnoreCase("")))) {
222                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
223                                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, "");
224                        modelAndView = getUIFModelAndView(form);
225                        return modelAndView;
226                    } else {
227                        oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
228                        oleCheckListBo.setMimeType(attachmentFile.getContentType());
229                        String remoteObjectIdentifier = UUID.randomUUID().toString();
230                        if (storeAttachment(attachmentFile, remoteObjectIdentifier))
231                            oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
232                    }
233                }
234            } catch (Exception e) {
235                LOG.error("EXception while storing the attachment "+e);
236            }
237        }
238        if (form.getMaintenanceAction().equals("Edit")) {
239            try {
240                if (!(attachmentFile.getOriginalFilename().isEmpty() ||
241                        attachmentFile.getOriginalFilename().equalsIgnoreCase(""))) {
242                    if (attachmentFile.getSize() == 0) {
243                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
244                                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename());
245                    } else {
246                        oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
247                        oleCheckListBo.setMimeType(attachmentFile.getContentType());
248                        String remoteObjectIdentifier = UUID.randomUUID().toString();
249                        if (storeAttachment(attachmentFile, remoteObjectIdentifier))
250                            deleteAttachment(oleCheckListBoOld);
251                        oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
252                    }
253                }
254            } catch (Exception e) {
255                LOG.error("EXception while storing the attachment "+e);
256            }
257        }
258
259
260        modelAndView = super.route(form, result, request, response);
261
262        if (document.getNewMaintainableObject().getDataObject() instanceof PersistableAttachment) {
263            PersistableAttachment bo = (PersistableAttachment) getBusinessObjectService()
264                    .retrieve((PersistableBusinessObject) document.getNewMaintainableObject().getDataObject());
265            request.setAttribute("fileName", bo.getFileName());
266        }
267
268        modelAndView = getUIFModelAndView(form);
269
270        return modelAndView;
271    }
272
273
274    /**
275     * Performs the blanket approve workflow action on the form document instance
276     *
277     * @param docForm - document form base containing the document instance that will be blanket approved
278     * @return ModelAndView
279     */
280    @RequestMapping(params = "methodToCall=blanketApprove")
281    public ModelAndView blanketApprove(@ModelAttribute("KualiForm") DocumentFormBase docForm, BindingResult result,
282                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
283        ModelAndView modelAndView;
284        MaintenanceDocumentForm form = (MaintenanceDocumentForm) docForm;
285        MultipartFile attachmentFile = form.getAttachmentFile();
286        MaintenanceDocument document = form.getDocument();
287        OleCheckListBo oleCheckListBo = (OleCheckListBo) document.getNewMaintainableObject().getDataObject();
288        OleCheckListBo oleCheckListBoOld = (OleCheckListBo) document.getOldMaintainableObject().getDataObject();
289        Person kualiUser = GlobalVariables.getUserSession().getPerson();
290        if (kualiUser != null) {
291            oleCheckListBo.setAuthor(kualiUser.getPrincipalId());
292        }
293        oleCheckListBo.setLastModified((Timestamp) CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
294        if (form.getMaintenanceAction().equals("New")) {
295            try {
296                if (oleCheckListBo.getFileName() == null) {
297                    if ((attachmentFile.getSize() == 0 || (attachmentFile.getOriginalFilename().isEmpty() ||
298                            attachmentFile.getOriginalFilename().equalsIgnoreCase("")))) {
299                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
300                                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, "");
301                        modelAndView = getUIFModelAndView(form);
302                        return modelAndView;
303                    } else {
304                        oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
305                        oleCheckListBo.setMimeType(attachmentFile.getContentType());
306                        String remoteObjectIdentifier = UUID.randomUUID().toString();
307                        if (storeAttachment(attachmentFile, remoteObjectIdentifier))
308                            oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
309                    }
310                }
311
312            } catch (Exception e) {
313                LOG.error("EXception while storing the attachment "+e);
314            }
315        }
316        if (form.getMaintenanceAction().equals("Edit")) {
317            try {
318                if (!(attachmentFile.getOriginalFilename().isEmpty() ||
319                        attachmentFile.getOriginalFilename().equalsIgnoreCase(""))) {
320                    if (attachmentFile.getSize() == 0) {
321                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
322                                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename());
323                    } else {
324                        oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
325                        oleCheckListBo.setMimeType(attachmentFile.getContentType());
326                        String remoteObjectIdentifier = UUID.randomUUID().toString();
327                        if (storeAttachment(attachmentFile, remoteObjectIdentifier))
328                            deleteAttachment(oleCheckListBoOld);
329                        oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
330                    }
331                }
332            } catch (Exception e) {
333                LOG.error("EXception while storing the attachment "+e);
334            }
335        }
336
337
338        modelAndView = super.blanketApprove(form, result, request, response);
339
340        if (document.getNewMaintainableObject().getDataObject() instanceof PersistableAttachment) {
341            PersistableAttachment bo = (PersistableAttachment) getBusinessObjectService()
342                    .retrieve((PersistableBusinessObject) document.getNewMaintainableObject().getDataObject());
343            request.setAttribute("fileName", bo.getFileName());
344        }
345
346        modelAndView = getUIFModelAndView(form);
347
348        return modelAndView;
349    }
350
351    /**
352     * This method stores uploaded checklist template in the specified path.
353     *
354     * @param attachedFile
355     * @param fileName
356     * @return boolean
357     * @throws java.io.IOException
358     */
359    public boolean storeAttachment(MultipartFile attachedFile, String fileName) throws IOException {
360        String location = null;
361        /*if(objectId != null) {
362            location  = getKualiConfigurationService().getPropertyValueAsString(
363                    KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY)+ File.separator+"checkList"+File.separator+objectId;
364        }
365        else {*/
366        location = getKualiConfigurationService().getPropertyValueAsString(
367                KRADConstants.ATTACHMENTS_PENDING_DIRECTORY_KEY) + File.separator + "checkList";
368        //}
369        if (LOG.isInfoEnabled()) {
370            LOG.info("file location : " + location);
371        }
372        File dirLocation = new File(location);
373        if (!dirLocation.exists()) {
374            boolean success = dirLocation.mkdirs();
375            if (!success) {
376                LOG.error("Could not generate directory for File at: " + dirLocation.getAbsolutePath());
377                return false;
378            }
379        }
380        location = location + File.separator + fileName;
381        File fileOut = new File(location);
382        FileOutputStream streamOut = null;
383        BufferedOutputStream bufferedStreamOut = null;
384        try {
385            InputStream fileContent = attachedFile.getInputStream();
386            streamOut = new FileOutputStream(fileOut);
387            bufferedStreamOut = new BufferedOutputStream(streamOut);
388            int c;
389            while ((c = fileContent.read()) != -1) {
390                bufferedStreamOut.write(c);
391            }
392        } finally {
393            bufferedStreamOut.close();
394            streamOut.close();
395        }
396        return true;
397    }
398
399    /**
400     * Saves the document instance contained on the form
401     *
402     * @param docForm - document form base containing the document instance that will be saved
403     * @return ModelAndView
404     */
405    @RequestMapping(params = "methodToCall=save")
406    public ModelAndView save(@ModelAttribute("KualiForm") DocumentFormBase docForm, BindingResult result,
407                             HttpServletRequest request, HttpServletResponse response) throws Exception {
408        ModelAndView modelAndView;
409        MaintenanceDocumentForm form = (MaintenanceDocumentForm) docForm;
410        MultipartFile attachmentFile = form.getAttachmentFile();
411        MaintenanceDocument document = form.getDocument();
412        OleCheckListBo oleCheckListBo = (OleCheckListBo) document.getNewMaintainableObject().getDataObject();
413        OleCheckListBo oleCheckListBoOld = (OleCheckListBo) document.getOldMaintainableObject().getDataObject();
414        Person kualiUser = GlobalVariables.getUserSession().getPerson();
415        if (kualiUser != null) {
416            oleCheckListBo.setAuthor(kualiUser.getPrincipalId());
417        }
418        oleCheckListBo.setLastModified((Timestamp) CoreApiServiceLocator.getDateTimeService().getCurrentTimestamp());
419        if (form.getMaintenanceAction().equals("New")) {
420            try {
421                if ((attachmentFile.getSize() == 0 || (attachmentFile.getOriginalFilename().isEmpty() ||
422                        attachmentFile.getOriginalFilename().equalsIgnoreCase("")))) {
423                    GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
424                            RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, "");
425                    modelAndView = getUIFModelAndView(form);
426                    return modelAndView;
427                } else {
428                    oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
429                    oleCheckListBo.setMimeType(attachmentFile.getContentType());
430                    String remoteObjectIdentifier = UUID.randomUUID().toString();
431                    if (storeAttachment(attachmentFile, remoteObjectIdentifier))
432                        oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
433                }
434            } catch (Exception e) {
435                LOG.error("EXception while storing the attachment "+e);
436            }
437        }
438        if (form.getMaintenanceAction().equals("Edit")) {
439            try {
440                if (!(attachmentFile.getOriginalFilename().isEmpty() ||
441                        attachmentFile.getOriginalFilename().equalsIgnoreCase(""))) {
442                    if (attachmentFile.getSize() == 0) {
443                        GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS,
444                                RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename());
445                    } else {
446                        oleCheckListBo.setFileName(attachmentFile.getOriginalFilename());
447                        oleCheckListBo.setMimeType(attachmentFile.getContentType());
448                        String remoteObjectIdentifier = UUID.randomUUID().toString();
449                        if (storeAttachment(attachmentFile, remoteObjectIdentifier))
450                            deleteAttachment(oleCheckListBoOld);
451                        oleCheckListBo.setRemoteObjectIdentifier(remoteObjectIdentifier);
452                    }
453                }
454            } catch (Exception e) {
455                LOG.error("EXception while storing the attachment "+e);
456            }
457        }
458
459
460        return super.save(form, result, request, response);
461    }
462
463}