001    package org.kuali.ole.license.controller;
002    
003    import org.apache.commons.lang.StringUtils;
004    import org.apache.log4j.Logger;
005    import org.kuali.ole.OLEConstants;
006    import org.kuali.ole.PropertyUtil;
007    import org.kuali.ole.ingest.OleLocationXMLSchemaValidator;
008    import org.kuali.ole.ingest.form.OleLocationForm;
009    import org.kuali.ole.ingest.pojo.MatchBo;
010    import org.kuali.ole.license.bo.*;
011    import org.kuali.ole.service.OleLicenseRequestService;
012    import org.kuali.ole.service.OleLocationConverterService;
013    import org.kuali.ole.service.impl.OleLicenseRequestServiceImpl;
014    import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
015    import org.kuali.rice.core.api.util.RiceKeyConstants;
016    import org.kuali.rice.kew.api.action.ActionRequest;
017    import org.kuali.rice.kew.api.document.node.RouteNodeInstance;
018    import org.kuali.rice.krad.bo.PersistableAttachment;
019    import org.kuali.rice.krad.bo.PersistableBusinessObject;
020    import org.kuali.rice.krad.maintenance.MaintenanceDocument;
021    import org.kuali.rice.krad.service.*;
022    import org.kuali.rice.krad.uif.UifConstants;
023    import org.kuali.rice.krad.uif.UifParameters;
024    import org.kuali.rice.krad.uif.container.CollectionGroup;
025    import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
026    import org.kuali.rice.krad.uif.view.View;
027    import org.kuali.rice.krad.util.GlobalVariables;
028    import org.kuali.rice.krad.util.KRADConstants;
029    import org.kuali.rice.krad.web.controller.DocumentControllerBase;
030    import org.kuali.rice.krad.web.controller.MaintenanceDocumentController;
031    import org.kuali.rice.krad.web.controller.UifControllerBase;
032    import org.kuali.rice.krad.web.form.DocumentFormBase;
033    import org.kuali.rice.krad.web.form.MaintenanceForm;
034    import org.kuali.rice.krad.web.form.UifFormBase;
035    import org.kuali.rice.krms.api.KrmsApiServiceLocator;
036    import org.kuali.rice.krms.api.engine.*;
037    import org.kuali.rice.krms.impl.repository.AgendaBo;
038    import org.springframework.stereotype.Controller;
039    import org.springframework.util.FileCopyUtils;
040    import org.springframework.validation.BindingResult;
041    import org.springframework.web.bind.annotation.ModelAttribute;
042    import org.springframework.web.bind.annotation.RequestMapping;
043    import org.springframework.web.bind.annotation.RequestMethod;
044    import org.springframework.web.multipart.MultipartFile;
045    import org.springframework.web.servlet.ModelAndView;
046    
047    import javax.servlet.http.HttpServletRequest;
048    import javax.servlet.http.HttpServletResponse;
049    import java.io.*;
050    import java.util.*;
051    
052    /**
053     * Created by IntelliJ IDEA.
054     * User: ?
055     * Date: 6/27/12
056     * Time: 6:20 PM
057     * To change this template use File | Settings | File Templates.
058     */
059    @Controller
060    @RequestMapping(value = "/oleLicenseRequest")
061    public class OleLicenseRequestController extends MaintenanceDocumentController {
062    
063        /**
064         *  This method populates date of the eventlog object thereby adding to the existing list.
065         * @param uifForm
066         * @param result
067         * @param request
068         * @param response
069         * @return ModelAndView
070         */
071        @RequestMapping(params = "methodToCall=addEventLogLine")
072        public ModelAndView addEventLogLine(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
073                                    HttpServletRequest request, HttpServletResponse response) {
074            MaintenanceForm form = (MaintenanceForm) uifForm;
075            String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
076            CollectionGroup collectionGroup = form.getPostedView().getViewIndex().getCollectionGroupByPath(
077                    selectedCollectionPath);
078            String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
079            Object eventObject = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath);
080            OleEventLogBo oleEventLogBo = (OleEventLogBo) eventObject;
081            //oleEventLogBo.setEventType("<user>");
082            oleEventLogBo.setCurrentTimeStamp();
083            return addLine(uifForm, result, request, response);
084        }
085    
086        /**
087         *  This method sets appropriate LicenseRequestStatusCode and gets the UUIDs for the agreement document from the docstore 
088         *          (ingesting into the docstore) and proceeds with normal routing.
089         * @param form
090         * @param result
091         * @param result
092         * @param request
093         * @param response
094         * @return ModelAndView
095         */
096        @Override
097        @RequestMapping(params = "methodToCall=route")
098        public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
099                                  HttpServletRequest request, HttpServletResponse response) {
100            MaintenanceForm maintenanceForm = (MaintenanceForm) form;
101            MaintenanceDocument document = (MaintenanceDocument) maintenanceForm.getDocument();
102            OleLicenseRequestBo oleLicenseRequestBo = (OleLicenseRequestBo)document.getNewMaintainableObject().getDataObject();
103            oleLicenseRequestBo.setAgreementId(UUID.randomUUID().toString());
104            oleLicenseRequestBo.setRequisitionDocNumber("3014");
105            oleLicenseRequestBo.setLicenseRequestStatusCode("LN");
106            List<OleAgreementDocumentMetadata> agreementDocuments = oleLicenseRequestBo.getAgreementDocumentMetadataList();
107            OleLicenseRequestService oleLicenseRequestService = new OleLicenseRequestServiceImpl();
108            List<OleAgreementDocumentMetadata> newAgreementDocuments = new ArrayList<OleAgreementDocumentMetadata>();
109            List<OleAgreementDocumentMetadata> checkInAgreementDocuments = new ArrayList<OleAgreementDocumentMetadata>();
110            if(agreementDocuments.size() > 0) {
111                for(OleAgreementDocumentMetadata agreementDocument : agreementDocuments) {
112                    if(isNewAgreementDocument(agreementDocument))
113                        newAgreementDocuments.add(agreementDocument);
114                    else
115                        checkInAgreementDocuments.add(agreementDocument);
116                }
117            }
118            List<OleAgreementDocumentMetadata> agreementDocumentMetadataList = new ArrayList<OleAgreementDocumentMetadata>();
119            if(newAgreementDocuments.size() > 0) {
120                agreementDocumentMetadataList.addAll(oleLicenseRequestService.processIngestAgreementDocuments(newAgreementDocuments));
121            }
122            if(checkInAgreementDocuments.size() > 0) {
123                agreementDocumentMetadataList.addAll(oleLicenseRequestService.processCheckInAgreementDocuments(checkInAgreementDocuments));
124            }
125            oleLicenseRequestBo.setAgreementDocumentMetadataList(agreementDocumentMetadataList);
126            String licenseRequestWorkflowTypeCode = oleLicenseRequestBo.getLicenseRequestWorkflowTypeCode();
127            if(licenseRequestWorkflowTypeCode.equalsIgnoreCase("SIGO"))  {
128                oleLicenseRequestBo.setLicenseRequestStatusCode("PSIG");
129            }else if(licenseRequestWorkflowTypeCode.equalsIgnoreCase("RVWO"))  {
130                oleLicenseRequestBo.setLicenseRequestStatusCode("PREV");
131            }else if(licenseRequestWorkflowTypeCode.equalsIgnoreCase("APPO"))  {
132                oleLicenseRequestBo.setLicenseRequestStatusCode("PAPP");
133            }else if(licenseRequestWorkflowTypeCode.equalsIgnoreCase("FAPP")){
134                oleLicenseRequestBo.setLicenseRequestStatusCode("PSIG");
135            }
136    
137            boolean valid = false;
138            EngineResults engineResult = executeEngineResults(oleLicenseRequestBo);
139            List<ResultEvent> allResults = engineResult.getAllResults();
140            for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
141                ResultEvent resultEvent = resultEventIterator.next();
142                if (resultEvent.getType().equals("Rule Evaluated")) {
143                    valid |= resultEvent.getResult();
144                }
145            }
146            if(!valid){
147                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleLicenseRequest.LICENSE_RULE_VAILDATIONS);
148            }
149    
150            String currentUser = GlobalVariables.getUserSession().getPrincipalName();
151            if(currentUser.equalsIgnoreCase(oleLicenseRequestBo.getAssignee()) && oleLicenseRequestBo.getEventLogs().size()<1){
152                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleLicenseRequest.LICENSE_EVENT_LOG_CHECK );
153            }
154            //modelAndView = super.route(form, result, request, response);
155    
156            return super.route(form, result, request, response);
157        }
158        /**
159         * Performs the approve workflow action on the document
160         *
161         * @param form - document form base containing the document instance that will be approved
162         * @return ModelAndView
163         */
164        @RequestMapping(params = "methodToCall=approve")
165        public ModelAndView approve(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
166                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
167            MaintenanceForm oldMaintenanceForm = (MaintenanceForm) form;
168            MaintenanceDocument oldDocument= (MaintenanceDocument) oldMaintenanceForm.getDocument();
169            OleLicenseRequestBo oldOleLicenseRequestBo = (OleLicenseRequestBo)oldDocument.getNewMaintainableObject().getDataObject();
170            List<ActionRequest> oldActionRequests = oldDocument.getDocumentHeader().getWorkflowDocument().getDocumentDetail().getActionRequests();
171            String roleName1="";
172            for(ActionRequest actionRequest1 : oldActionRequests){
173                if(actionRequest1.getStatus().getCode().equalsIgnoreCase("A")){
174                    roleName1 = actionRequest1.getQualifiedRoleNameLabel()!=null?actionRequest1.getQualifiedRoleNameLabel():"No Role";
175                    actionRequest1.isCurrent();
176                }
177            }
178            boolean validRule = false;
179            EngineResults engineResult = executeEngineResults((OleLicenseRequestBo)oldDocument.getNewMaintainableObject().getDataObject());
180            List<ResultEvent> allResults = engineResult.getAllResults();
181            for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
182                ResultEvent resultEvent = resultEventIterator.next();
183                if (resultEvent.getType().equals("Rule Evaluated")) {
184                    validRule |= resultEvent.getResult();
185                }
186            }
187            if(!validRule){
188                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleLicenseRequest.LICENSE_RULE_VAILDATIONS);
189            }
190            String currentUser = GlobalVariables.getUserSession().getPrincipalName();
191            boolean eventLogCheck = currentUser.equalsIgnoreCase(oldOleLicenseRequestBo.getAssignee()) && oldOleLicenseRequestBo.getEventLogs().size()<1;
192            if(eventLogCheck){
193                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleLicenseRequest.LICENSE_EVENT_LOG_CHECK );
194            }
195            if(!validRule || eventLogCheck){
196                return getUIFModelAndView(form);
197            }
198            performWorkflowAction(form, UifConstants.WorkflowAction.APPROVE, true);
199            MaintenanceForm maintenanceForm = (MaintenanceForm) form;
200            MaintenanceDocument document = (MaintenanceDocument) maintenanceForm.getDocument();
201            List<ActionRequest> actionRequests = document.getDocumentHeader().getWorkflowDocument().getDocumentDetail().getActionRequests();
202            OleLicenseRequestBo oleLicenseRequestBo = (OleLicenseRequestBo)document.getNewMaintainableObject().getDataObject();
203            List<RouteNodeInstance> routeNodeInstances = document.getDocumentHeader().getWorkflowDocument().getActiveRouteNodeInstances();
204            String nodeName = routeNodeInstances.get(0).getName();
205            for(ActionRequest actionRequest :actionRequests){
206                String roleName = actionRequest!=null && actionRequest.getQualifiedRoleNameLabel()!=null?actionRequest.getQualifiedRoleNameLabel():"No Role";
207                if(roleName.equalsIgnoreCase(roleName1)){
208                    if(roleName.equalsIgnoreCase("OLE_Signatory") && actionRequest.getStatus().getCode().equalsIgnoreCase("D")){
209                        oleLicenseRequestBo.setLicenseRequestStatusCode("SIGC");
210                        getDocumentService().saveDocument(document);
211                    }else if(nodeName.equalsIgnoreCase("Owner PeopleFlow") && actionRequest.getStatus().getCode().equalsIgnoreCase("D")){
212                        oleLicenseRequestBo.setLicenseRequestStatusCode("PSIG");
213                        getDocumentService().saveDocument(document);
214                    }else if(roleName.equalsIgnoreCase("OLE_LicenseReviewer") && actionRequest.getStatus().getCode().equalsIgnoreCase("D")){
215                        oleLicenseRequestBo.setLicenseRequestStatusCode("RVWC");
216                        getDocumentService().saveDocument(document);
217                    }else if(nodeName.equalsIgnoreCase("Owner PeopleFlow1") && actionRequest.getStatus().getCode().equalsIgnoreCase("D")){
218                        oleLicenseRequestBo.setLicenseRequestStatusCode("PAPP");
219                        getDocumentService().saveDocument(document);
220                    }else if(roleName.equalsIgnoreCase("OLE_Licensing_Approver") && actionRequest.getStatus().getCode().equalsIgnoreCase("D")){
221                        oleLicenseRequestBo.setLicenseRequestStatusCode("LC");
222                        getDocumentService().saveDocument(document);
223                    }
224                }
225            }
226            return returnToPrevious(form);
227        }
228        /**
229         * Performs the disapprove workflow action on the document 
230         *
231         * @param form - document form base containing the document instance that will be disapproved
232         * @return ModelAndView
233         */
234        @RequestMapping(params = "methodToCall=disapprove")
235        public ModelAndView disapprove(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
236                                       HttpServletRequest request, HttpServletResponse response) throws Exception {
237            MaintenanceForm maintenanceForm = (MaintenanceForm) form;
238            MaintenanceDocument document = (MaintenanceDocument) maintenanceForm.getDocument();
239            OleLicenseRequestBo oleLicenseRequestBo = (OleLicenseRequestBo)document.getNewMaintainableObject().getDataObject();
240            if(oleLicenseRequestBo.getEventLogs().size()<1){
241                GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleLicenseRequest.LICENSE_DISAPPROVE_VALIDATIONS);
242                return getUIFModelAndView(form);
243            }
244            oleLicenseRequestBo.setLicenseRequestStatusCode("LNF");
245            getDocumentService().saveDocument(document);
246            performWorkflowAction(form, UifConstants.WorkflowAction.DISAPPROVE, true);
247    
248            return returnToPrevious(form);
249        }
250    
251        /**
252         * Perform
253         * @param oleLicenseRequestBo
254         * @return EngineResults
255         */
256        private EngineResults executeEngineResults(OleLicenseRequestBo oleLicenseRequestBo){
257            Engine engine =  KrmsApiServiceLocator.getEngine();
258            EngineResults engineResult =null;
259            HashMap<String, Object> agendaValue = new HashMap<String, Object>();
260            agendaValue.put("nm", "LICENSE_POLICY");
261            List<AgendaBo> agendaBos = (List<AgendaBo>) KRADServiceLocator.getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
262            if(agendaBos!=null && agendaBos.size()>0){
263                AgendaBo agendaBo = agendaBos.get(0);
264                HashMap<String, String> map = new HashMap<String, String>();
265                map.put("AGENDA_NAME", agendaBo.getName());
266                List<MatchBo> matchBos = (List<MatchBo>) KRADServiceLocator.getBusinessObjectService().findMatching(MatchBo.class, map);
267    
268                SelectionCriteria selectionCriteria =
269                        SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()), getAgendaContext("LICENSE_POLICY"));
270    
271                ExecutionOptions executionOptions = new ExecutionOptions();
272                executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
273    
274                Facts.Builder factBuilder = Facts.Builder.create();
275    
276                String licenseType = getLicenseType(oleLicenseRequestBo.getLicenseRequestTypeId());
277                String workflowName = getWorkFlowName(oleLicenseRequestBo.getLicenseRequestWorkflowTypeCode()) ;
278                String agreementMethod =oleLicenseRequestBo.getAgreementMethod();
279                HashMap<String,Object> termValues = new HashMap<String, Object>() ;
280    
281                termValues.put("licenseType",licenseType);
282                termValues.put("agreementMethod",agreementMethod);
283                termValues.put("workflowName",workflowName);
284    
285    
286    
287                for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
288                    MatchBo matchBo = matchBoIterator.next();
289                    factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
290                }
291    
292    
293                engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
294            }
295            return engineResult;
296        }
297    
298        /**
299         *   This method returns selectionContext using contextName.
300         * @param contextName
301         * @return Map
302         */
303        protected Map<String, String> getSelectionContext(String contextName) {
304            Map<String, String> selector = new HashMap<String, String>();
305            selector.put(OLEConstants.NAMESPACE_CODE_SELECTOR, "OLE");
306            selector.put(OLEConstants.NAME_SELECTOR, contextName);
307            return selector;
308        }
309    
310        /**
311         *    This method returns agendaContext using agendaName.
312         * @param agendaName
313         * @return Map
314         */
315        protected Map<String, String> getAgendaContext(String agendaName) {
316            Map<String, String> selector = new HashMap<String, String>();
317            selector.put(OLEConstants.NAME_SELECTOR, agendaName);
318            return selector;
319        }
320    
321        /**
322         * This method returns LicenseType using licenseRequestTypeId.
323         * @param licenseRequestTypeId
324         * @return Map
325         */
326        private String getLicenseType(String licenseRequestTypeId){
327            OleLicenseRequestType oleLicenseRequestType = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestType.class, licenseRequestTypeId);
328            return oleLicenseRequestType.getName();
329        }
330    
331        /**
332         *   This method returns WorkFlowName using licenseRequestWorkflowTypeCode.
333         * @param licenseRequestWorkflowTypeCode
334         * @return
335         */
336        private String getWorkFlowName(String licenseRequestWorkflowTypeCode){
337            OleLicenseRequestWorkflowType oleLicenseRequestWorkflowType = KRADServiceLocator.getBusinessObjectService().findBySinglePrimaryKey(OleLicenseRequestWorkflowType.class, licenseRequestWorkflowTypeCode);
338            return oleLicenseRequestWorkflowType.getName();
339        }
340    
341        /**
342         * This method will add the agreement document to the existing list and also stores the attachment 
343         *   to the specified path.
344         *
345         * @param form - MaintenanceForm
346         * @return ModelAndView
347         */ 
348        @RequestMapping(params = "methodToCall=insertAgreementDocument")
349        public ModelAndView insertAgreementDocument(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
350                                                    HttpServletRequest request, HttpServletResponse response) {
351    
352            MaintenanceForm form = (MaintenanceForm) uifForm;
353            String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH);
354            CollectionGroup collectionGroup = form.getPostedView().getViewIndex().getCollectionGroupByPath(
355                    selectedCollectionPath);
356            String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath();
357            Object eventObject = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath);
358            OleAgreementDocumentMetadata oleAgreementDocumentMetadata = (OleAgreementDocumentMetadata)eventObject;
359            oleAgreementDocumentMetadata.setCurrentTimeStamp();
360            String userName = GlobalVariables.getUserSession().getPrincipalName();
361            oleAgreementDocumentMetadata.setUploadedBy(userName);
362    
363            MultipartFile attachmentFile = form.getAttachmentFile();
364    
365            if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getOriginalFilename())) {
366                if (attachmentFile.getSize() == 0) {
367                    GlobalVariables.getMessageMap().putError(String.format("%s.%s",
368                            "document.agreementDocumentMetadataList",
369                            KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME), RiceKeyConstants.ERROR_UPLOADFILE_EMPTY,
370                            attachmentFile.getOriginalFilename());
371                } else {
372                    try {
373                        oleAgreementDocumentMetadata.setAgreementFileName(attachmentFile.getOriginalFilename());
374                        oleAgreementDocumentMetadata.setAgreementMimeType(attachmentFile.getContentType());
375                        storeAgreementAttachment(attachmentFile);
376                    }
377                    catch(Exception e) {
378                        LOG.error("Error while storing the Agreement Document");
379                    }
380    
381                }
382            }
383            return addLine(uifForm, result, request, response);
384        }
385    
386         /**
387         * This method will deletes the agreement document from the existing list 
388         *
389         * @param form - MaintenanceForm
390         * @return ModelAndView
391         */ 
392        @RequestMapping(params = "methodToCall=deleteAgreementDocument")
393        public ModelAndView deleteAgreementDocument(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
394                                                    HttpServletRequest request, HttpServletResponse response) {
395    
396            return deleteLine(uifForm, result, request, response);
397        }
398    
399         /**
400         * This method will download the agreement document from the docstore if it is already ingested 
401         *   otherwise will download from the temprovary location.
402         *
403         * @param form - MaintenanceForm
404         * @return ModelAndView
405         */ 
406        @RequestMapping(params = "methodToCall=downloadAgreement")
407        public ModelAndView downloadAgreement(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
408                                              HttpServletRequest request,
409                                              HttpServletResponse response) {
410            String selectedLineIndex = uifForm.getActionParamaterValue("selectedLineIndex");
411            MaintenanceForm maintenanceForm = (MaintenanceForm) uifForm;
412            MaintenanceDocument document = (MaintenanceDocument) maintenanceForm.getDocument();
413            OleLicenseRequestBo oleLicenseRequestBo = (OleLicenseRequestBo)document.getNewMaintainableObject().getDataObject();
414            OleAgreementDocumentMetadata oleAgreementDocumentMetadata = oleLicenseRequestBo.getAgreementDocumentMetadataList().get(Integer.parseInt(selectedLineIndex));
415            File file;
416            try {
417                if(oleAgreementDocumentMetadata.getAgreementUUID() == null) {
418                    file = new File(OLEConstants.OleLicenseRequest.AGREEMENT_LOCATION +
419                            File.separator+oleAgreementDocumentMetadata.getAgreementFileName()) ;
420    
421                }
422                else {
423                    OleLicenseRequestService oleLicenseRequestService = new OleLicenseRequestServiceImpl();
424                    file = oleLicenseRequestService.downloadAgreementDocumentFromDocstore(oleAgreementDocumentMetadata);
425    
426                }
427                response.setContentType(oleAgreementDocumentMetadata.getAgreementMimeType());
428                response.setContentLength((int) file.length());
429                response.setHeader("Expires", "0");
430                response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
431                response.setHeader("Pragma", "public");
432                response.setHeader("Content-Disposition",
433                        "attachment; filename=\"" + oleAgreementDocumentMetadata.getAgreementFileName()+ "\"");
434                InputStream fis = new BufferedInputStream(new FileInputStream(file));
435                FileCopyUtils.copy(fis, response.getOutputStream());
436    
437            }
438            catch (Exception e) {
439                LOG.error("Error while retrieving the attachment");
440            }
441    
442            return null;
443        }
444    
445         /**
446         * This method will populate the url which will be used to view the related Requisition Document 
447         *
448         * @param form - MaintenanceForm
449         * @return ModelAndView
450         */ 
451        @RequestMapping(params = "methodToCall=viewRelatedDocument")
452        public ModelAndView viewRelatedDocument(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result,
453                                                HttpServletRequest request,
454                                                HttpServletResponse response) {
455            ModelAndView modelAndView = new ModelAndView();
456            MaintenanceForm maintenanceForm = (MaintenanceForm) uifForm;
457            String oleurl = PropertyUtil.getPropertyUtil().getProperty("ole.url") ;
458            String olePortal = oleurl.substring(0,oleurl.indexOf("portal.jsp"));
459            String requisitionDocNumber = request.getParameter("requisitionDocNumber");
460            Map criteriaMap = new HashMap();
461            criteriaMap.put("requisitionDocNumber",requisitionDocNumber);
462            List<OleLicenseRequestBo> oleLicenseRequestBoList = (List<OleLicenseRequestBo>)KRADServiceLocator.getBusinessObjectService().findMatching(OleLicenseRequestBo.class,criteriaMap);
463            if(oleLicenseRequestBoList.size() > 0) {
464                String redirectUrl = olePortal+"kew/DocHandler.do?command=displayDocSearchView&docId="+oleLicenseRequestBoList.get(0).getRequisitionDocNumber();
465                GlobalVariables.getUifFormManager().removeForm(uifForm);
466                modelAndView = new ModelAndView(REDIRECT_PREFIX + redirectUrl);
467            }
468    
469            return modelAndView;
470        }
471    
472         /**
473         * This method store the uploaded agreement document to the specified location
474         *
475         * @param form - MaintenanceForm
476         * @return ModelAndView
477         */ 
478        private void storeAgreementAttachment(MultipartFile agreementFile) throws IOException {
479            String location = "";
480            location  = "/tmp/agreement_tmp";
481    
482            File dirLocation = new File(location);
483            if(!dirLocation.exists()) {
484                boolean  success = dirLocation.mkdirs();
485                if(!success)
486                    LOG.error("Could not generate directory for File at: " + dirLocation.getAbsolutePath());
487            }
488            location = location+File.separator+agreementFile.getOriginalFilename();
489            InputStream fileContents = agreementFile.getInputStream();
490            File fileOut = new File(location);
491            FileOutputStream streamOut = null;
492            BufferedOutputStream bufferedStreamOut = null;
493            try {
494                streamOut = new FileOutputStream(fileOut);
495                bufferedStreamOut = new BufferedOutputStream(streamOut);
496                int c;
497                while ((c = fileContents.read()) != -1) {
498                    bufferedStreamOut.write(c);
499                }
500            }
501            finally {
502                bufferedStreamOut.close();
503                streamOut.close();
504            }
505    
506        }
507    
508        /**
509         *   This method true if the agreement document is new.
510         * @param agreementDocumentMetadata
511         * @return boolean
512         */
513        private boolean isNewAgreementDocument (OleAgreementDocumentMetadata agreementDocumentMetadata) {
514            return agreementDocumentMetadata.getAgreementUUID() == null;
515        }
516    }