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