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