View Javadoc
1   package org.kuali.ole.deliver.controller;
2   
3   import org.apache.log4j.Logger;
4   import org.kuali.asr.ASRConstants;
5   import org.kuali.asr.service.ASRHelperServiceImpl;
6   import org.kuali.ole.DataCarrierService;
7   import org.kuali.ole.OLEConstants;
8   import org.kuali.ole.deliver.batch.OleDeliverBatchServiceImpl;
9   import org.kuali.ole.deliver.bo.OleCirculationDesk;
10  import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
11  import org.kuali.ole.deliver.bo.OleDeliverRequestType;
12  import org.kuali.ole.deliver.bo.OleLoanDocument;
13  import org.kuali.ole.deliver.processor.LoanProcessor;
14  import org.kuali.ole.deliver.service.OLEDeliverNoticeHelperService;
15  import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
16  import org.kuali.ole.deliver.service.impl.OLEDeliverNoticeHelperServiceImpl;
17  import org.kuali.ole.docstore.common.document.content.instance.Item;
18  import org.kuali.ole.ingest.pojo.MatchBo;
19  import org.kuali.ole.sys.context.SpringContext;
20  import org.kuali.ole.util.DocstoreUtil;
21  import org.kuali.rice.core.api.exception.RiceRuntimeException;
22  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
23  import org.kuali.rice.core.api.util.xml.XmlHelper;
24  import org.kuali.rice.kew.rule.xmlrouting.XPathHelper;
25  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
26  import org.kuali.rice.krad.maintenance.MaintenanceUtils;
27  import org.kuali.rice.krad.service.KRADServiceLocator;
28  import org.kuali.rice.krad.util.GlobalVariables;
29  import org.kuali.rice.krad.util.KRADConstants;
30  import org.kuali.rice.krad.util.ObjectUtils;
31  import org.kuali.rice.krad.web.controller.MaintenanceDocumentController;
32  import org.kuali.rice.krad.web.form.DocumentFormBase;
33  import org.kuali.rice.krad.web.form.MaintenanceDocumentForm;
34  import org.kuali.rice.krad.web.form.UifFormBase;
35  import org.kuali.rice.krms.api.KrmsApiServiceLocator;
36  import org.kuali.rice.krms.api.engine.*;
37  import org.kuali.rice.krms.impl.repository.AgendaBo;
38  import org.springframework.stereotype.Controller;
39  import org.springframework.validation.BindingResult;
40  import org.springframework.web.bind.annotation.ModelAttribute;
41  import org.springframework.web.bind.annotation.RequestMapping;
42  import org.springframework.web.servlet.ModelAndView;
43  import org.w3c.dom.Document;
44  
45  import javax.servlet.http.HttpServletRequest;
46  import javax.servlet.http.HttpServletResponse;
47  import javax.xml.xpath.XPath;
48  import javax.xml.xpath.XPathConstants;
49  import java.io.ByteArrayInputStream;
50  import java.sql.Timestamp;
51  import java.util.*;
52  
53  /**
54   * Created with IntelliJ IDEA.
55   * User: ?
56   * Date: 10/17/12
57   * Time: 1:59 PM
58   * To change this template use File | Settings | File Templates.
59   */
60  @Controller
61  @RequestMapping(value = "/deliverRequestMaintenance")
62  public class OleDeliverRequestMaintenanceDocumentController extends MaintenanceDocumentController {
63      private static final Logger LOG = Logger.getLogger(OleDeliverRequestMaintenanceDocumentController.class);
64      private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
65      private static final String NAME_SELECTOR = "name";
66      private final static String RULE_EVALUATED = "Rule Evaluated";
67      private final static String ROUTED_EXTERNAL = "Routed External";
68      private LoanProcessor loanProcessor;
69      private DocstoreUtil docstoreUtil = getDocstoreUtil();
70      private OleDeliverRequestDocumentHelperServiceImpl service =  getService();
71      private OLEDeliverNoticeHelperService oleDeliverNoticeHelperService ;
72  
73      /**
74       * This method initiate LoanProcessor.
75       *
76       * @return LoanProcessor
77       */
78      private LoanProcessor getLoanProcessor() {
79          if (loanProcessor == null) {
80              loanProcessor = new LoanProcessor();
81          }
82          return loanProcessor;
83      }
84  
85      public DocstoreUtil getDocstoreUtil(){
86          if(docstoreUtil == null){
87              docstoreUtil = new DocstoreUtil();
88          }
89          return docstoreUtil;
90      }
91  
92      public OleDeliverRequestDocumentHelperServiceImpl getService(){
93          if(service == null){
94              service = new OleDeliverRequestDocumentHelperServiceImpl();
95          }
96          return service;
97  
98      }
99  
100     public OLEDeliverNoticeHelperService getOleDeliverNoticeHelperService() {
101         if(oleDeliverNoticeHelperService ==null){
102             oleDeliverNoticeHelperService = SpringContext.getBean(OLEDeliverNoticeHelperServiceImpl.class);
103         }
104         return oleDeliverNoticeHelperService;
105     }
106 
107     public void setOleDeliverNoticeHelperService(OLEDeliverNoticeHelperService oleDeliverNoticeHelperService) {
108         this.oleDeliverNoticeHelperService = oleDeliverNoticeHelperService;
109     }
110 
111     @RequestMapping(params = "methodToCall=" + "maintenanceCancel")
112     public ModelAndView maintenanceCancel(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
113                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
114         setupMaintenanceForDelete(form, request, "Cancel");
115         return getUIFModelAndView(form);
116     }
117 
118 
119     /**
120      * This method invokes deleteAttachment method to delete attachment and set the error accordingly ..
121      *
122      * @param form
123      * @param result
124      * @param request
125      * @param response
126      * @return ModelAndView
127      * @throws Exception
128      */
129     @RequestMapping(params = "methodToCall=" + "cancelDocument")
130     public ModelAndView cancelDocument(@ModelAttribute("KualiForm") MaintenanceDocumentForm form, BindingResult result,
131                                        HttpServletRequest request, HttpServletResponse response) throws Exception {
132         LOG.debug("Inside Cancel document");
133         MaintenanceDocument document = form.getDocument();
134         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) document.getOldMaintainableObject().getDataObject();
135         service.cancelDocument(oleDeliverRequestBo);
136 
137         return back(form, result, request, response);
138     }
139 
140     /**
141      * This method populates confirmation to delete the document.
142      *
143      * @param form
144      * @param request
145      * @param maintenanceAction
146      */
147     protected void setupMaintenanceForDelete(MaintenanceDocumentForm form, HttpServletRequest request, String maintenanceAction) {
148         MaintenanceDocument document = form.getDocument();
149         if (document == null) {
150             document = getMaintenanceDocumentService()
151                     .setupNewMaintenanceDocument(form.getDataObjectClassName(), form.getDocTypeName(),
152                             maintenanceAction);
153 
154             form.setDocument(document);
155             form.setDocTypeName(document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName());
156         }
157 
158         form.setMaintenanceAction(maintenanceAction);
159         getMaintenanceDocumentService().setupMaintenanceObject(document, maintenanceAction, request.getParameterMap());
160         MaintenanceUtils.checkForLockingDocument(document, false);
161     }
162 
163     @Override
164     @RequestMapping(params = "methodToCall=route")
165     public ModelAndView route(@ModelAttribute("KualiForm") DocumentFormBase form, BindingResult result,
166                               HttpServletRequest request, HttpServletResponse response) {
167         LOG.debug("Inside route document");
168 
169         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
170         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) form.getDocument();
171         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) maintenanceDocument.getDocumentDataObject();
172         oleDeliverRequestBo.setMessage(null);
173         oleDeliverRequestBo.setValidToProcess(true);
174         if (oleDeliverRequestBo.getOperatorModifiedId() == null) {
175             if (!docstoreUtil.isItemAvailableInDocStore(oleDeliverRequestBo)) {
176                 oleDeliverRequestBo.setValidToProcess(false);
177                 GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID, OLEConstants.ITEM_NOT_AVAILABLE);
178                 //return super.route(form,result,request,response);
179             }
180 
181             oleDeliverRequestBo = service.processRequestType(oleDeliverRequestBo);
182             if (oleDeliverRequestBo.getBorrowerId() == null) {
183                 oleDeliverRequestBo.setValidToProcess(false);
184                 GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID, OLEConstants.OleDeliverRequest.INVALID_PATRON_BARCODE);
185                 return getUIFModelAndView(form);
186             }
187             if (oleDeliverRequestBo.getRequestTypeId() == null || (oleDeliverRequestBo.getRequestTypeId() != null && oleDeliverRequestBo.getRequestTypeId().trim().isEmpty())) {
188                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleDeliverRequest.INVALID_REQUEST_TYPE);
189                 oleDeliverRequestBo.setValidToProcess(false);
190                 // return getUIFModelAndView(form);
191             }
192             if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON) && oleDeliverRequestBo.getProxyBorrowerId() == null) {
193                 GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.PROXY_BORROWER_ID, OLEConstants.OleDeliverRequest.INVALID_PROXY_PATRON);
194                 oleDeliverRequestBo.setValidToProcess(false);
195                 //  return getUIFModelAndView(form);
196             }
197             if (oleDeliverRequestBo.getRequestTypeId() != null && !oleDeliverRequestBo.getRequestTypeId().equals("7") && !oleDeliverRequestBo.getRequestTypeId().equals("8")) {
198 
199                 String message = service.patronRecordExpired(oleDeliverRequestBo);
200                 if (message != null) {
201                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID, message);
202                     oleDeliverRequestBo.setValidToProcess(false);
203                 }
204 
205                 if (!service.isValidProxyPatron(oleDeliverRequestBo)) {
206                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.PROXY_BORROWER_ID, OLEConstants.OleDeliverRequest.INVALID_PROXY);
207                     oleDeliverRequestBo.setValidToProcess(false);
208                 }
209                 if (!service.validateDeliveryPrivilege(oleDeliverRequestBo)) {
210                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.NO_DELIVERY_PRIVILEGE);
211                     oleDeliverRequestBo.setValidToProcess(false);
212                 }
213                 if (!service.validatePagingPrivilege(oleDeliverRequestBo)) {
214                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.NO_PAGE_PRIVILEGE);
215                     oleDeliverRequestBo.setValidToProcess(false);
216                 }
217 
218                 if (service.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo)) {
219                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.ALREADY_RAISED);
220                     oleDeliverRequestBo.setValidToProcess(false);
221                 }
222 
223                 /* if( service.isItemAvailable(oleDeliverRequestBo)){
224                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID,OLEConstants.OleDeliverRequest.ITEM_AVAILABLE);
225                 }*/
226                 ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
227                 String itemLocation = oleDeliverRequestBo.getItemLocation();
228                 if(itemLocation!=null ){
229                     if (oleDeliverRequestBo.isASRItem() && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && !oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))){
230                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "Cannot create "+oleDeliverRequestBo.getRequestTypeCode()+" for this item");
231                         oleDeliverRequestBo.setValidToProcess(false);
232                     }else if(oleDeliverRequestBo.isASRItem() && !oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))){
233                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "Cannot create "+oleDeliverRequestBo.getRequestTypeCode()+" for this item");
234                         oleDeliverRequestBo.setValidToProcess(false);
235                     }
236                 }
237                 if (!service.canRaiseRequest(oleDeliverRequestBo)) {
238                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID, OLEConstants.OleDeliverRequest.NO_REQUEST,oleDeliverRequestBo.getRequestTypeCode(), oleDeliverRequestBo.getItemStatus());
239                     oleDeliverRequestBo.setValidToProcess(false);
240                 }
241                 if (!service.isItemEligible(oleDeliverRequestBo)) {
242                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID, OLEConstants.OleDeliverRequest.ITEM_NOT_ELIGIBLE);
243                     oleDeliverRequestBo.setValidToProcess(false);
244                 }
245 
246                 if (service.isAlreadyLoaned(oleDeliverRequestBo)) {
247                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID, OLEConstants.OleDeliverRequest.ITEM_ALREADY_LOANED);
248                     oleDeliverRequestBo.setValidToProcess(false);
249                 }
250 
251             }
252             if (oleDeliverRequestBo.getRequestTypeId() != null && oleDeliverRequestBo.getRequestTypeId().equals("8")) {
253                 if (!oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR)) {
254                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.TRANSIT_ERROR);
255                     oleDeliverRequestBo.setValidToProcess(false);
256                 }
257                 else if (!service.isItemAvailableForLoan(oleDeliverRequestBo)) {
258                     if (service.isRequestRaised(oleDeliverRequestBo)) {
259                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.ITEM_IN_LOAN);
260                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.TRANSIT_REQUEST_RAISED);
261                         oleDeliverRequestBo.setValidToProcess(false);
262                     }
263                     else
264                     {
265                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.ITEM_IN_LOAN);
266                         oleDeliverRequestBo.setValidToProcess(false);
267                     }
268 
269                 }
270                 else  if (service.isRequestRaised(oleDeliverRequestBo)) {
271                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.TRANSIT_REQUEST_RAISED);
272                     oleDeliverRequestBo.setValidToProcess(false);
273                 }
274 
275                 else if (service.processOperator(GlobalVariables.getUserSession().getPrincipalId())) {
276                     LoanProcessor loanProcessor = getLoanProcessor();
277                     try {
278 
279                         Item oleItem = oleDeliverRequestBo.getOleItem();
280                         oleItem.setItemStatusEffectiveDate(new Date(System.currentTimeMillis()).toString());
281                         if (oleDeliverRequestBo.getInTransitCheckInNote() != null && !oleDeliverRequestBo.getInTransitCheckInNote().isEmpty()) {
282                             oleItem.setCheckinNote(oleDeliverRequestBo.getInTransitCheckInNote());
283                         }
284                         loanProcessor.updateItemStatus(oleItem, OLEConstants.OleDeliverRequest.INTRANSIT_STATUS);
285                     } catch (Exception e) {
286                         LOG.error("Exception", e);
287                     }
288                 /*    if (!service.isItemAvailableForLoan(oleDeliverRequestBo)) {
289                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.ITEM_IN_LOAN);
290                     }
291                     if (service.isRequestRaised(oleDeliverRequestBo)) {
292                         GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.TRANSIT_REQUEST_RAISED);
293                     }    */
294 
295                 } else {
296                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR, OLEConstants.OleDeliverRequest.INVALID_OPERATOR);
297                     oleDeliverRequestBo.setValidToProcess(false);
298                 }
299             }
300             if (oleDeliverRequestBo.getRequestTypeId() != null && oleDeliverRequestBo.getRequestTypeId().equals("7")) {
301                 String message = service.patronRecordExpired(oleDeliverRequestBo);
302                 if (message != null) {
303                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID, message);
304                     oleDeliverRequestBo.setValidToProcess(false);
305                 }
306                 if (service.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo)) {
307                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID, OLEConstants.OleDeliverRequest.ALREADY_RAISED);
308                     oleDeliverRequestBo.setValidToProcess(false);
309                 }
310                 if (!service.canRaiseRequest(oleDeliverRequestBo)) {
311                     GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.ITEM_ID, OLEConstants.OleDeliverRequest.NO_REQUEST,oleDeliverRequestBo.getRequestTypeCode(), oleDeliverRequestBo.getItemStatus());
312                     oleDeliverRequestBo.setValidToProcess(false);
313                  }
314 
315             }
316 
317             oleDeliverRequestBo = service.processRequester(oleDeliverRequestBo);
318              if(oleDeliverRequestBo.isValidToProcess()){
319             boolean valid = false;
320             EngineResults engineResult = executeEngineResults(oleDeliverRequestBo);
321             if (engineResult != null) {
322                 List<ResultEvent> allResults = engineResult.getAllResults();
323                 if (allResults.size() > 0) {
324                     for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
325                         ResultEvent resultEvent = resultEventIterator.next();
326                         if (resultEvent.getType().equals(RULE_EVALUATED)) {
327                             valid |= resultEvent.getResult();
328                         }
329                     }
330                 }
331                 if(oleDeliverRequestBo.getNewDueDate() != null){
332                     try {
333                         Item oleItem = oleDeliverRequestBo.getOleItem();
334                         oleItem.setDueDateTime(loanProcessor.convertToString(new Timestamp(oleDeliverRequestBo.getNewDueDate().getTime())));
335                         loanProcessor.updateItemStatus(oleItem,oleItem.getItemStatus().getCodeValue());
336                     } catch (Exception e) {
337                         LOG.error("Exception", e);
338                     }
339                 }
340             }
341             //  oleDeliverRequestBo = service.reOrderQueuePosition(oleDeliverRequestBo);
342         }
343         if ((oleDeliverRequestBo.getMessage() != null && !oleDeliverRequestBo.getMessage().isEmpty())) {
344             return getUIFModelAndView(form);
345         }
346        // oleDeliverRequestBo.setItemFullLocation(oleDeliverRequestBo.getOleItem().);
347         oleDeliverRequestBo.setOleItem(null);
348 
349         return  super.route(form, result, request, response);
350         }else{
351             return getUIFModelAndView(form);
352         }
353     }
354 
355 
356     private EngineResults executeEngineResults(OleDeliverRequestBo oleDeliverRequestBo) {
357         List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
358         List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
359         List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
360         List<OleDeliverRequestBo> asrList = new ArrayList<OleDeliverRequestBo>();
361         List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
362         Engine engine = KrmsApiServiceLocator.getEngine();
363         EngineResults engineResult = null;
364         HashMap<String, Object> agendaValue = new HashMap<String, Object>();
365         agendaValue.put(OLEConstants.NAME_NM, OLEConstants.REQUEST_AGENDA_NM);
366         List<AgendaBo> agendaBos = (List<AgendaBo>) KRADServiceLocator.getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
367         if (agendaBos != null && agendaBos.size() > 0) {
368             AgendaBo agendaBo = agendaBos.get(0);
369             HashMap<String, String> map = new HashMap<String, String>();
370             map.put(OLEConstants.AGENDA_NAME, agendaBo.getName());
371             List<MatchBo> matchBos = (List<MatchBo>) KRADServiceLocator.getBusinessObjectService().findMatching(MatchBo.class, map);
372 
373             SelectionCriteria selectionCriteria =
374                     SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()),
375                             getAgendaContext(OLEConstants.REQUEST_AGENDA_NM));
376 
377             ExecutionOptions executionOptions = new ExecutionOptions();
378             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
379 
380             Facts.Builder factBuilder = Facts.Builder.create();
381 
382             String borrowerType = "";
383             if (oleDeliverRequestBo.getOlePatron() != null && oleDeliverRequestBo.getOlePatron().getOleBorrowerType() != null) {
384                 borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeCode();
385             }
386             String itemType = oleDeliverRequestBo.getItemType();
387 
388             String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
389 
390             String requestType = oleDeliverRequestBo.getRequestTypeCode();
391 
392             String location = oleDeliverRequestBo.getShelvingLocation();
393             LoanProcessor loanProcessor = getLoanProcessor();
394             OleLoanDocument oleLoanDocument = loanProcessor.getOleLoanDocumentUsingItemUUID(oleDeliverRequestBo.getItemUuid());
395             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
396             dataCarrierService.addData(OLEConstants.LOANED_DATE, oleLoanDocument != null ? oleLoanDocument.getCreateDate() : null);
397             dataCarrierService.addData(OLEConstants.DUE_DATE,oleLoanDocument!=null?oleLoanDocument.getLoanDueDate():null);
398             String patronId = oleDeliverRequestBo.getBorrowerId()!=null ?  oleDeliverRequestBo.getBorrowerId() : "";
399             String itemId = oleDeliverRequestBo.getItemId()!=null ?  oleDeliverRequestBo.getItemId() : "";
400             dataCarrierService.removeData(patronId+itemId);
401             String borrowerId = oleDeliverRequestBo.getBorrowerId();
402             Map<String, String> requestMap = new HashMap<String, String>();
403             requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
404             if (requestTypeId != null && (requestTypeId.equals("1") || requestTypeId.equals("2"))) {
405                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
406                 recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
407                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
408                 recallList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
409             } else if (requestTypeId != null && (requestTypeId.equals("3") || requestTypeId.equals("4"))) {
410                 //  holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
411                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
412                 holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
413                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
414                 holdList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
415             } else if (requestTypeId != null && (requestTypeId.equals("5") || requestTypeId.equals("6"))) {
416                 // pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
417                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
418                 pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
419                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
420                 pageList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
421             } else if(requestTypeId != null && (requestTypeId.equals("9"))){
422                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
423                 asrList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
424 
425             }
426             Map<String, String> requestByBorrower = new HashMap<String, String>();
427             requestByBorrower.put(OLEConstants.OleDeliverRequest.BORROWER_ID, borrowerId);
428             requestsByBorrower = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestByBorrower);
429             HashMap<String, Object> termValues = new HashMap<String, Object>();
430             termValues.put(OLEConstants.BORROWER_TYPE, borrowerType);
431             termValues.put(OLEConstants.ITEM_TYPE, itemType);
432             termValues.put(OLEConstants.LOCATION, location);
433             termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
434             termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
435             termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
436             termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
437             termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
438             termValues.put(OLEConstants.MAX_NO_OF_RECALL_REQUEST, new Integer(recallList.size()) + 1);
439             termValues.put(OLEConstants.MAX_NO_OF_HOLD_REQUEST, new Integer(holdList.size()) + 1);
440             termValues.put(OLEConstants.MAX_NO_OF_PAGE_REQUEST, new Integer(pageList.size()) + 1);
441             termValues.put(OLEConstants.MAX_NO_OF_ASR_REQUEST, new Integer(asrList.size()) + 1);
442             termValues.put(OLEConstants.OleDeliverRequest.CLAIMS_RETURNED_FLAG, oleDeliverRequestBo.isClaimsReturnedFlag());
443             // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
444             termValues.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, requestTypeId);
445             termValues.put(OLEConstants.REQUEST_TYPE, requestType);
446             termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
447             termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
448 
449             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
450                 MatchBo matchBo = matchBoIterator.next();
451                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
452             }
453             if (LOG.isDebugEnabled()){
454                 LOG.debug("termValues.toString()" + termValues.toString());
455             }
456             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
457             dataCarrierService.removeData(patronId+itemId);
458             List<String> errorMessage = (List<String>) engineResult.getAttribute(OLEConstants.ERROR_ACTION);
459             java.sql.Date d = (java.sql.Date) engineResult.getAttribute(OLEConstants.REQ_EXPIRATION_DATE);
460             Timestamp recallDueDate = (Timestamp) engineResult.getAttribute(OLEConstants.RECALL_DUE_DATE);
461             String notice = (String) engineResult.getAttribute(OLEConstants.NOTICE);
462             oleDeliverRequestBo.setNoticeType(notice);
463             oleDeliverRequestBo.setRequestExpiryDate(d);
464             StringBuffer failures = new StringBuffer();
465             if (errorMessage != null && errorMessage.size() > 0) {
466                 int i = 1;
467                 for (String errMsg : errorMessage) {
468                     failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
469                 }
470             }
471             if (!failures.toString().isEmpty()) {
472                 oleDeliverRequestBo.setMessage(failures.toString());
473             }
474             else if(failures.toString().trim().isEmpty()){
475 
476             if(oleLoanDocument!=null && (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2"))){
477 
478                 Timestamp itemDueDate = null;
479                 if(ObjectUtils.isNotNull(oleLoanDocument)){
480                     itemDueDate = oleLoanDocument.getLoanDueDate();
481                 }
482                 Item oleItem = oleDeliverRequestBo.getOleItem();
483                 if(itemDueDate == null && recallDueDate!=null){
484                     // oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
485                     oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
486                     oleLoanDocument.setLoanDueDate(recallDueDate);
487                     oleDeliverRequestBo.setRecallDueDate(recallDueDate);
488                     oleItem.setDueDateTime(recallDueDate.toString());
489                     getBusinessObjectService().save(oleLoanDocument);
490                     OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
491                             getLoanProcessor().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
492                     oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
493                     OLEDeliverNoticeHelperService oleDeliverNoticeHelperService =getOleDeliverNoticeHelperService();
494                     oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
495                     try{
496                         oleDeliverNoticeHelperService.generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
497                                 oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
498                                 oleLoanDocument.getBorrowerTypeCode(),itemType, oleDeliverRequestBo.getItemStatus(),
499                                 oleLoanDocument.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
500                                 oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
501                                 oleDeliverRequestBo.getShelvingLocation(), oleDeliverRequestBo.getItemCollection(), oleDeliverRequestBo.getItemLibrary(),
502                                 oleDeliverRequestBo.getItemCampus(), oleDeliverRequestBo.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
503                     }catch(Exception e){
504                         LOG.info("Exception occured while updating the date in notice table");
505                         LOG.error(e,e);
506                     }
507                     oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate,"MM/dd/yyyy HH:mm:ss"));
508                     try{
509                         service.updateItem(oleItem);
510                     }catch(Exception e){
511                         if(LOG.isInfoEnabled()){
512                             LOG.info("Exception occured while updating the item . " +e.getMessage() );
513                         }
514                         LOG.error(e,e);
515                     }
516                 }
517                 if (recallDueDate != null && itemDueDate!=null ) {
518                     if(itemDueDate.compareTo(recallDueDate) > 0){
519                         oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
520                         oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
521                         oleLoanDocument.setLoanDueDate(recallDueDate);
522                         oleDeliverRequestBo.setRecallDueDate(recallDueDate);
523                         getBusinessObjectService().save(oleLoanDocument);
524                         OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
525                                 getLoanProcessor().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
526                         oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
527                         OLEDeliverNoticeHelperService oleDeliverNoticeHelperService =getOleDeliverNoticeHelperService();
528                         oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
529                         try{
530                             oleDeliverNoticeHelperService.generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
531                                     oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
532                                     oleLoanDocument.getBorrowerTypeCode(),itemType, oleDeliverRequestBo.getItemStatus(),
533                                     oleLoanDocument.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
534                                     oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
535                                     oleDeliverRequestBo.getShelvingLocation(), oleDeliverRequestBo.getItemCollection(), oleDeliverRequestBo.getItemLibrary(),
536                                     oleDeliverRequestBo.getItemCampus(), oleDeliverRequestBo.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
537                         }catch(Exception e){
538                             LOG.info("Exception occured while updating the date in notice table");
539                             LOG.error(e,e);
540                         }
541                         oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate,"MM/dd/yyyy HH:mm:ss"));
542                         try{
543                             service.updateItem(oleItem);
544                         }catch(Exception e){
545                             if(LOG.isInfoEnabled()){
546                                 LOG.info("Exception occured while updating the item . " +e.getMessage() );
547                             }
548                             LOG.error(e,e);
549                         }
550                     }else{
551                         oleDeliverRequestBo.setNewDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
552                         oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
553                     }
554                 }
555             }
556 
557             }
558             dataCarrierService.addData(OLEConstants.ERROR_ACTION, null);
559 
560         }
561         return engineResult;
562     }
563 
564     /**
565      * This method returns ElementValue using docContent and xpathExpression..
566      *
567      * @param docContent
568      * @param xpathExpression
569      * @return value
570      */
571     private String getElementValue(String docContent, String xpathExpression) {
572         try {
573             Document document = XmlHelper.trimXml(new ByteArrayInputStream(docContent.getBytes()));
574 
575             XPath xpath = XPathHelper.newXPath();
576             String value = (String) xpath.evaluate(xpathExpression, document, XPathConstants.STRING);
577 
578             return value;
579 
580         } catch (Exception e) {
581             LOG.error("Exception while getting element value", e);
582             throw new RiceRuntimeException();
583         }
584     }
585 
586     /**
587      * This method returns SelectionContext using contextName.
588      *
589      * @param contextName
590      * @return Map
591      */
592     protected Map<String, String> getSelectionContext(String contextName) {
593         Map<String, String> selector = new HashMap<String, String>();
594         selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
595         selector.put(NAME_SELECTOR, contextName);
596         return selector;
597     }
598 
599     /**
600      * This method returns AgendaContext using agendaName..
601      *
602      * @param agendaName
603      * @return Map
604      */
605     protected Map<String, String> getAgendaContext(String agendaName) {
606         Map<String, String> selector = new HashMap<String, String>();
607         selector.put(NAME_SELECTOR, agendaName);
608         return selector;
609     }
610 
611     @RequestMapping(params = "methodToCall=refreshPageView")
612     public ModelAndView refreshPageView(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
613                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
614         super.refresh(form, result, request, response);
615         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
616         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) maintenanceForm.getDocument();
617         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) maintenanceDocument.getDocumentDataObject();
618 
619         oleDeliverRequestBo.setRequestTypeId(null);
620         if (oleDeliverRequestBo.getRequestTypeId() == null && oleDeliverRequestBo.getRequestTypeCode() != null && !oleDeliverRequestBo.getRequestTypeCode().trim().isEmpty()) {
621             Map<String, String> requestTypeMap = new HashMap<String, String>();
622             requestTypeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_CD, oleDeliverRequestBo.getRequestTypeCode());
623             List<OleDeliverRequestType> oleDeliverRequestTypeList = (List<OleDeliverRequestType>) getBusinessObjectService().findMatching(OleDeliverRequestType.class, requestTypeMap);
624             if (oleDeliverRequestTypeList != null && oleDeliverRequestTypeList.size() == 0) {
625                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OleDeliverRequest.INVALID_REQUEST_TYPE);
626             } else if (oleDeliverRequestTypeList != null && oleDeliverRequestTypeList.size() > 0) {
627                 oleDeliverRequestBo.setRequestTypeId(oleDeliverRequestTypeList.get(0).getRequestTypeId());
628             }
629         }
630         return getUIFModelAndView(form);
631     }
632 
633 
634     @RequestMapping(params = "methodToCall=searchItem")
635     public ModelAndView searchItem(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
636                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
637 
638         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
639         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) maintenanceForm.getDocument();
640         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) maintenanceDocument.getDocumentDataObject();
641         if (!docstoreUtil.isItemAvailableInDocStore(oleDeliverRequestBo)) {
642             oleDeliverRequestBo.setTitle(null);
643             oleDeliverRequestBo.setAuthor(null);
644             oleDeliverRequestBo.setCallNumber(null);
645             oleDeliverRequestBo.setCopyNumber(null);
646             oleDeliverRequestBo.setShelvingLocation(null);
647             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.OlePatron.INV_ITEM_BAR);
648         }
649         return getUIFModelAndView(form);
650     }
651 
652 
653     @RequestMapping(params = "methodToCall=searchPatron")
654     public ModelAndView searchPatron(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
655                                      HttpServletRequest request, HttpServletResponse response) throws Exception {
656         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
657         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) maintenanceForm.getDocument();
658         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) maintenanceDocument.getDocumentDataObject();
659         service.processPatron(oleDeliverRequestBo);
660         if (oleDeliverRequestBo.getBorrowerName() == null || (oleDeliverRequestBo.getBorrowerName() != null && oleDeliverRequestBo.getBorrowerName().isEmpty()))
661             GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.BORROWER_ID, OLEConstants.OleDeliverRequest.INVALID_PATRON);
662         return getUIFModelAndView(form);
663     }
664 
665 
666     @RequestMapping(params = "methodToCall=printPdf")
667     public void printPdf(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
668                          HttpServletRequest request, HttpServletResponse response) throws Exception {
669         MaintenanceDocumentForm maintenanceForm = (MaintenanceDocumentForm) form;
670         MaintenanceDocument maintenanceDocument = (MaintenanceDocument) maintenanceForm.getDocument();
671         OleDeliverRequestBo oleDeliverRequestBo = (OleDeliverRequestBo) maintenanceDocument.getDocumentDataObject();
672         if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR) && oleDeliverRequestBo.getRequestTypeId().equals("8")) {
673             int errorCount = GlobalVariables.getMessageMap().getErrorCount();
674             if (errorCount == 0) {
675                 OleDeliverBatchServiceImpl oleDeliverBatchServiceimpl = new OleDeliverBatchServiceImpl();
676                 oleDeliverBatchServiceimpl.createPdfForIntransitRequest(oleDeliverRequestBo, response);
677             }
678         }
679     }
680 
681 
682 }
683 
684