View Javadoc
1   package org.kuali.ole.deliver.service;
2   
3   
4   import com.itextpdf.text.Document;
5   import org.apache.commons.collections.CollectionUtils;
6   import org.apache.commons.lang.StringUtils;
7   import org.apache.log4j.Logger;
8   import org.kuali.asr.ASRConstants;
9   import org.kuali.asr.service.ASRHelperServiceImpl;
10  import org.kuali.ole.DataCarrierService;
11  import org.kuali.ole.OLEConstants;
12  import org.kuali.ole.OLEParameterConstants;
13  import org.kuali.ole.deliver.batch.OleDeliverBatchServiceImpl;
14  import org.kuali.ole.deliver.batch.OleMailer;
15  import org.kuali.ole.deliver.batch.OleNoticeBo;
16  import org.kuali.ole.deliver.batch.OleSms;
17  import org.kuali.ole.deliver.bo.*;
18  import org.kuali.ole.deliver.processor.LoanProcessor;
19  import org.kuali.ole.deliver.service.impl.OLEDeliverNoticeHelperServiceImpl;
20  import org.kuali.ole.describe.bo.OleInstanceItemType;
21  import org.kuali.ole.describe.bo.OleLocation;
22  import org.kuali.ole.describe.bo.OleLocationLevel;
23  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
24  import org.kuali.ole.docstore.common.document.*;
25  import org.kuali.ole.docstore.common.document.HoldingsTree;
26  import org.kuali.ole.docstore.common.document.content.enums.DocType;
27  import org.kuali.ole.docstore.common.document.content.instance.Item;
28  import org.kuali.ole.docstore.common.document.content.instance.*;
29  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
30  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
31  import org.kuali.ole.docstore.common.search.*;
32  import org.kuali.ole.docstore.engine.client.DocstoreLocalClient;
33  import org.kuali.ole.ingest.pojo.MatchBo;
34  import org.kuali.ole.ncip.bo.OLEPlaceRequest;
35  import org.kuali.ole.ncip.converter.OLEPlaceRequestConverter;
36  import org.kuali.ole.service.OleCirculationPolicyService;
37  import org.kuali.ole.service.OleCirculationPolicyServiceImpl;
38  import org.kuali.ole.service.OlePatronHelperService;
39  import org.kuali.ole.service.OlePatronHelperServiceImpl;
40  import org.kuali.ole.sys.context.SpringContext;
41  import org.kuali.ole.util.DocstoreUtil;
42  import org.kuali.rice.core.api.config.property.ConfigContext;
43  import org.kuali.rice.core.api.datetime.DateTimeService;
44  import org.kuali.rice.core.api.mail.EmailBody;
45  import org.kuali.rice.core.api.mail.EmailFrom;
46  import org.kuali.rice.core.api.mail.EmailSubject;
47  import org.kuali.rice.core.api.mail.EmailTo;
48  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
49  import org.kuali.rice.coreservice.api.CoreServiceApiServiceLocator;
50  import org.kuali.rice.coreservice.api.parameter.Parameter;
51  import org.kuali.rice.coreservice.api.parameter.ParameterKey;
52  import org.kuali.rice.coreservice.impl.parameter.ParameterBo;
53  import org.kuali.rice.kew.api.exception.WorkflowException;
54  import org.kuali.rice.kim.api.identity.Person;
55  import org.kuali.rice.kim.api.identity.PersonService;
56  import org.kuali.rice.kim.api.permission.PermissionService;
57  import org.kuali.rice.kim.api.role.RoleService;
58  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
59  import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
60  import org.kuali.rice.krad.UserSession;
61  import org.kuali.rice.krad.dao.impl.PersistenceDaoOjb;
62  import org.kuali.rice.krad.maintenance.MaintenanceDocument;
63  import org.kuali.rice.krad.service.BusinessObjectService;
64  import org.kuali.rice.krad.service.DocumentService;
65  import org.kuali.rice.krad.service.KRADServiceLocator;
66  import org.kuali.rice.krad.util.GlobalVariables;
67  import org.kuali.rice.krad.util.KRADConstants;
68  import org.kuali.rice.krad.util.ObjectUtils;
69  import org.kuali.rice.krms.api.KrmsApiServiceLocator;
70  import org.kuali.rice.krms.api.engine.*;
71  import org.kuali.rice.krms.api.repository.agenda.AgendaDefinition;
72  import org.kuali.rice.krms.api.repository.context.ContextDefinition;
73  import org.kuali.rice.krms.impl.repository.KrmsRepositoryServiceLocator;
74  
75  import java.io.OutputStream;
76  import java.sql.*;
77  import java.text.DateFormat;
78  import java.text.SimpleDateFormat;
79  import java.util.*;
80  import java.util.Date;
81  import java.util.concurrent.ExecutorService;
82  import java.util.concurrent.Executors;
83  
84  /**
85   * Created with IntelliJ IDEA.
86   * User: ?
87   * Date: 10/24/12
88   * Time: 10:27 AM
89   * To change this template use File | Settings | File Templates.
90   */
91  public class OleDeliverRequestDocumentHelperServiceImpl {
92      private static final Logger LOG = Logger.getLogger(OleDeliverRequestDocumentHelperServiceImpl.class);
93      private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
94      private static final String NAME_SELECTOR = "name";
95      private final static String RULE_EVALUATED = "Rule Evaluated";
96      private final static String ROUTED_EXTERNAL = "Routed External";
97      private BusinessObjectService businessObjectService;
98      private int queuePosition = 0;
99      private LoanProcessor loanProcessor;
100     private DocstoreUtil docstoreUtil;
101     private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
102     private OLEDeliverNoticeHelperService oleDeliverNoticeHelperService;
103     private DocumentService documentService;
104     private PersonService personService = KimApiServiceLocator.getPersonService();
105     private OleCirculationPolicyService oleCirculationPolicyService;
106     private DateTimeService dateTimeService;
107     private List<OleLoanDocument> laonDocumentsFromLaondId;
108     private OlePatronHelperServiceImpl olePatronHelperService;
109     private CircDeskLocationResolver circDeskLocationResolver;
110 
111     public DateTimeService getDateTimeService() {
112         return (DateTimeService) SpringContext.getService("dateTimeService");
113     }
114 
115     private PermissionService getPermissionService() {
116         PermissionService service = KimApiServiceLocator.getPermissionService();
117         return service;
118     }
119 
120     private CircDeskLocationResolver getCircDeskLocationResolver() {
121         if (circDeskLocationResolver == null) {
122             circDeskLocationResolver = new CircDeskLocationResolver();
123         }
124         return circDeskLocationResolver;
125     }
126 
127     public void setCircDeskLocationResolver(CircDeskLocationResolver circDeskLocationResolver) {
128         this.circDeskLocationResolver = circDeskLocationResolver;
129     }
130 
131     private DocstoreClientLocator docstoreClientLocator;
132 
133     public DocstoreClientLocator getDocstoreClientLocator() {
134 
135         if (docstoreClientLocator == null) {
136             docstoreClientLocator = (DocstoreClientLocator)SpringContext.getService("docstoreClientLocator");
137 
138         }
139         return docstoreClientLocator;
140     }
141 
142     public OlePatronHelperService getOlePatronHelperService() {
143         if (olePatronHelperService == null)
144             olePatronHelperService = new OlePatronHelperServiceImpl();
145         return olePatronHelperService;
146     }
147 
148     public void setOlePatronHelperService(OlePatronHelperServiceImpl olePatronHelperService) {
149         this.olePatronHelperService = olePatronHelperService;
150     }
151 
152     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
153         this.businessObjectService = businessObjectService;
154     }
155 
156 
157     public void setLoanProcessor(LoanProcessor loanProcessor) {
158         this.loanProcessor = loanProcessor;
159     }
160 
161     public void setDocstoreUtil(DocstoreUtil docstoreUtil) {
162         this.docstoreUtil = docstoreUtil;
163     }
164 
165     public void setDocstoreClientLocator(DocstoreClientLocator docstoreClientLocator) {
166         this.docstoreClientLocator = docstoreClientLocator;
167     }
168 
169     public DocstoreUtil getDocstoreUtil() {
170         if (docstoreUtil == null) {
171             docstoreUtil = (DocstoreUtil)SpringContext.getService("docstoreUtil");
172         }
173         return docstoreUtil;
174     }
175 
176 
177     /**
178      * Gets the businessObjectService attribute.
179      *
180      * @return Returns the businessObjectService
181      */
182     private BusinessObjectService getBusinessObjectService() {
183         if (null == businessObjectService) {
184             businessObjectService = KRADServiceLocator.getBusinessObjectService();
185         }
186         return businessObjectService;
187     }
188 
189     public LoanProcessor getLoanProcessor() {
190         if (loanProcessor == null) {
191             loanProcessor = (LoanProcessor)SpringContext.getService("loanProcessor");
192         }
193         return loanProcessor;
194     }
195 
196     public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
197         if (itemOlemlRecordProcessor == null) {
198             itemOlemlRecordProcessor = (ItemOlemlRecordProcessor) SpringContext.getService("itemOlemlRecordProcessor");
199         }
200         return itemOlemlRecordProcessor;
201     }
202 
203     public OLEDeliverNoticeHelperService getOleDeliverNoticeHelperService() {
204         if (oleDeliverNoticeHelperService == null) {
205             oleDeliverNoticeHelperService = (OLEDeliverNoticeHelperService)SpringContext.getService("oleDeliverNoticeHelperService");
206         }
207         return oleDeliverNoticeHelperService;
208     }
209 
210     public void setOleDeliverNoticeHelperService(OLEDeliverNoticeHelperService oleDeliverNoticeHelperService) {
211         this.oleDeliverNoticeHelperService = oleDeliverNoticeHelperService;
212     }
213 
214 
215     /**
216      * Gets the oleCirculationPolicyService attribute.
217      *
218      * @return Returns the oleCirculationPolicyService
219      */
220     public OleCirculationPolicyService getOleCirculationPolicyService() {
221         if (null == oleCirculationPolicyService) {
222             oleCirculationPolicyService = (OleCirculationPolicyService)SpringContext.getService("oleCirculationPolicyService");
223         }
224         return oleCirculationPolicyService;
225     }
226 
227     /**
228      * This method is used to change the request type based on selection of  pick up  location
229      *
230      * @param oleDeliverRequestBo
231      * @return oleDeliverRequestBo
232      */
233     public OleDeliverRequestBo processRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
234         if (LOG.isDebugEnabled()) {
235             LOG.debug("Inside processRequestType for the Request id :" + oleDeliverRequestBo.getRequestId());
236         }
237         oleDeliverRequestBo = processPatron(oleDeliverRequestBo);
238         oleDeliverRequestBo = processItem(oleDeliverRequestBo);
239         oleDeliverRequestBo = processRequestTypeByPickUpLocation(oleDeliverRequestBo);
240         return oleDeliverRequestBo;
241     }
242 
243     private OleDeliverRequestBo processRequestTypeByPickUpLocation(OleDeliverRequestBo oleDeliverRequestBo) {
244         if (oleDeliverRequestBo.getRequestTypeId() != null) {
245             if (oleDeliverRequestBo.getRequestTypeId().equals("3") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
246                 oleDeliverRequestBo.setRequestTypeId("4");
247             } else if (oleDeliverRequestBo.getRequestTypeId().equals("5") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
248                 oleDeliverRequestBo.setRequestTypeId("6");
249             } else if (oleDeliverRequestBo.getRequestTypeId().equals("1") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
250                 oleDeliverRequestBo.setRequestTypeId("2");
251             }
252         }
253         return oleDeliverRequestBo;
254     }
255 
256 
257     /**
258      * This is to create a new patron object if the user enters the operator Id manually
259      *
260      * @param oleDeliverRequestBo
261      * @return deliver
262      */
263     public OleDeliverRequestBo processPatron(OleDeliverRequestBo oleDeliverRequestBo) {
264         LOG.debug("Inside processPatron");
265         OleDeliverRequestBo deliver = oleDeliverRequestBo;
266 
267         if (oleDeliverRequestBo.getBorrowerBarcode() != null || oleDeliverRequestBo.getProxyBorrowerBarcode() != null) {
268             Map<String, String> patronMap = new HashMap<String, String>();
269             patronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getBorrowerBarcode());
270             List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
271             if (olePatronDocumentList != null && olePatronDocumentList.size() > 0) {
272                 deliver.setOlePatron(olePatronDocumentList.get(0));
273                 deliver.setBorrowerName(olePatronDocumentList.get(0).getPatronName());
274                 deliver.setBorrowerId(olePatronDocumentList.get(0).getOlePatronId());
275             } else if (olePatronDocumentList != null && olePatronDocumentList.size() == 0) {
276                 deliver.setBorrowerId(null);
277                 deliver.setFirstName(null);
278                 deliver.setLastName(null);
279                 deliver.setOlePatron(null);
280                 deliver.setBorrowerName(null);
281                 deliver.setBorrowerBarcode(null);
282             }
283             if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
284                 Map<String, String> proxyPatronMap = new HashMap<String, String>();
285                 proxyPatronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getProxyBorrowerBarcode());
286                 List<OlePatronDocument> oleProxyPatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, proxyPatronMap);
287                 if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() > 0) {
288                     deliver.setOleProxyPatron(oleProxyPatronDocumentList.get(0));
289                     deliver.setProxyBorrowerName(oleProxyPatronDocumentList.get(0).getPatronName());
290                     deliver.setProxyBorrowerId(oleProxyPatronDocumentList.get(0).getOlePatronId());
291                 } else if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() == 0) {
292                     deliver.setProxyBorrowerId(null);
293                     deliver.setProxyBorrowerName(null);
294                     deliver.setOleProxyPatron(null);
295                 }
296             }
297 
298         }
299 
300         return deliver;
301     }
302 
303     public boolean processOperator(String principalId) {
304         /*if (getPermissionService().hasPermission(oleDeliverRequestBo.getOperatorCreateId(), OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN)) {
305             return true;
306         }*/
307         // Modified as per comments in Jira OLE-4901
308         boolean isOperator = true;
309         Collection<String> roles = getRoleService().getRoleMemberPrincipalIds(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR, null);
310         if (roles != null) {
311             isOperator = roles.contains(principalId);
312         }
313         return isOperator;
314     }
315 
316     /**
317      * This is to check whether the pick up location is selected for the hold type of Request
318      *
319      * @param oleDeliverRequestBo
320      * @return validRequest
321      */
322     public boolean validateRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
323         LOG.debug("Inside validateRequestType");
324         boolean validRequest = true;
325         if ((oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) && (oleDeliverRequestBo.getPickUpLocationId() == null) || (oleDeliverRequestBo.getPickUpLocationId() != null && oleDeliverRequestBo.getPickUpLocationId().isEmpty())) {
326             validRequest = false;
327         }
328         return validRequest;
329     }
330 
331 
332     /**
333      * This is to check whether the patron is having delivery privilege or not
334      *
335      * @param oleDeliverRequestBo
336      * @return hasDeliveryPrivilege
337      */
338     public boolean validateDeliveryPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
339         LOG.debug("Inside validateDeliveryPrivilege");
340         boolean hasDeliveryPrivilege = true;
341         if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("3") || oleDeliverRequestBo.getRequestTypeId().equals("5")) {
342             if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege()) {
343                 hasDeliveryPrivilege = false;
344             }
345         } else if (oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
346             if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege() && oleDeliverRequestBo.getPickUpLocationId() == null) {
347                 hasDeliveryPrivilege = false;
348             }
349         }
350         return hasDeliveryPrivilege;
351     }
352 
353 
354     /**
355      * This is to check whether the patron is having paging privilege or not
356      *
357      * @param oleDeliverRequestBo
358      * @return hasPagePrivilege
359      */
360     public boolean validatePagingPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
361         LOG.debug("Inside validatePagingPrivilege");
362         boolean hasPagePrivilege = true;
363         if (oleDeliverRequestBo.getRequestTypeId().equals("5") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
364             if (!oleDeliverRequestBo.getOlePatron().isPagingPrivilege()) {
365                 hasPagePrivilege = false;
366             }
367         }
368         return hasPagePrivilege;
369     }
370 
371 
372     /**
373      * This for setting the null values for the unselected requester
374      *
375      * @param oleDeliverRequestBo
376      * @return oleDeliverRequestBo
377      */
378     public OleDeliverRequestBo processRequester(OleDeliverRequestBo oleDeliverRequestBo) {
379         LOG.debug("Inside processRequester");
380         if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PATRON)) {
381             oleDeliverRequestBo.setProxyBorrowerId(null);
382             oleDeliverRequestBo.setOleProxyPatron(null);
383             oleDeliverRequestBo.setOperatorCreateId(null);
384             oleDeliverRequestBo.setOperatorCreator(null);
385         } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
386             oleDeliverRequestBo.setOperatorCreateId(null);
387             oleDeliverRequestBo.setOperatorCreator(null);
388         } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR)) {
389             oleDeliverRequestBo.setProxyBorrowerId(null);
390             oleDeliverRequestBo.setOleProxyPatron(null);
391         }
392         return oleDeliverRequestBo;
393     }
394 
395 
396     /**
397      * This is to check whether the login patron is the proxy patron for the real patron
398      *
399      * @param oleDeliverRequestBo
400      * @return validProxy
401      */
402     public boolean isValidProxyPatron(OleDeliverRequestBo oleDeliverRequestBo) {
403         LOG.debug("Inside isValidProxyPatron");
404         boolean validProxy = true;
405         Map<String, String> proxyMap = new HashMap<String, String>();
406         proxyMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
407         proxyMap.put(OLEConstants.OleDeliverRequest.PROXY_PATRON_ID, oleDeliverRequestBo.getProxyBorrowerId());
408         if (oleDeliverRequestBo.getProxyBorrowerId() != null && !oleDeliverRequestBo.getProxyBorrowerId().isEmpty()) {
409             List<OleProxyPatronDocument> proxyPatronDocuments = (List<OleProxyPatronDocument>) getBusinessObjectService().findMatching(OleProxyPatronDocument.class, proxyMap);
410             if (proxyPatronDocuments.size() == 0) {
411                 validProxy = false;
412             }
413         }
414         return validProxy;
415     }
416 
417 
418     /**
419      * This is to check whether the request is already raised by the patron for this item
420      *
421      * @param oleDeliverRequestBo
422      * @return alreadyExist
423      */
424     public boolean isRequestAlreadyRaisedByPatron(OleDeliverRequestBo oleDeliverRequestBo) {
425         LOG.debug("Inside isRequestAlreadyRaised");
426         boolean alreadyExist = false;
427         Map<String, String> requestMap = new HashMap<String, String>();
428         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, oleDeliverRequestBo.getBorrowerId());
429         requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
430         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
431         if (deliverRequestBos != null && deliverRequestBos.size() > 0) {
432             alreadyExist = true;
433         }
434         return alreadyExist;
435     }
436 
437 
438     /**
439      * This is to check whether the requested item is currently in loan to the requesting patron
440      *
441      * @param oleDeliverRequestBo
442      * @return alreadyLoaned
443      */
444     public boolean isAlreadyLoaned(OleDeliverRequestBo oleDeliverRequestBo) {
445         LOG.debug("Inside isAlreadyLoaned");
446         boolean alreadyLoaned = false;
447         Map<String, String> loanMap = new HashMap<String, String>();
448         loanMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, oleDeliverRequestBo.getBorrowerId());
449         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
450         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
451         if (loanDocuments != null && loanDocuments.size() > 0) {
452             alreadyLoaned = true;
453         }
454         return alreadyLoaned;
455     }
456 
457 
458     /**
459      * This is to check whether the item is available in the desk or not
460      *
461      * @param oleDeliverRequestBo
462      * @return itemAvailable
463      */
464     public boolean isItemAvailable(OleDeliverRequestBo oleDeliverRequestBo) {
465         LOG.debug("Inside isItemAvailable");
466         boolean itemAvailable = true;
467 
468         String itemStatuslist = null;
469         String requestTypeCode = oleDeliverRequestBo.getRequestTypeCode();
470         if (requestTypeCode.equals("Recall/Delivery Request")) {
471             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.RECALL_DELIVERY_ITEM_STATUS);
472         } else if (requestTypeCode.equals("Recall/Hold Request")) {
473             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.RECALL_HOLD_ITEM_STATUS);
474         } else if (requestTypeCode.equals("Hold/Delivery Request")) {
475             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.HOLD_DELIVERY_ITEM_STATUS);
476         } else if (requestTypeCode.equals("Hold/Hold Request")) {
477             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.HOLD_HOLD_ITEM_STATUS);
478         } else if (requestTypeCode.equals("Page/Delivery Request")) {
479             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.PAGE_DELIVERY_ITEM_STATUS);
480         } else if (requestTypeCode.equals("Page/Hold Request")) {
481             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.PAGE_HOLD_ITEM_STATUS);
482         } else if (requestTypeCode.equals("Copy Request")) {
483             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.COPY_REQUEST_ITEM_STATUS);
484         } else if (requestTypeCode.equals("ASR Request")) {
485             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.ASR_REQUEST_ITEM_STATUS);
486         } else {
487             GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.REQUEST_ID_INVALID);
488         }
489         String[] str = itemStatuslist.split(";");
490         for (String itemStatus : str) {
491             if ((itemStatus != null) && (!itemStatus.isEmpty()) && (itemStatus.equals(oleDeliverRequestBo.getItemStatus()))) {
492                 itemAvailable = false;
493             }
494         }
495         return itemAvailable;
496     }
497 
498 
499     /**
500      * This is to check whether the item is available in the desk or not
501      *
502      * @param oleDeliverRequestBo
503      * @return itemAvailable
504      */
505     public boolean isItemAvailableForLoan(OleDeliverRequestBo oleDeliverRequestBo) {
506         LOG.debug("Inside isItemAvailable");
507         boolean itemAvailable = false;
508         Map<String, String> loanItemMap = new HashMap<String, String>();
509         loanItemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
510         List<OleLoanDocument> loanItemDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanItemMap);
511         if (loanItemDocuments.size() == 0) {
512             itemAvailable = true;
513         }
514         return itemAvailable;
515     }
516 
517 
518     /**
519      * This is to check whether the item is eligible to loan
520      *
521      * @param oleDeliverRequestBo
522      * @return itemEligible
523      */
524     public boolean isItemEligible(OleDeliverRequestBo oleDeliverRequestBo) {
525         LOG.debug("Inside isItemEligible");
526         boolean itemEligible = true;
527         Map<String, String> statusMap = new HashMap<String, String>();
528         statusMap.put(OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT, OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT);
529         statusMap.put(OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE, OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE);
530         statusMap.put(OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN, OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN);
531 
532         if (statusMap.containsKey(oleDeliverRequestBo.getItemStatus())) {
533             itemEligible = false;
534         }
535         return itemEligible;
536     }
537 
538     /**
539      * This is to check whether the patron record is alive or expired
540      *
541      * @param oleDeliverRequestBo
542      * @return expired
543      */
544     public String patronRecordExpired(OleDeliverRequestBo oleDeliverRequestBo) {
545         LOG.debug("Inside patronRecordExpired");
546         String expired = null;
547 
548         OlePatronDocument olePatronDocument = oleDeliverRequestBo.getOlePatron();
549         if (olePatronDocument == null) {
550             Map<String, String> patronMap = new HashMap<String, String>();
551             patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
552             List<OlePatronDocument> olePatronDocuments = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
553             if (olePatronDocuments != null && olePatronDocuments.size() > 0) {
554                 olePatronDocument = olePatronDocuments.get(0);
555             }
556         }
557         if (olePatronDocument != null) {
558             SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
559             Date expirationDate = olePatronDocument.getExpirationDate();
560             Date activationDate = olePatronDocument.getActivationDate();
561             if ((fmt.format(activationDate)).compareTo(fmt.format(new Date(System.currentTimeMillis()))) <= 0) {
562                 if (expirationDate != null) {
563                     if ((fmt.format(expirationDate)).compareTo(fmt.format(new Date(System.currentTimeMillis()))) < 0) {
564                         expired = OLEConstants.OleDeliverRequest.PATRON_RECORD_EXPIRE;
565                     }
566                 }
567             } else {
568                 expired = OLEConstants.OleDeliverRequest.PATRON_RECORD_FUTURE;
569             }
570         }
571         return expired;
572     }
573 
574 
575     /**
576      * This is for retrieving the request raised by  the patron
577      *
578      * @param olePatronId
579      * @return deliverRequestBos
580      */
581     public List<OleDeliverRequestBo> getRequestedItems(String olePatronId) {
582         LOG.debug("Inside getRequestedItems");
583         Map<String, String> requestMap = new HashMap<String, String>();
584         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, olePatronId);
585         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
586         for (int i = 0; i < deliverRequestBos.size(); i++) {
587             processItem(deliverRequestBos.get(i));
588         }
589         return deliverRequestBos;
590 
591     }
592 
593 
594     /**
595      * This is to check the  duplicate in the queue Position while re -ordering
596      *
597      * @param itemList
598      * @return exist
599      */
600     public String validateQueuePosition(List<OleDeliverRequestBo> itemList) {
601         LOG.debug("Inside validateQueuePosition");
602         String message = OLEConstants.OleDeliverRequest.REORDER_SUCCESS;
603         List<Integer> queuePositionList = new ArrayList<Integer>();
604         if (itemList.get(0).getBorrowerQueuePosition() < 1) {
605             return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
606         }
607         queuePositionList.add(itemList.get(0).getBorrowerQueuePosition());
608 
609         for (int i = 1; i < itemList.size(); i++) {
610             for (int j = 0; j < queuePositionList.size(); j++) {
611                 if (itemList.get(i).getBorrowerQueuePosition() != null) {
612                     if ((itemList.get(i).getBorrowerQueuePosition() >= 1) && (itemList.get(i).getBorrowerQueuePosition() == queuePositionList.get(j))) {
613                         return OLEConstants.OleDeliverRequest.QUEUE_DUPLICATE;
614                     } else if ((itemList.get(i).getBorrowerQueuePosition() <= 0)) {
615                         return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
616                     }
617                 }
618             }
619             queuePositionList.add(itemList.get(i).getBorrowerQueuePosition());
620         }
621         return message;
622     }
623 
624     //
625 
626     /**
627      * This is to check whether any request raised for the item
628      *
629      * @param oleDeliverRequestBo
630      * @return exist
631      */
632     public boolean isRequestRaised(OleDeliverRequestBo oleDeliverRequestBo) {
633         LOG.debug("Inside isRequestRaised");
634         boolean exist = false;
635         Map<String, String> requestMap = new HashMap<String, String>();
636         requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
637         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
638         if (deliverRequestBos.size() > 0) {
639             exist = true;
640         }
641         return exist;
642     }
643 
644 
645     /**
646      * This method is used to cancel the request document using ASR/NCIP.
647      *
648      * @param oleDeliverRequestBo
649      */
650     public void cancelDocument(OleDeliverRequestBo oleDeliverRequestBo) {
651         String operatorId = GlobalVariables.getUserSession().getLoggedInUserPrincipalName();
652         try {
653             List<OleNoticeBo> oleNoticeBos = cancelRequestForItem(oleDeliverRequestBo.getItemUuid(), oleDeliverRequestBo.getBorrowerId());
654             ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
655             createRequestHistoryRecord(oleDeliverRequestBo.getRequestId(), operatorId, oleDeliverRequestBo.getLoanTransactionRecordNumber(), ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.REQUEST_CANCELLED));
656             LOG.debug("Inside cancelDocument");
657             Map<String, String> itemMap = new HashMap<String, String>();
658             itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
659             Map<String, String> requestMap = new HashMap<String, String>();
660             requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, oleDeliverRequestBo.getRequestId());
661             getBusinessObjectService().deleteMatching(OleDeliverRequestBo.class, requestMap);
662             List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
663             getBusinessObjectService().delete(oleDeliverRequestDocumentsList);
664             int queuePosition = 1;
665             for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
666                 oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
667                 queuePosition = queuePosition + 1;
668             }
669             getBusinessObjectService().save(oleDeliverRequestDocumentsList);
670             asrHelperService.deleteASRTypeRequest(oleDeliverRequestBo.getRequestId());
671             sendCancelNotice(oleNoticeBos);
672         } catch (Exception e) {
673             LOG.error("Cancellation of Request" + e.getMessage());
674         }
675     }
676 
677     /**
678      * Build the cancellation notice template.
679      *
680      * @param itemUuid
681      * @param patronId
682      * @return
683      * @throws Exception
684      */
685     public List<OleNoticeBo> cancelRequestForItem(String itemUuid, String patronId) throws Exception {
686         Map<String, String> requestMap = new HashMap<String, String>();
687         requestMap.put(OLEConstants.ITEM_UUID, itemUuid);
688         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, patronId);
689         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
690         List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
691         if (org.apache.commons.collections.CollectionUtils.isNotEmpty(oleDeliverRequestBoList)) {
692             OleDeliverRequestBo oleDeliverRequestBo = oleDeliverRequestBoList.get(0);
693             //cancelDocument(oleDeliverRequestBo);
694             OleItemSearch itemSearch = getDocstoreUtil().getOleItemSearchList(itemUuid);
695             EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
696 
697             OleNoticeBo oleNoticeBo = new OleNoticeBo();
698             oleNoticeBo.setNoticeName(OLEConstants.CANCELLATION_NOTICE);
699             oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
700             oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
701             oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
702             oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
703             oleNoticeBo.setAuthor(itemSearch.getAuthor() != null ? itemSearch.getAuthor() : "");
704             oleNoticeBo.setItemCallNumber(itemSearch.getCallNumber() != null ? itemSearch.getCallNumber() : "");
705             if (itemSearch.getShelvingLocation() != null && itemSearch.getShelvingLocation().toString().contains("/")) {
706                 String[] location = itemSearch.getShelvingLocation().split("/");
707                 if (location != null && location.length > 0)
708                     oleNoticeBo.setItemShelvingLocation(location[1] != null ? location[1] : "");
709             } else {
710                 oleNoticeBo.setItemShelvingLocation("");
711             }
712             oleNoticeBo.setItemId(itemSearch.getItemBarCode() != null ? itemSearch.getItemBarCode() : "");
713             oleNoticeBo.setTitle(itemSearch.getTitle() != null ? itemSearch.getTitle() : "");
714             oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
715             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
716                 oleNoticeBos.add(oleNoticeBo);
717             }
718         }
719         return oleNoticeBos;
720     }
721 
722 
723     /**
724      * send the email to respective patron.
725      *
726      * @param oleNoticeBos
727      * @throws Exception
728      */
729     public void sendCancelNotice(List<OleNoticeBo> oleNoticeBos) throws Exception {
730         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
731         for (OleNoticeBo oleNoticeBo : oleNoticeBos) {
732             List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
733             String content = list.toString();
734             content = content.replace('[', ' ');
735             content = content.replace(']', ' ');
736             if (!content.trim().equals("")) {
737                 OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
738                 String replyToEmail = getCircDeskLocationResolver().getReplyToEmail(oleNoticeBo.getItemShelvingLocation());
739                 if (replyToEmail != null) {
740                     oleMailer.sendEmail(new EmailFrom(replyToEmail), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.CANCELLATION_NOTICE), new EmailBody(content), true);
741                 } else {
742                     String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
743                     if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
744                         fromAddress = OLEConstants.KUALI_MAIL;
745                     }
746                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.CANCELLATION_NOTICE), new EmailBody(content), true);
747                 }
748             }
749         }
750     }
751 
752 
753     public void cancelPendingRequestForClaimsReturnedItem(String itemUuid) throws Exception {
754         Map<String, String> requestMap = new HashMap<String, String>();
755         requestMap.put(OLEConstants.ITEM_UUID, itemUuid);
756         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
757         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
758         for (OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBoList) {
759             cancelDocument(oleDeliverRequestBo);
760         }
761     }
762 
763     /**
764      * This method is to set the item values from docstore
765      *
766      * @param oleDeliverRequestBo
767      * @return oleDeliverRequestBo
768      */
769     public OleDeliverRequestBo processItem(OleDeliverRequestBo oleDeliverRequestBo) {
770         LOG.debug("Inside processItem");
771         OleItemSearch oleItemSearch = null;
772         if (oleDeliverRequestBo.getItemType() == null) {
773             // Map<String, String> itemMap = new HashMap<String, String>();
774             //itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
775             OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(oleDeliverRequestBo.getItemUuid());
776             try {
777                 //org.kuali.ole.docstore.common.document.Item item=getDocstoreClientLocator().getDocstoreClient().retrieveItem( oleDeliverRequestBo.getItemUuid());
778 
779 
780                 if (itemSearchList != null) {
781                     oleItemSearch = itemSearchList;
782                     oleDeliverRequestBo.setTitle(itemSearchList.getTitle());
783                     oleDeliverRequestBo.setAuthor(itemSearchList.getAuthor());
784                     oleDeliverRequestBo.setCallNumber(itemSearchList.getCallNumber());
785                     oleDeliverRequestBo.setItemType(itemSearchList.getItemType());
786                     oleDeliverRequestBo.setItemLocation(itemSearchList.getShelvingLocation());
787                     oleDeliverRequestBo.setShelvingLocation(itemSearchList.getShelvingLocation());
788                     oleDeliverRequestBo.setCopyNumber(itemSearchList.getCopyNumber());
789                     oleDeliverRequestBo.setItemStatus(itemSearchList.getItemStatus());
790                 }
791             } catch (Exception ex) {
792                 ex.printStackTrace();
793             }
794             try {
795                 String itemXml = getLoanProcessor().getItemXML(oleDeliverRequestBo.getItemUuid());
796                 Item oleItem = getLoanProcessor().getItemPojo(itemXml);
797                 if (oleItemSearch == null) {
798                     oleItemSearch = new OleItemSearch();
799                     oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
800                     if (oleItem.getItemStatus() != null) {
801                         oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
802                     }
803                     oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
804                     oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
805 
806                     if (oleItem.getItemStatus() != null) {
807                         oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
808                     }
809                     oleDeliverRequestBo.setShelvingLocation(oleItemSearch.getShelvingLocation());
810                 }
811                 // Map docStoreDetails = loanProcessor.getItemDetails(oleDeliverRequestBo.getItemId());
812                 if (oleDeliverRequestBo.getRequestTypeId().equals("8")) {
813                     oleDeliverRequestBo.setInTransitCheckInNote(oleItem.getCheckinNote());
814                 }
815             } catch (Exception e) {
816                 LOG.error(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC), e);  //To change body of catch statement use File | Settings | File Templates.
817             }
818         }
819         oleDeliverRequestBo.setOleItemSearch(oleItemSearch);
820         oleDeliverRequestBo = processItemType(oleDeliverRequestBo);
821         return oleDeliverRequestBo;
822     }
823 
824     /**
825      * This method is to set the item type name  based on the item type code
826      *
827      * @param oleDeliverRequestBo
828      * @return
829      */
830     public OleDeliverRequestBo processItemType(OleDeliverRequestBo oleDeliverRequestBo) {
831         LOG.debug("Inside process Item Type");
832         Map<String, String> itemMap = new HashMap<String, String>();
833         itemMap = new HashMap<String, String>();
834         itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, oleDeliverRequestBo.getItemType());
835         List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) getBusinessObjectService().findMatching(OleInstanceItemType.class, itemMap);
836         if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
837             OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
838             oleDeliverRequestBo.setItemTypeName(oleInstanceItemType.getInstanceItemTypeName());
839         }
840 
841         return oleDeliverRequestBo;
842     }
843 
844     /**
845      * This method is to retrieve the shelving location from item
846      *
847      * @param oleLocation
848      * @return locationLevelName
849      */
850     private String getShelvingLocation(Location oleLocation) {
851 
852         LOG.debug("Inside getShelvingLocation");
853         String locationLevelName = "";
854         if (oleLocation != null) {
855             LocationLevel locationLevel =
856                     oleLocation.getLocationLevel();
857             if (locationLevel != null) {
858                 while (locationLevel.getLocationLevel() != null && !locationLevel.getLevel().equalsIgnoreCase(OLEConstants.OleDeliverRequest.SHELVING)) {
859                     locationLevel = locationLevel.getLocationLevel();
860                 }
861                 locationLevelName = locationLevel.getName();
862             }
863         }
864         return locationLevelName;
865     }
866 
867 
868     /**
869      * This method is to check whether the selected  request can be raised for the item
870      *
871      * @param oleDeliverRequestBo
872      * @return canRaiseRequest
873      */
874     public boolean canRaiseRequest(OleDeliverRequestBo oleDeliverRequestBo) {
875         LOG.debug("Inside canRaiseRequest");
876         boolean canRaiseRequest = true;
877 
878         if (isItemAvailable(oleDeliverRequestBo)) {
879             canRaiseRequest = false;
880 
881 
882         }
883         return canRaiseRequest;
884     }
885 
886 
887     /**
888      * racle
889      * This method is to update the request id in the loan document
890      *
891      * @param oleDeliverRequestBo
892      */
893     public OleDeliverRequestBo updateLoanDocument(OleDeliverRequestBo oleDeliverRequestBo) {
894         LOG.debug("Inside updateLoanDocument");
895         Map<String, String> loanMap = new HashMap<String, String>();
896         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
897         List<OleLoanDocument> oleLoanDocumentList = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
898         if (oleLoanDocumentList != null && oleLoanDocumentList.size() > 0 && oleLoanDocumentList.get(0) != null && oleLoanDocumentList.get(0).getOleRequestId() == null) {
899             if (oleLoanDocumentList.get(0).getLoanId() != null) {
900                 oleLoanDocumentList.get(0).setOleRequestId(oleDeliverRequestBo.getRequestId());
901                 oleDeliverRequestBo.setLoanTransactionRecordNumber(oleLoanDocumentList.get(0).getLoanId());
902             }
903             businessObjectService.save(oleLoanDocumentList.get(0));
904 
905         }
906         return oleDeliverRequestBo;
907     }
908 
909     /**
910      * @param requestId
911      * @param itemUUID
912      * @param operatorId
913      * @param loanTransactionNumber
914      */
915     public void deleteRequest(String requestId, String itemUUID, String operatorId, String loanTransactionNumber, String reuestOutCome) {
916         LOG.debug("Inside deleteRequest");
917         Map<String, String> requestMap = new HashMap<String, String>();
918         Map<String, String> titleLevelRequestMap = new HashMap<String, String>();
919         List<OleDeliverRequestBo> titleLevelRequestBoList = null;
920         requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
921         OleDeliverRequestBo oleDeliverRequestBo = createRequestHistoryRecord(requestId, operatorId, loanTransactionNumber, reuestOutCome);
922         if (oleDeliverRequestBo != null) {
923             if (oleDeliverRequestBo.getRequestLevel().equalsIgnoreCase("Item Level")) {
924                 Map<String, String> itemMap = new HashMap<String, String>();
925                 itemMap.put(OLEConstants.ITEM_UUID, itemUUID);
926                 List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
927                 getBusinessObjectService().delete(oleDeliverRequestDocumentsList);
928                 int queuePosition = 1;
929                 for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
930                     oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
931                     queuePosition = queuePosition + 1;
932                 }
933                 getBusinessObjectService().save(oleDeliverRequestDocumentsList);
934             } else if (oleDeliverRequestBo.getRequestLevel().equalsIgnoreCase("Title Level")) {
935                 requestMap = new HashMap<String, String>();
936                 requestMap.put("bibId", oleDeliverRequestBo.getBibId());
937                 requestMap.put("borrowerBarcode", oleDeliverRequestBo.getBorrowerBarcode());
938                 List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
939                 if (oleDeliverRequestBoList.size() > 0) {
940                     for (OleDeliverRequestBo oleDeliverRequestBo1 : oleDeliverRequestBoList) {
941                         titleLevelRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo1.getItemUuid());
942                         getBusinessObjectService().delete(oleDeliverRequestBo1);
943                         titleLevelRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, titleLevelRequestMap);
944                         int queuePosition = 1;
945                         for (int i = 0; i < titleLevelRequestBoList.size(); i++) {
946                             titleLevelRequestBoList.get(i).setBorrowerQueuePosition(queuePosition);
947                             queuePosition = queuePosition + 1;
948                         }
949                         getBusinessObjectService().save(titleLevelRequestBoList);
950                     }
951                 }
952             }
953         }
954 
955     }
956 
957 
958     public void deleteTitleLevelIndividualRequests(OleDeliverRequestBo oleDeliverRequestBo) {
959         Map<String, String> requestMap = new HashMap<String, String>();
960         Map<String, String> titleLevelRequestMap = new HashMap<String, String>();
961         List<OleDeliverRequestBo> titleLevelRequestBoList = null;
962         requestMap = new HashMap<String, String>();
963         requestMap.put("bibId", oleDeliverRequestBo.getBibId());
964         requestMap.put("borrowerBarcode", oleDeliverRequestBo.getBorrowerBarcode());
965         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
966         if (oleDeliverRequestBoList.size() > 0) {
967             for (OleDeliverRequestBo oleDeliverRequestBo1 : oleDeliverRequestBoList) {
968                 titleLevelRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo1.getItemUuid());
969                 getBusinessObjectService().delete(oleDeliverRequestBo1);
970                 titleLevelRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, titleLevelRequestMap);
971                 int queuePosition = 1;
972                 for (int i = 0; i < titleLevelRequestBoList.size(); i++) {
973                     titleLevelRequestBoList.get(i).setBorrowerQueuePosition(queuePosition);
974                     queuePosition = queuePosition + 1;
975                 }
976                 getBusinessObjectService().save(titleLevelRequestBoList);
977             }
978         }
979     }
980 
981     /**
982      * This for retrieving the item Details from docstore
983      *
984      * @param itemUUID
985      * @return oleItemSearch
986      */
987     public OleItemSearch getItemDetails(String itemUUID) {
988         LOG.debug("Inside getItemDetails");
989         OleItemSearch oleItemSearch = getItemDetailsForPatron(itemUUID);
990         try {
991             // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
992             String itemXml = getLoanProcessor().getItemXML(itemUUID);
993             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
994             if (oleItem != null && oleItem.getItemType() != null) {
995                 oleItemSearch.setItemType(processItemType(oleItem.getItemType().getCodeValue()));
996             }
997             oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
998             if (oleItem.getItemStatus() != null) {
999                 oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
1000             }
1001             oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
1002             oleItemSearch.setVolumeNumber(oleItem.getVolumeNumber());
1003         } catch (Exception e) {
1004             LOG.error("Not able to retrieve information from the docstore for the Item Barcode : " + itemUUID, e);  //To change body of catch statement use File | Settings | File Templates.
1005         }
1006         return oleItemSearch;
1007     }
1008 
1009     /**
1010      * This method is for retrieving the item details for displaying in the patron screen
1011      *
1012      * @param itemUUID
1013      * @return OleItemSearch
1014      */
1015     public OleItemSearch getItemDetailsForPatron(String itemUUID) {
1016         LOG.debug("Inside getItemDetailsForPatron");
1017         OleItemSearch oleItemSearch;
1018         try {
1019 
1020             Map<String, String> itemMap = new HashMap<String, String>();
1021             // itemMap.put(OLEConstants.OleDeliverRequest.ITEM_UUID, itemUUID);
1022             OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(itemUUID);
1023             if (itemSearchList != null) {
1024                 return oleItemSearch = itemSearchList;
1025             }
1026         } catch (NullPointerException e) {
1027             LOG.error("No item details available for the Item Barcode : " + itemUUID, e);
1028         }
1029 
1030         return new OleItemSearch();
1031 
1032     }
1033 
1034     /**
1035      * This method is to re-order the queuePosition based on the priority while creating the request
1036      *
1037      * @param oleDeliverRequestBo
1038      * @return OleDeliverRequestBo
1039      */
1040     public OleDeliverRequestBo reOrderQueuePosition(OleDeliverRequestBo oleDeliverRequestBo) {
1041         LOG.debug("Inside reOrderQueuePosition");
1042         List<OleDeliverRequestBo> existingRequest = new ArrayList<OleDeliverRequestBo>();
1043         String queue = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.REQUEST_QUEUE);
1044         List<String> orderQueue = new ArrayList<String>();
1045         String[] queueArray = queue.split(";");
1046         for (int i = 0; i < queueArray.length; i++) {
1047             orderQueue.add(queueArray[i]);
1048         }
1049         List<OleDeliverRequestBo> finalList = new ArrayList<OleDeliverRequestBo>();
1050         Map<String, String> recallRequestMap = new HashMap<String, String>();
1051         recallRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1052         recallRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
1053         Map<String, String> recallHoldRequestMap = new HashMap<String, String>();
1054         recallHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1055         recallHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
1056         Map<String, String> holdRequestMap = new HashMap<String, String>();
1057         holdRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1058         holdRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
1059         Map<String, String> holdHoldRequestMap = new HashMap<String, String>();
1060         holdHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1061         holdHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
1062         Map<String, String> pageRequestMap = new HashMap<String, String>();
1063         pageRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1064         pageRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
1065         Map<String, String> pageHoldRequestMap = new HashMap<String, String>();
1066         pageHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1067         pageHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
1068         Map<String, String> copyRequestMap = new HashMap<String, String>();
1069         copyRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1070         copyRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "7");
1071         Map<String, String> inTransitRequestMap = new HashMap<String, String>();
1072         inTransitRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1073         inTransitRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "8");
1074         Map<String, String> asrRequestMap = new HashMap<String, String>();
1075         asrRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1076         asrRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
1077         List<OleDeliverRequestBo> recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, recallRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1078         List<OleDeliverRequestBo> recallHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, recallHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1079         List<OleDeliverRequestBo> holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, holdRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1080         List<OleDeliverRequestBo> holdHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, holdHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1081         List<OleDeliverRequestBo> pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, pageRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1082         List<OleDeliverRequestBo> pageHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, pageHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1083         List<OleDeliverRequestBo> copyList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, copyRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1084         List<OleDeliverRequestBo> inTransitList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, inTransitRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1085         List<OleDeliverRequestBo> asrList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, asrRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1086         if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_DELIVERY)) {
1087             recallList.add(oleDeliverRequestBo);
1088         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_DELIVERY)) {
1089             holdList.add(oleDeliverRequestBo);
1090         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_DELIVERY)) {
1091             pageList.add(oleDeliverRequestBo);
1092         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.COPY)) {
1093             copyList.add(oleDeliverRequestBo);
1094         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.INTRANSIT)) {
1095             inTransitList.add(oleDeliverRequestBo);
1096         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_HOLD)) {
1097             recallHoldList.add(oleDeliverRequestBo);
1098         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_HOLD)) {
1099             holdHoldList.add(oleDeliverRequestBo);
1100         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_HOLD)) {
1101             pageHoldList.add(oleDeliverRequestBo);
1102         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.ASR_REQUEST)) {
1103             asrList.add(oleDeliverRequestBo);
1104         }
1105         OleDeliverRequestBo oleDeliverRequestBo1;
1106         for (int i = 0; i < orderQueue.size(); i++) {
1107             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallList.size() > 0) {
1108                 for (int x = 0; x < recallList.size(); x++) {
1109                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallList.get(x));
1110                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1111                     this.queuePosition = this.queuePosition + 1;
1112                     finalList.add(oleDeliverRequestBo1);
1113 
1114                 }
1115             }
1116             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdList.size() > 0) {
1117                 for (int x = 0; x < holdList.size(); x++) {
1118                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdList.get(x));
1119                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1120                     this.queuePosition = this.queuePosition + 1;
1121                     finalList.add(oleDeliverRequestBo1);
1122 
1123                 }
1124             }
1125             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageList.size() > 0) {
1126                 for (int x = 0; x < pageList.size(); x++) {
1127                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageList.get(x));
1128                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1129                     this.queuePosition = this.queuePosition + 1;
1130                     finalList.add(oleDeliverRequestBo1);
1131                 }
1132             }
1133             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallHoldList.size() > 0) {
1134                 for (int x = 0; x < recallHoldList.size(); x++) {
1135                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallHoldList.get(x));
1136                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1137                     this.queuePosition = this.queuePosition + 1;
1138                     finalList.add(oleDeliverRequestBo1);
1139 
1140                 }
1141             }
1142             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdHoldList.size() > 0) {
1143                 for (int x = 0; x < holdHoldList.size(); x++) {
1144                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdHoldList.get(x));
1145                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1146                     this.queuePosition = this.queuePosition + 1;
1147                     finalList.add(oleDeliverRequestBo1);
1148 
1149                 }
1150             }
1151             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageHoldList.size() > 0) {
1152                 for (int x = 0; x < pageHoldList.size(); x++) {
1153                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageHoldList.get(x));
1154                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1155                     this.queuePosition = this.queuePosition + 1;
1156                     finalList.add(oleDeliverRequestBo1);
1157                 }
1158             }
1159             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.COPY) && copyList.size() > 0) {
1160                 for (int x = 0; x < copyList.size(); x++) {
1161                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(copyList.get(x));
1162                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1163                     this.queuePosition = this.queuePosition + 1;
1164                     finalList.add(oleDeliverRequestBo1);
1165 
1166                 }
1167             }
1168             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.INTRANSIT) && inTransitList.size() > 0) {
1169                 for (int x = 0; x < inTransitList.size(); x++) {
1170                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(inTransitList.get(x));
1171                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1172                     this.queuePosition = this.queuePosition + 1;
1173                     finalList.add(oleDeliverRequestBo1);
1174 
1175                 }
1176             }
1177             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.ASR_REQUEST) && asrList.size() > 0) {
1178                 for (int x = 0; x < asrList.size(); x++) {
1179                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(asrList.get(x));
1180                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1181                     this.queuePosition = this.queuePosition + 1;
1182                     finalList.add(oleDeliverRequestBo1);
1183 
1184                 }
1185             }
1186         }
1187         for (int i = 0; i < finalList.size(); i++) {
1188             if (finalList.get(i).getRequestId() == null) {
1189                 oleDeliverRequestBo.setBorrowerQueuePosition(finalList.get(i).getBorrowerQueuePosition());
1190                 finalList.remove(finalList.get(i));
1191             }
1192         }
1193         getBusinessObjectService().save(finalList);
1194         this.queuePosition = 0;
1195         oleDeliverRequestBo.setRequestId(KRADServiceLocator.getSequenceAccessorService().getNextAvailableSequenceNumber("OLE_DLVR_RQST_S").toString());
1196         return oleDeliverRequestBo;
1197     }
1198 
1199     /**
1200      * Thsi method is to check whether the item is available in doc store or not
1201      *
1202      * @param oleDeliverRequestBo
1203      * @return boolean
1204      */
1205     public boolean isItemAvailbleInDocstore(OleDeliverRequestBo oleDeliverRequestBo) {
1206         LOG.debug("Inside isItemAvailbleInDocstore");
1207         boolean available = false;
1208         Map<String, String> itemMap = new HashMap<String, String>();
1209         try {
1210             String itemUUID = "";
1211             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1212             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
1213             SearchResponse searchResponse = null;
1214             search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, oleDeliverRequestBo.getItemId()), ""));
1215 
1216 
1217             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
1218             ;
1219 
1220                    /* Map<String,String> map=new HashMap<>();
1221                     map.put(item.BARCODE, itemBarcode);
1222                     item=getDocstoreClientLocator().getDocstoreClient().findItem(map);*/
1223 
1224             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
1225             for (SearchResult searchResult : searchResponse.getSearchResults()) {
1226                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1227                     String fieldName = searchResultField.getFieldName();
1228                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
1229 
1230                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("item")) {
1231                         itemUUID = fieldValue;
1232                     }
1233 
1234                 }
1235             }
1236 
1237 
1238             oleDeliverRequestBo.setItemUuid(itemUUID);
1239         } catch (Exception e) {
1240             LOG.error("Exception", e);
1241             //To change body of catch statement use File | Settings | File Templates.
1242         }
1243         // itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1244         OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(oleDeliverRequestBo.getItemUuid());
1245         if (itemSearchList != null) {
1246             oleDeliverRequestBo.setTitle(itemSearchList.getTitle());
1247             oleDeliverRequestBo.setAuthor(itemSearchList.getAuthor());
1248             oleDeliverRequestBo.setCallNumber(itemSearchList.getCallNumber());
1249             oleDeliverRequestBo.setItemType(itemSearchList.getItemType());
1250         }
1251         try {
1252             // Map docStoreDetails = loanProcessor.getItemDetailsByUUID(oleDeliverRequestBo.getItemId());
1253             String itemXml = getLoanProcessor().getItemXML(oleDeliverRequestBo.getItemUuid());
1254             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
1255 
1256             oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
1257             if (oleItem.getItemStatus() != null) {
1258                 oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
1259             }
1260             oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
1261             available = true;
1262         } catch (Exception e) {
1263             LOG.error(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC), e);  //To change body of catch statement use File | Settings | File Templates.
1264         }
1265         return available;
1266     }
1267 
1268     public OleDeliverRequestBo populateItemDetailsToRequest(OleDeliverRequestBo oleDeliverRequestBo, OleItemSearch oleItemSearch) {
1269         LOG.debug("Inside populateItemDetailsToRequest");
1270         if (oleDeliverRequestBo != null && oleItemSearch != null) {
1271             oleDeliverRequestBo.setAuthor(oleItemSearch.getAuthor());
1272             oleDeliverRequestBo.setTitle(oleItemSearch.getTitle());
1273             oleDeliverRequestBo.setCallNumber(oleItemSearch.getCallNumber());
1274             oleDeliverRequestBo.setCopyNumber(oleItemSearch.getCopyNumber());
1275             oleDeliverRequestBo.setItemType(oleItemSearch.getItemType());
1276             oleDeliverRequestBo.setItemStatus(oleItemSearch.getItemStatus());
1277             oleItemSearch.setShelvingLocation(oleDeliverRequestBo.getShelvingLocation());
1278         }
1279         return oleDeliverRequestBo;
1280     }
1281 
1282 
1283     public OleDeliverRequestBo generateRecallNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
1284         Map<String, String> loanMap = new HashMap<String, String>();
1285         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1286         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
1287         OleLoanDocument oleLoanDocument = loanDocuments.get(0);
1288         Map<String, String> patronMap = new HashMap<String, String>();
1289         patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleLoanDocument.getPatronId());
1290         List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
1291         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1292         Item item;
1293         if (patronDocumentList.size() > 0) {
1294             OlePatronDocument olePatronDocument = patronDocumentList.get(0);
1295             EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
1296             oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + olePatronDocument.getEntity().getNames().get(0).getLastName());
1297             oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1298             oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1299             oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1300         }
1301         oleNoticeBo.setAuthor(oleDeliverRequestBo.getAuthor() != null ? oleDeliverRequestBo.getAuthor() : "");
1302         oleNoticeBo.setCirculationDeskAddress("");
1303         oleNoticeBo.setCirculationDeskName("");
1304         oleNoticeBo.setCirculationDeskEmailAddress("");
1305         oleNoticeBo.setCirculationDeskPhoneNumber("");
1306         oleNoticeBo.setItemCallNumber(oleDeliverRequestBo.getCallNumber() != null ? oleDeliverRequestBo.getCallNumber() : "");
1307         oleNoticeBo.setItemShelvingLocation(oleDeliverRequestBo.getShelvingLocation() != null ? oleDeliverRequestBo.getShelvingLocation() : "");
1308         oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
1309         oleNoticeBo.setTitle(oleDeliverRequestBo.getTitle() != null ? oleDeliverRequestBo.getTitle() : "");
1310         oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
1311         oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
1312         oleNoticeBo.setVolumeNumber(oleDeliverRequestBo.getVolumeNumber() != null ? oleDeliverRequestBo.getVolumeNumber() : "");
1313         oleNoticeBo.setOriginalDueDate(oleDeliverRequestBo.getOriginalDueDate());
1314         oleNoticeBo.setNewDueDate(oleDeliverRequestBo.getNewDueDate());
1315         String volumeNumber = oleDeliverRequestBo.getEnumeration() != null ? oleDeliverRequestBo.getEnumeration() : "";
1316         String chronology = oleDeliverRequestBo.getChronology() != null ? oleDeliverRequestBo.getChronology() : "";
1317         String copyNumber = oleDeliverRequestBo.getCopyNumber() != null ? oleDeliverRequestBo.getCopyNumber() : "";
1318         oleNoticeBo.setVolumeIssueCopyNumber(volumeNumber + "/" + chronology + "/" + copyNumber);
1319         /*if (oleDeliverRequestBo.getRecallDueDate() != null) {
1320             oleNoticeBo.setNewDueDate(oleDeliverRequestBo.getRecallDueDate());
1321         } else {
1322             oleNoticeBo.setNewDueDate(oleLoanDocument.getLoanDueDate());
1323         }*/
1324         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_RECALL);
1325         String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_BODY);
1326         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1327         //  oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo,oleDeliverRequestBo.getOlePatron());
1328         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1329         List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
1330         String noticeType = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_NOTICE_TYPE);
1331         oleNoticeBos.add(oleNoticeBo);
1332         if (noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1333             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
1334                 List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
1335                 String content = list.toString();
1336                 content = content.replace('[', ' ');
1337                 content = content.replace(']', ' ');
1338                 if (!content.trim().equals("")) {
1339                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1340                     String replyToEmail = getCircDeskLocationResolver().getReplyToEmail(oleNoticeBo.getItemShelvingLocation());
1341                     if (replyToEmail != null) {
1342                         oleMailer.sendEmail(new EmailFrom(replyToEmail), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1343                     } else {
1344                         String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1345                         if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1346                             fromAddress = OLEConstants.KUALI_MAIL;
1347                         }
1348                         oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1349                     }
1350                 } else {
1351                     for (OleNoticeBo oleNoticeBo1 : oleNoticeBos) {
1352                         if (LOG.isDebugEnabled()) {
1353                             LOG.debug("Notice Type :" + oleNoticeBo1.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo1.getItemId() + " " + "Patron Name :" + oleNoticeBo1.getPatronName());
1354                         }
1355                     }
1356                 }
1357                 if (LOG.isDebugEnabled()) {
1358                     LOG.debug("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1359                 }
1360 /*
1361                 Mailer  mailer = CoreApiServiceLocator.getMailer();
1362                 mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1363           */
1364             }
1365         } else if (noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1366             //oleNoticeBos.add(oleNoticeBo);
1367             Map map = oleDeliverBatchService.getSMSForPatron(oleNoticeBos);
1368             HashMap sms = (HashMap) map.get(OLEConstants.OleDeliverRequest.RECALL);
1369             Iterator it = sms.entrySet().iterator();
1370             while (it.hasNext()) {
1371                 Map.Entry pairs = (Map.Entry) it.next();
1372                 String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1373                 OleSms oleSms = new OleSms();
1374                 oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1375             }
1376 
1377         }
1378         if (noticeType.equalsIgnoreCase(OLEConstants.MAIL) || noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1379             //oleNoticeBos.add(oleNoticeBo);
1380             oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
1381             if (LOG.isDebugEnabled()) {
1382                 LOG.debug("Recall Notice Pdf generated for item Id" + oleNoticeBo.getItemId());
1383             }
1384         }
1385      //   oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(oleDeliverRequestBo);
1386         oleDeliverRequestBo.setRecallNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1387         return oleDeliverRequestBo;
1388     }
1389 
1390 
1391     public List<String> getList(String[] arrays) {
1392         List<String> resultList = new ArrayList<>();
1393         if (arrays != null && arrays.length > 0) {
1394             for (String arrayObj : arrays) {
1395                 resultList.add(arrayObj);
1396             }
1397         }
1398         return resultList;
1399     }
1400 
1401     public Map<String, String> getMap(String[] arrays) {
1402         Map<String, String> resultMap = new HashMap<String, String>();
1403         if (arrays != null && arrays.length > 0) {
1404             for (String arrayObj : arrays) {
1405                 resultMap.put(arrayObj, arrayObj);
1406             }
1407         }
1408         return resultMap;
1409     }
1410 
1411 
1412     public void generateOnHoldNoticesBasedOnPickupLocation(String pickupLocationId) throws Exception {
1413 
1414         List<OleDeliverRequestBo> finalDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1415         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService("oleLoanDao");
1416         String requestTypeParameter = getLoanProcessor().getParameter(OLEConstants.ON_HOLD_NOTICE_REQUEST_TYPE);
1417         String onHoldItemStatusParameter = getLoanProcessor().getParameter(OLEConstants.ON_HOLD_NOTICE_ITEM_STATUS);
1418         List<String> requestTypeIds = new ArrayList<String>();
1419         List<String> requestTypeCodes = new ArrayList<String>();
1420         Map<String, String> itemStatuses = new HashMap<String, String>();
1421         if (requestTypeParameter != null && !requestTypeParameter.trim().isEmpty()) {
1422             String[] requestType = requestTypeParameter.split(";");
1423             requestTypeCodes = getList(requestType);
1424             requestTypeIds = oleLoanDocumentDaoOjb.getRequestTypeIdsForHoldNotice(requestTypeCodes);
1425         }
1426         if (onHoldItemStatusParameter != null && !onHoldItemStatusParameter.trim().isEmpty()) {
1427             String[] itemStatus = onHoldItemStatusParameter.split(";");
1428             itemStatuses = getMap(itemStatus);
1429         }
1430         Collection oleDeliverRequestBoList = oleLoanDocumentDaoOjb.getHoldRequestsByPickupLocation(requestTypeIds, pickupLocationId);
1431         OleDeliverRequestBo oleDeliverRequestBo;
1432         Set<String> circulationDeskIds = new HashSet<>();
1433         List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1434         EntityTypeContactInfoBo entityTypeContactInfoBo;
1435         OleNoticeBo oleNoticeBo;
1436         Item item;
1437         boolean firstTime = true;
1438         String patronId = "";
1439         String noticeTypeParam = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_NOTICE_TYPE);
1440         for (Object obj : oleDeliverRequestBoList) {
1441             OleDeliverRequestBo deliverRequestBo = (OleDeliverRequestBo) obj;
1442             if (firstTime) {
1443                 patronId = deliverRequestBo.getBorrowerId();
1444                 firstTime = false;
1445             }
1446             if (getDocstoreUtil().isItemAvailableInDocStore(deliverRequestBo)) {
1447                 item = deliverRequestBo.getOleItem();
1448                 OlePatronDocument olePatronDocument = deliverRequestBo.getOlePatron();
1449                 if (item != null && item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null && deliverRequestBo.getOnHoldNoticeSentDate() == null) {
1450                     if (itemStatuses.containsKey(item.getItemStatus().getCodeValue())) {
1451                         entityTypeContactInfoBo = deliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1452                         oleNoticeBo = new OleNoticeBo();
1453                         oleNoticeBo.setAuthor(deliverRequestBo.getAuthor());
1454                         oleNoticeBo.setCirculationDeskAddress("");
1455                         oleNoticeBo.setCirculationDeskName("");
1456                         oleNoticeBo.setCirculationDeskEmailAddress("");
1457                         oleNoticeBo.setCirculationDeskPhoneNumber("");
1458                         oleNoticeBo.setPatronName(deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1459                         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1460                         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1461                         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1462                         oleNoticeBo.setItemCallNumber(deliverRequestBo.getCallNumber() != null ? deliverRequestBo.getCallNumber() : "");
1463                         oleNoticeBo.setItemShelvingLocation(deliverRequestBo.getShelvingLocation() != null ? deliverRequestBo.getShelvingLocation() : "");
1464                         oleNoticeBo.setItemId(deliverRequestBo.getItemId() != null ? deliverRequestBo.getItemId() : "");
1465                         oleNoticeBo.setTitle(deliverRequestBo.getTitle() != null ? deliverRequestBo.getTitle() : "");
1466                         oleNoticeBo.setOleItem(item);
1467                         oleNoticeBo.setOlePatron(deliverRequestBo.getOlePatron());
1468                         oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1469                         oleNoticeBo.setNewDueDate(new Date());
1470                         oleNoticeBo.setOriginalDueDate(new Date());
1471                         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_ONHOLD);
1472                         oleNoticeBo.setCirculationDeskName(deliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
1473                         oleNoticeBo.setCirculationDeskReplyToEmail(deliverRequestBo.getOlePickUpLocation().getReplyToEmail());
1474                         String circulationDeskId = deliverRequestBo.getPickUpLocationId();
1475                         int noDays = 0;
1476                         Map<String, String> mapCirculationDesk = new HashMap<String, String>();
1477                         mapCirculationDesk.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_ID, circulationDeskId);
1478                         List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDesk.class, mapCirculationDesk);
1479                         if (oleCirculationDesks.size() > 0) {
1480                             OleCirculationDesk oleCirculationDesk = oleCirculationDesks.get(0);
1481                             noDays = Integer.parseInt(oleCirculationDesk.getOnHoldDays());
1482                         }
1483                         Calendar calendar = Calendar.getInstance();
1484                         calendar.add(Calendar.DATE, noDays);
1485                         Date date = calendar.getTime();
1486                         oleNoticeBo.setExpiredOnHoldDate(date);
1487                         deliverRequestBo.setHoldExpirationDate(new java.sql.Date(date.getTime()));
1488                    /* try {
1489                        KRADServiceLocator.getBusinessObjectService().save(deliverRequestBo);
1490                     } catch (Exception e){
1491                         LOG.error("Exception occurred While persisting expiration hold date "+e);
1492                     }*/
1493                         String maxNumOfDays = deliverRequestBo.getOlePickUpLocation().getOnHoldDays() != null ? deliverRequestBo.getOlePickUpLocation().getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1494                         Integer maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1495                         oleNoticeBo.setOnHoldDueDate(dateAdd(deliverRequestBo.getCreateDate(), maxNumberOfDaysOnHold));
1496                         String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_BODY);
1497                         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1498                         String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1499                         HashMap<String, Object> termValues = new HashMap<String, Object>();
1500                         OleCirculationDesk oleCirculationDesk = deliverRequestBo.getOlePickUpLocation();
1501                         String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1502                         String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1503                         termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1504                         termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1505                         termValues.put(OLEConstants.NOTICE, OLEConstants.NOTICE_ONHOLD);
1506                         if (LOG.isDebugEnabled()) {
1507                             LOG.debug("termValues.toString()" + termValues.toString());
1508                         }
1509                         EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1510                         String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1511                         if (LOG.isDebugEnabled()) {
1512                             LOG.debug("**************" + noticeType);
1513                         }
1514                         noticeType = noticeType != null ? noticeType : noticeTypeParam;
1515                         oleNoticeBo.setNoticeType(noticeType);
1516                         if (!patronId.equalsIgnoreCase(deliverRequestBo.getBorrowerId()) && noticesList.size() > 0) {
1517                             String replyToEmail = null;
1518                             if (circulationDeskIds.size() == 1) {
1519                                 OleCirculationDesk circulationDesk = getCircDeskLocationResolver().getOleCirculationDesk(circulationDeskIds.iterator().next());
1520                                 if (circulationDesk != null && StringUtils.isNotBlank(circulationDesk.getReplyToEmail())) {
1521                                     replyToEmail = circulationDesk.getReplyToEmail();
1522                                 }
1523                             }
1524                             generateNoticesBasedOnNoticeType(noticesList, OLEConstants.NOTICE_ONHOLD, replyToEmail);
1525                             patronId = deliverRequestBo.getBorrowerId();
1526                             circulationDeskIds = new HashSet<>();
1527                             noticesList = new ArrayList<>();
1528                         }
1529                         if (deliverRequestBo.getOlePickUpLocation() != null && StringUtils.isNotBlank(deliverRequestBo.getOlePickUpLocation().getCirculationDeskId())) {
1530                             circulationDeskIds.add(deliverRequestBo.getOlePickUpLocation().getCirculationDeskId());
1531                         }
1532                         noticesList.add(oleNoticeBo);
1533                         // To do send Notice
1534                         deliverRequestBo.setOleItem(null);
1535                         oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(deliverRequestBo);
1536                         oleDeliverRequestBo.setOnHoldNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1537                         finalDeliverRequestBoList.add(oleDeliverRequestBo);
1538                     }
1539                 }
1540             }
1541         }
1542         if (noticesList.size() > 0) {
1543             String replyToEmail = null;
1544             if (circulationDeskIds.size() == 1) {
1545                 OleCirculationDesk circulationDesk = getCircDeskLocationResolver().getOleCirculationDesk(circulationDeskIds.iterator().next());
1546                 if (circulationDesk != null && StringUtils.isNotBlank(circulationDesk.getReplyToEmail())) {
1547                     replyToEmail = circulationDesk.getReplyToEmail();
1548                 }
1549             }
1550             generateNoticesBasedOnNoticeType(noticesList, OLEConstants.NOTICE_ONHOLD, replyToEmail);
1551         }
1552         getBusinessObjectService().save(finalDeliverRequestBoList);
1553     }
1554 
1555 
1556     public void generateOnHoldNotice() throws Exception {
1557 
1558         List<OleDeliverRequestBo> finalDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1559         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService("oleLoanDao");
1560         String requestTypeParameter = getLoanProcessor().getParameter(OLEConstants.ON_HOLD_NOTICE_REQUEST_TYPE);
1561         String onHoldItemStatusParameter = getLoanProcessor().getParameter(OLEConstants.ON_HOLD_NOTICE_ITEM_STATUS);
1562         List<String> requestTypeIds = new ArrayList<String>();
1563         List<String> requestTypeCodes = new ArrayList<String>();
1564         Map<String, String> itemStatuses = new HashMap<String, String>();
1565         if (requestTypeParameter != null && !requestTypeParameter.trim().isEmpty()) {
1566             String[] requestType = requestTypeParameter.split(";");
1567             requestTypeCodes = getList(requestType);
1568             requestTypeIds = oleLoanDocumentDaoOjb.getRequestTypeIdsForHoldNotice(requestTypeCodes);
1569         }
1570         if (onHoldItemStatusParameter != null && !onHoldItemStatusParameter.trim().isEmpty()) {
1571             String[] itemStatus = onHoldItemStatusParameter.split(";");
1572             itemStatuses = getMap(itemStatus);
1573         }
1574         Collection oleDeliverRequestBoList = oleLoanDocumentDaoOjb.getHoldRequests(requestTypeIds);
1575         OleDeliverRequestBo oleDeliverRequestBo;
1576         Set<String> circulationDeskIds = new HashSet<>();
1577         List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1578         EntityTypeContactInfoBo entityTypeContactInfoBo;
1579         OleNoticeBo oleNoticeBo;
1580         Item item;
1581         boolean firstTime = true;
1582         String patronId = "";
1583         String noticeTypeParam = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_NOTICE_TYPE);
1584         for (Object obj : oleDeliverRequestBoList) {
1585             OleDeliverRequestBo deliverRequestBo = (OleDeliverRequestBo) obj;
1586             if (firstTime) {
1587                 patronId = deliverRequestBo.getBorrowerId();
1588                 firstTime = false;
1589             }
1590             if (getDocstoreUtil().isItemAvailableInDocStore(deliverRequestBo)) {
1591                 item = deliverRequestBo.getOleItem();
1592                 OlePatronDocument olePatronDocument = deliverRequestBo.getOlePatron();
1593                 if (item != null && item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null && deliverRequestBo.getOnHoldNoticeSentDate() == null) {
1594                     if (itemStatuses.containsKey(item.getItemStatus().getCodeValue())) {
1595                         entityTypeContactInfoBo = deliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1596                         oleNoticeBo = new OleNoticeBo();
1597                         oleNoticeBo.setAuthor(deliverRequestBo.getAuthor());
1598                         oleNoticeBo.setCirculationDeskAddress("");
1599                         oleNoticeBo.setCirculationDeskName("");
1600                         oleNoticeBo.setCirculationDeskEmailAddress("");
1601                         oleNoticeBo.setCirculationDeskPhoneNumber("");
1602                         oleNoticeBo.setPatronName(deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1603                         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1604                         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1605                         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1606                         oleNoticeBo.setItemCallNumber(deliverRequestBo.getCallNumber() != null ? deliverRequestBo.getCallNumber() : "");
1607                         oleNoticeBo.setItemShelvingLocation(deliverRequestBo.getShelvingLocation() != null ? deliverRequestBo.getShelvingLocation() : "");
1608                         oleNoticeBo.setItemId(deliverRequestBo.getItemId() != null ? deliverRequestBo.getItemId() : "");
1609                         oleNoticeBo.setTitle(deliverRequestBo.getTitle() != null ? deliverRequestBo.getTitle() : "");
1610                         oleNoticeBo.setOleItem(item);
1611                         oleNoticeBo.setOlePatron(deliverRequestBo.getOlePatron());
1612                         oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1613                         oleNoticeBo.setNewDueDate(new Date());
1614                         oleNoticeBo.setOriginalDueDate(new Date());
1615                         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_ONHOLD);
1616                         oleNoticeBo.setCirculationDeskName(deliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
1617                         oleNoticeBo.setCirculationDeskReplyToEmail(deliverRequestBo.getOlePickUpLocation().getReplyToEmail());
1618                         String circulationDeskId = deliverRequestBo.getPickUpLocationId();
1619                         int noDays = 0;
1620                         Map<String, String> mapCirculationDesk = new HashMap<String, String>();
1621                         mapCirculationDesk.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_ID, circulationDeskId);
1622                         List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDesk.class, mapCirculationDesk);
1623                         if (oleCirculationDesks.size() > 0) {
1624                             OleCirculationDesk oleCirculationDesk = oleCirculationDesks.get(0);
1625                             noDays = Integer.parseInt(oleCirculationDesk.getOnHoldDays());
1626                         }
1627                         Calendar calendar = Calendar.getInstance();
1628                         calendar.add(Calendar.DATE, noDays);
1629                         Date date = calendar.getTime();
1630                         oleNoticeBo.setExpiredOnHoldDate(date);
1631                         deliverRequestBo.setHoldExpirationDate(new java.sql.Date(date.getTime()));
1632                         String maxNumOfDays = deliverRequestBo.getOlePickUpLocation().getOnHoldDays() != null ? deliverRequestBo.getOlePickUpLocation().getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1633                         Integer maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1634                         oleNoticeBo.setOnHoldDueDate(dateAdd(deliverRequestBo.getCreateDate(), maxNumberOfDaysOnHold));
1635                         String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_BODY);
1636                         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1637                         String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1638                         HashMap<String, Object> termValues = new HashMap<String, Object>();
1639                         OleCirculationDesk oleCirculationDesk = deliverRequestBo.getOlePickUpLocation();
1640                         String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1641                         String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1642                         termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1643                         termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1644                         termValues.put(OLEConstants.NOTICE, OLEConstants.NOTICE_ONHOLD);
1645                         if (LOG.isDebugEnabled()) {
1646                             LOG.debug("termValues.toString()" + termValues.toString());
1647                         }
1648                         EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1649                         String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1650                         if (LOG.isDebugEnabled()) {
1651                             LOG.debug("**************" + noticeType);
1652                         }
1653                         noticeType = noticeType != null ? noticeType : noticeTypeParam;
1654                         oleNoticeBo.setNoticeType(noticeType);
1655                         if (!patronId.equalsIgnoreCase(deliverRequestBo.getBorrowerId()) && noticesList.size() > 0) {
1656                             String replyToEmail = null;
1657                             if (circulationDeskIds.size() == 1) {
1658                                 OleCirculationDesk circulationDesk = getCircDeskLocationResolver().getOleCirculationDesk(circulationDeskIds.iterator().next());
1659                                 if (circulationDesk != null && StringUtils.isNotBlank(circulationDesk.getReplyToEmail())) {
1660                                     replyToEmail = circulationDesk.getReplyToEmail();
1661                                 }
1662                             }
1663                             generateNoticesBasedOnNoticeType(noticesList, OLEConstants.NOTICE_ONHOLD, replyToEmail);
1664                             patronId = deliverRequestBo.getBorrowerId();
1665                             circulationDeskIds = new HashSet<>();
1666                             noticesList = new ArrayList<>();
1667                         }
1668                         if (deliverRequestBo.getOlePickUpLocation() != null && StringUtils.isNotBlank(deliverRequestBo.getOlePickUpLocation().getCirculationDeskId())) {
1669                             circulationDeskIds.add(deliverRequestBo.getOlePickUpLocation().getCirculationDeskId());
1670                         }
1671                         noticesList.add(oleNoticeBo);
1672                         // To do send Notice
1673                         deliverRequestBo.setOleItem(null);
1674                         oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(deliverRequestBo);
1675                         oleDeliverRequestBo.setOnHoldNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1676                         finalDeliverRequestBoList.add(oleDeliverRequestBo);
1677                     }
1678                 }
1679             }
1680         }
1681         if (noticesList.size() > 0) {
1682             String replyToEmail = null;
1683             if (circulationDeskIds.size() == 1) {
1684                 OleCirculationDesk circulationDesk = getCircDeskLocationResolver().getOleCirculationDesk(circulationDeskIds.iterator().next());
1685                 if (circulationDesk != null && StringUtils.isNotBlank(circulationDesk.getReplyToEmail())) {
1686                     replyToEmail = circulationDesk.getReplyToEmail();
1687                 }
1688             }
1689             generateNoticesBasedOnNoticeType(noticesList, OLEConstants.NOTICE_ONHOLD, replyToEmail);
1690         }
1691         getBusinessObjectService().save(finalDeliverRequestBoList);
1692     }
1693 
1694     private void generateNoticesBasedOnNoticeType(List<OleNoticeBo> noticesList, String noticeName, String replyToEmail) throws Exception {
1695         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1696         OleNoticeBo oleNoticeBo = noticesList.get(0);
1697         String noticeType = oleNoticeBo.getNoticeType();
1698         if (noticeType != null && (noticeType.equalsIgnoreCase(OLEConstants.EMAIL) || noticeType.equalsIgnoreCase(OLEConstants.MAIL))) {
1699             if (LOG.isDebugEnabled()) {
1700                 LOG.debug("noticesList.size()" + noticesList.size());
1701             }
1702             oleDeliverBatchService.getPdfNoticeForPatron(noticesList);
1703         }
1704         if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1705             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
1706                 List list = oleDeliverBatchService.getNoticeForPatron(noticesList);
1707                 String content = list.toString();
1708                 content = content.replace('[', ' ');
1709                 content = content.replace(']', ' ');
1710                 if (!content.trim().equals("")) {
1711                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1712                     if (replyToEmail != null) {
1713                         oleMailer.sendEmail(new EmailFrom(replyToEmail), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1714                     } else {
1715                         String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1716                         if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1717                             fromAddress = OLEConstants.KUALI_MAIL;
1718                         }
1719                         oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1720                     }
1721                 } else {
1722                     if (LOG.isDebugEnabled()) {
1723                         LOG.debug("Notice Details" + noticesList);
1724                     }
1725                 }
1726                 if (LOG.isDebugEnabled()) {
1727                     LOG.debug("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1728                 }
1729             }
1730         } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1731             Map map = oleDeliverBatchService.getSMSForPatron(noticesList);
1732             HashMap sms = (HashMap) map.get(noticeName);
1733             Iterator it = sms.entrySet().iterator();
1734             while (it.hasNext()) {
1735                 Map.Entry pairs = (Map.Entry) it.next();
1736                 String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1737                 OleSms oleSms = new OleSms();
1738                 oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1739             }
1740         }
1741     }
1742 
1743     public void generateRequestExpirationNotice() throws Exception {
1744         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService("oleLoanDao");
1745         Collection oleDeliverRequestBoList = oleLoanDocumentDaoOjb.getExpiredRequests();
1746         SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1747         EntityTypeContactInfoBo entityTypeContactInfoBo;
1748         List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1749         Set<String> itemLocations = new HashSet<>();
1750         Item item;
1751         String noticeType = null;
1752         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1753         boolean firstTime = true;
1754         String patronId = "";
1755         String noticeTypeParam = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RQST_EXPR_NOTICE_TYPE);
1756         if (oleDeliverRequestBoList.size() > 0) {
1757             for (Object obj : oleDeliverRequestBoList) {
1758                 OleDeliverRequestBo deliverRequestBo = (OleDeliverRequestBo) obj;
1759                 if (firstTime) {
1760                     patronId = deliverRequestBo.getBorrowerId();
1761                     firstTime = false;
1762                 }
1763                 if (getDocstoreUtil().isItemAvailableInDocStore(deliverRequestBo)) {
1764                     //  processItem(deliverRequestBo);
1765                     item = deliverRequestBo.getOleItem();
1766                     if (LOG.isDebugEnabled()) {
1767                         LOG.debug("Expiration Date :" + deliverRequestBo.getRequestExpiryDate());
1768                     }
1769                     if (deliverRequestBo.getOlePatron().isCourtesyNotice()) {
1770                         if (LOG.isDebugEnabled()) {
1771                             LOG.debug("Inside Expiration Date :" + deliverRequestBo.getRequestExpiryDate());
1772                         }
1773                         entityTypeContactInfoBo = deliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1774                         oleNoticeBo = new OleNoticeBo();
1775                         oleNoticeBo.setAuthor(deliverRequestBo.getAuthor());
1776                         oleNoticeBo.setCirculationDeskAddress("");
1777                         oleNoticeBo.setCirculationDeskName("");
1778                         oleNoticeBo.setCirculationDeskEmailAddress("");
1779                         oleNoticeBo.setCirculationDeskPhoneNumber("");
1780                         oleNoticeBo.setPatronName(deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1781                         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1782                         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1783                         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1784                         oleNoticeBo.setItemCallNumber(deliverRequestBo.getCallNumber() != null ? deliverRequestBo.getCallNumber() : "");
1785                         oleNoticeBo.setItemShelvingLocation(deliverRequestBo.getShelvingLocation() != null ? deliverRequestBo.getShelvingLocation() : "");
1786                         oleNoticeBo.setItemId(deliverRequestBo.getItemId() != null ? deliverRequestBo.getItemId() : "");
1787                         oleNoticeBo.setTitle(deliverRequestBo.getTitle() != null ? deliverRequestBo.getTitle() : "");
1788                         oleNoticeBo.setOleItem(item);
1789                         oleNoticeBo.setOlePatron(deliverRequestBo.getOlePatron());
1790                         oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1791                         oleNoticeBo.setNewDueDate(new Date());
1792                         oleNoticeBo.setOriginalDueDate(new Date());
1793                         oleNoticeBo.setNoticeName(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1794                         String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.EXP_HOLD_NOTICE_CONTENT);
1795                         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1796                         //  noticesList.add(oleNoticeBo);
1797                         String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1798                         HashMap<String, Object> termValues = new HashMap<String, Object>();
1799                         OleCirculationDesk oleCirculationDesk = deliverRequestBo.getOlePickUpLocation();
1800                         OlePatronDocument olePatronDocument = deliverRequestBo.getOlePatron();
1801                         String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1802                         String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1803                         termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1804                         termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1805                         termValues.put(OLEConstants.NOTICE, OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1806                         if (LOG.isDebugEnabled()) {
1807                             LOG.debug("termValues.toString()" + termValues.toString());
1808                         }
1809                         EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
1810                         noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1811                         if (LOG.isDebugEnabled()) {
1812                             LOG.debug("**************" + noticeType);
1813                         }
1814                         noticeType = noticeType != null ? noticeType : noticeTypeParam;
1815                         oleNoticeBo.setNoticeType(noticeType);
1816                         oleNoticeBo.setNoticeType(noticeType);
1817                         if (!patronId.equalsIgnoreCase(deliverRequestBo.getBorrowerId()) && noticesList.size() > 0) {
1818                             String replyToEmail = null;
1819                             if (itemLocations.size() == 1) {
1820                                 replyToEmail = getCircDeskLocationResolver().getReplyToEmail(itemLocations.iterator().next());
1821                             }
1822                             generateNoticesBasedOnNoticeType(noticesList, OLEConstants.OleDeliverRequest.EXPIRED_REQUEST, replyToEmail);
1823                             patronId = deliverRequestBo.getBorrowerId();
1824                             noticesList = new ArrayList<>();
1825                             itemLocations = new HashSet<>();
1826                         }
1827                         noticesList.add(oleNoticeBo);
1828                         itemLocations.add(oleNoticeBo.getItemShelvingLocation());
1829                     }
1830                 }
1831             }
1832             if (noticesList.size() > 0) {
1833                 String replyToEmail = null;
1834                 if (itemLocations.size() == 1) {
1835                     replyToEmail = getCircDeskLocationResolver().getReplyToEmail(itemLocations.iterator().next());
1836                 }
1837                 generateNoticesBasedOnNoticeType(noticesList, OLEConstants.OleDeliverRequest.EXPIRED_REQUEST, replyToEmail);
1838             }
1839         }
1840     }
1841 
1842     private java.sql.Date dateAdd(java.sql.Date in, int daysToAdd) {
1843         if (in == null) {
1844             return null;
1845         }
1846         GregorianCalendar cal = new GregorianCalendar();
1847         cal.setTime(in);
1848         cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
1849         return new java.sql.Date(cal.getTime().getTime());
1850     }
1851 
1852     public void deletingExpiredRequests() {
1853         LOG.debug("Inside deletingExpiredRequests");
1854         List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1855         List<OleDeliverRequestBo> newOleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1856         try {
1857             oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findAll(OleDeliverRequestBo.class);
1858             //getBusinessObjectService().delete(oleDeliverRequestBoList);
1859             SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1860             for (int i = 0; i < oleDeliverRequestBoList.size(); i++) {
1861                 try {
1862                     if ((fmt.format(oleDeliverRequestBoList.get(i).getRequestExpiryDate())).compareTo(fmt.format(new Date(System.currentTimeMillis()))) < 0) {
1863                         //newOleDeliverRequestBoList.add(oleDeliverRequestBoList.get(i));
1864                         deleteRequest(oleDeliverRequestBoList.get(i).getRequestId(), oleDeliverRequestBoList.get(i).getItemUuid(), oleDeliverRequestBoList.get(i).getOperatorCreateId(), oleDeliverRequestBoList.get(i).getLoanTransactionRecordNumber(), ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.REQUEST_EXPIRED));
1865                     }
1866                 } catch (Exception e) {
1867                     LOG.info("Exception occured while deleting the request with request Id : " + oleDeliverRequestBoList.get(i).getRequestId());
1868                     LOG.error(e, e);
1869                 }
1870             }
1871             //getBusinessObjectService().save(newOleDeliverRequestBoList);
1872         } catch (Exception e) {
1873             //getBusinessObjectService().save(oleDeliverRequestBoList);
1874             LOG.error("Exception while deleting expired requests", e);
1875         }
1876     }
1877 
1878     private Item getItem(String itemUUID) {
1879         LOG.debug("Inside getItem");
1880         try {
1881             // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
1882             String itemXml = getLoanProcessor().getItemXML(itemUUID);
1883             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
1884             return oleItem;
1885         } catch (Exception e) {
1886             LOG.error("Item not available in doc store", e);
1887         }
1888         return null;
1889     }
1890 
1891 
1892     private OleNoticeBo setPatronDetailsForNotice(OleNoticeBo oleNoticeBo, OlePatronDocument olePatronDocument) {
1893         LOG.debug("Inside setPatronDetailsForNotice");
1894         if (oleNoticeBo.getAuthor() != null && olePatronDocument.getOlePatronId() != null) {
1895             oleNoticeBo.setPatronName(olePatronDocument.getName().getFirstName());
1896             if (olePatronDocument.getAddresses().size() > 0) {
1897                 oleNoticeBo.setPatronAddress(olePatronDocument.getAddresses().get(0).getLine1() + "/n" + olePatronDocument.getAddresses().get(0).getLine2() + "/n" + olePatronDocument.getAddresses().get(0).getCity());
1898             }
1899             oleNoticeBo.setPatronEmailAddress(olePatronDocument.getEmailAddress());
1900             oleNoticeBo.setPatronPhoneNumber(olePatronDocument.getPhoneNumber());
1901         }
1902         return oleNoticeBo;
1903     }
1904 
1905 
1906     private OleDeliverRequestBo createRequestHistoryRecord(String requestId, String OperatorId, String loanTransactionNumber, String reuestOutCome) {
1907         LOG.debug("Inside createRequestHistoryRecord");
1908         Map<String, String> requestMap = new HashMap<String, String>();
1909         requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
1910         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1911         OleDeliverRequestBo oleDeliverRequestBo = null;
1912         if (oleDeliverRequestBoList.size() > 0) {
1913             oleDeliverRequestBo = oleDeliverRequestBoList.get(0);
1914             OleDeliverRequestHistoryRecord oleDeliverRequestHistoryRecord = new OleDeliverRequestHistoryRecord();
1915             oleDeliverRequestHistoryRecord.setRequestId(oleDeliverRequestBo.getRequestId());
1916             oleDeliverRequestHistoryRecord.setPatronId(oleDeliverRequestBo.getOlePatron() != null ? oleDeliverRequestBo.getOlePatron().getOlePatronId() : null);
1917             oleDeliverRequestHistoryRecord.setItemId(oleDeliverRequestBo.getItemId());
1918             oleDeliverRequestHistoryRecord.setArchiveDate(new java.sql.Date(System.currentTimeMillis()));
1919             oleDeliverRequestHistoryRecord.setPickUpLocationCode(oleDeliverRequestBo.getPickUpLocationCode());
1920             if (StringUtils.isNotBlank(OperatorId)) {
1921                 oleDeliverRequestHistoryRecord.setOperatorId(OperatorId);
1922             } else {
1923                 oleDeliverRequestHistoryRecord.setOperatorId(" ");
1924             }
1925             oleDeliverRequestHistoryRecord.setDeliverRequestTypeCode(oleDeliverRequestBo.getRequestTypeCode());
1926             oleDeliverRequestHistoryRecord.setPoLineItemNumber("");
1927             oleDeliverRequestHistoryRecord.setLoanTransactionId(loanTransactionNumber);
1928             oleDeliverRequestHistoryRecord.setRequestOutComeStatus(reuestOutCome);
1929             //oleDeliverRequestHistoryRecord.setMachineId(""); //commented for jira OLE-5675
1930             getBusinessObjectService().save(oleDeliverRequestHistoryRecord);
1931             getBusinessObjectService().delete(oleDeliverRequestBoList);
1932         }
1933         return oleDeliverRequestBo;
1934     }
1935 
1936     public OleDeliverRequestBo getOleDeliverRequestBo(String itemUUID) {
1937 
1938         LOG.debug("Inside getOleDeliverRequestBo method");
1939         Map<String, String> requestMap = new HashMap<String, String>();
1940         requestMap.put(OLEConstants.ITEM_UUID, itemUUID);
1941         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1942         if (oleDeliverRequestBoList.size() > 0)
1943             return oleDeliverRequestBoList.get(0);
1944         return null;
1945     }
1946 
1947     private static int determineDifferenceInDays(Date currentDate, Date dueDate) {
1948         Calendar calendar1 = Calendar.getInstance();
1949         calendar1.setTime(dueDate);
1950         Calendar calendar2 = Calendar.getInstance();
1951         calendar2.setTime(currentDate);
1952         long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
1953         return (int) (diffInMillis / (24 * 1000 * 60 * 60));
1954     }
1955 
1956     public void generateNotices() throws Exception {
1957         //generateOverdueNotice();
1958         generateCourtesyNotice();
1959         //generateLostNotice();
1960     }
1961 
1962     public void generateLostNotice() throws Exception {
1963         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService(OLEConstants.OLE_LOAN_DAO);
1964         LoanWithNoticesDAO loanWithNoticesDAO = (LoanWithNoticesDAO) SpringContext.getService(OLEConstants.LOAN_WITH_NOTICES_DAO);
1965         String lostNoticeToDate = ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
1966                 .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.LOST_NOTICE_TO_DATE);
1967         List<String> loanIds = loanWithNoticesDAO.getLoanIdsForOverudeNotices(lostNoticeToDate, OLEConstants.NOTICE_LOST);
1968         if (loanIds.size() > 0) {
1969             List<OleLoanDocument> loanDocuments = oleLoanDocumentDaoOjb.getLaonDocumentsFromLaondId(loanIds);
1970             List<OleLoanDocument> loanDocumentsWithItemInfo = getLoanDocumentWithItemInfo(loanDocuments);
1971             int threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
1972             String threadPoolSizeValue =ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
1973                     .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.NOTICE_THREAD_POOL_SIZE);
1974             if (StringUtils.isNotBlank(threadPoolSizeValue)) {
1975                 try {
1976                     threadPoolSize = Integer.parseInt(threadPoolSizeValue);
1977                 } catch (Exception e) {
1978                     LOG.error("Invalid thread pool size from SystemParameter. So assigned default thread pool size" + threadPoolSize);
1979                     threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
1980                 }
1981             }
1982 
1983             Map<String, List<OleLoanDocument>> mapofNoticesForEachPatron = buildMapofNoticesForEachPatron(loanDocumentsWithItemInfo);
1984 
1985             ExecutorService lostNoticesExecutorService = Executors.newFixedThreadPool(threadPoolSize);
1986 
1987             for (Iterator<String> iterator = mapofNoticesForEachPatron.keySet().iterator(); iterator.hasNext(); ) {
1988                 String patronId = iterator.next();
1989                 List<OleLoanDocument> oleLoanDocuments = mapofNoticesForEachPatron.get
1990                         (patronId);
1991                 Runnable deliverOverDueNoticesExecutor = new LostNoticesExecutor(oleLoanDocuments);
1992                 lostNoticesExecutorService.execute(deliverOverDueNoticesExecutor);
1993             }
1994         }
1995     }
1996 
1997 
1998     public void generateCourtesyNotice() throws Exception {
1999         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService(OLEConstants.OLE_LOAN_DAO);
2000         LoanWithNoticesDAO loanWithNoticesDAO = (LoanWithNoticesDAO) SpringContext.getService(OLEConstants.LOAN_WITH_NOTICES_DAO);
2001         String courtesyNoticeToDate = ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
2002                 .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.COURTESY_NOTICE_TO_DATE);
2003         List<String> loanIds = loanWithNoticesDAO.getLoanIdsForOverudeNotices(courtesyNoticeToDate, OLEConstants.NOTICE_COURTESY);
2004         if (loanIds.size() > 0) {
2005             List<OleLoanDocument> loanDocuments = oleLoanDocumentDaoOjb.getLaonDocumentsFromLaondId(loanIds);
2006             List<OleLoanDocument> loanDocumentsWithItemInfo = getLoanDocumentWithItemInfo(loanDocuments);
2007             int threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
2008             String threadPoolSizeValue = ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
2009                     .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.NOTICE_THREAD_POOL_SIZE);
2010             if (StringUtils.isNotBlank(threadPoolSizeValue)) {
2011                 try {
2012                     threadPoolSize = Integer.parseInt(threadPoolSizeValue);
2013                 } catch (Exception e) {
2014                     LOG.error("Invalid thread pool size from SystemParameter. So assigned default thread pool size" + threadPoolSize);
2015                     threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
2016                 }
2017             }
2018 
2019             Map<String, List<OleLoanDocument>> mapofNoticesForEachPatron = buildMapofNoticesForEachPatron(loanDocumentsWithItemInfo);
2020 
2021             ExecutorService courtesyNoticesExecutorService = Executors.newFixedThreadPool(threadPoolSize);
2022 
2023             for (Iterator<String> iterator = mapofNoticesForEachPatron.keySet().iterator(); iterator.hasNext(); ) {
2024                 String patronId = iterator.next();
2025                 List<OleLoanDocument> oleLoanDocuments = mapofNoticesForEachPatron.get
2026                         (patronId);
2027                 Runnable deliverCourtesyNoticesExecutor = new CourtesyNoticesExecutor(oleLoanDocuments);
2028                 courtesyNoticesExecutorService.execute(deliverCourtesyNoticesExecutor);
2029             }
2030         }
2031     }
2032 
2033     public void generateOverdueNotice() throws Exception {
2034         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb) SpringContext.getService(OLEConstants.OLE_LOAN_DAO);
2035         LoanWithNoticesDAO loanWithNoticesDAO = (LoanWithNoticesDAO) SpringContext.getService(OLEConstants.LOAN_WITH_NOTICES_DAO);
2036         String overdueNoticeToDate = ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
2037                 .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.OVERDUE_NOTICE_TO_DATE);
2038         List<String> loanIds = loanWithNoticesDAO.getLoanIdsForOverudeNotices(overdueNoticeToDate, OLEConstants.NOTICE_OVERDUE);
2039         if (loanIds.size() > 0) {
2040             List<OleLoanDocument> loanDocuments = oleLoanDocumentDaoOjb.getLaonDocumentsFromLaondId(loanIds);
2041             List<OleLoanDocument> loanDocumentsWithItemInfo = getLoanDocumentWithItemInfo(loanDocuments);
2042             int threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
2043             String threadPoolSizeValue = ParameterValueResolver.getInstance().getParameter(OLEConstants.APPL_ID_OLE, OLEConstants
2044                     .DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.NOTICE_THREAD_POOL_SIZE);
2045             if (StringUtils.isNotBlank(threadPoolSizeValue)) {
2046                 try {
2047                     threadPoolSize = Integer.parseInt(threadPoolSizeValue);
2048                 } catch (Exception e) {
2049                     LOG.error("Invalid thread pool size from SystemParameter. So assigned default thread pool size" + threadPoolSize);
2050                     threadPoolSize = OLEConstants.DEFAULT_NOTICE_THREAD_POOL_SIZE;
2051                 }
2052             }
2053 
2054             Map<String, List<OleLoanDocument>> mapofNoticesForEachPatron = buildMapofNoticesForEachPatron(loanDocumentsWithItemInfo);
2055 
2056             ExecutorService overDueNoticesExecutorService = Executors.newFixedThreadPool(threadPoolSize);
2057 
2058             for (Iterator<String> iterator = mapofNoticesForEachPatron.keySet().iterator(); iterator.hasNext(); ) {
2059                 String patronId = iterator.next();
2060                 List<OleLoanDocument> oleLoanDocuments = mapofNoticesForEachPatron.get
2061                         (patronId);
2062                 Runnable deliverOverDueNoticesExecutor = new OverdueNoticesExecutor(oleLoanDocuments);
2063                 overDueNoticesExecutorService.execute(deliverOverDueNoticesExecutor);
2064             }
2065         }
2066     }
2067 
2068     private Map<String, List<OleLoanDocument>> buildMapofNoticesForEachPatron(List<OleLoanDocument> loanDocuments) {
2069         Map<String, List<OleLoanDocument>> map = new HashMap<>();
2070         String patronId;
2071         for (Iterator<OleLoanDocument> iterator = loanDocuments.iterator(); iterator.hasNext(); ) {
2072             OleLoanDocument oleLoanDocument = iterator.next();
2073             patronId = oleLoanDocument.getPatronId();
2074             if (map.containsKey(patronId)) {
2075                 map.get(patronId).add(oleLoanDocument);
2076             } else {
2077                 List<OleLoanDocument> oleLoanDocumentList = new ArrayList<>();
2078                 oleLoanDocumentList.add(oleLoanDocument);
2079                 map.put(patronId, oleLoanDocumentList);
2080             }
2081         }
2082 
2083         return map;
2084     }
2085 
2086     private void iterateNotices(List<OleLoanDocument> notices, List<String> itemUUIDS) {
2087         List<OleLoanDocument> documents = new ArrayList<>();
2088         List<String> itemIds = new ArrayList<>();
2089         if (notices != null && notices.size() > 0) {
2090             boolean firstTime = true;
2091             String patronId = "";
2092             for (Object obj : notices) {
2093                 OleLoanDocument loanDocument = (OleLoanDocument) obj;
2094                 if (firstTime) {
2095                     patronId = loanDocument.getPatronId();
2096                 }
2097                 if (patronId != null && patronId.equals(loanDocument.getPatronId())) {
2098                     documents.add(loanDocument);
2099                     itemIds.add(loanDocument.getItemUuid());
2100                 } else {
2101                     generateNoticeForOverdueAndCourtesy(patronId, documents, true, itemUUIDS);
2102                     documents = new ArrayList<>();
2103                     itemIds = new ArrayList<>();
2104                     documents.add(loanDocument);
2105                     itemIds.add(loanDocument.getItemUuid());
2106                     patronId = loanDocument.getPatronId();
2107                 }
2108                 firstTime = false;
2109             }
2110             generateNoticeForOverdueAndCourtesy(patronId, documents, true, itemUUIDS);
2111         }
2112     }
2113 
2114     public void generateNoticeForOverdueAndCourtesy(String patronId, List<OleLoanDocument> oleLoanDocuments, boolean overdue, List<String> itemUUIDS) {
2115         Map<String, String> patronMap = new HashMap<String, String>();
2116         patronMap.put("olePatronId", patronId);
2117         List<OlePatronDocument> olePatronDocuments = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
2118         if (olePatronDocuments != null && olePatronDocuments.size() > 0) {
2119             OlePatronDocument olePatronDocument = olePatronDocuments.get(0);
2120             if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
2121                 getNoticeList(oleLoanDocuments, olePatronDocument, overdue, itemUUIDS);
2122             }
2123         }
2124     }
2125 
2126     public void generateHoldCourtesyNotice() throws Exception {
2127         List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) KRADServiceLocator.getBusinessObjectService().findAll(OleDeliverRequestBo.class);
2128         List<OleDeliverRequestBo> expiredOnHoldNoticeBos = new ArrayList<>();
2129         for (OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBos) {
2130             List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
2131             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
2132             if (getDocstoreUtil().isItemAvailableInDocStore(oleDeliverRequestBo) && oleDeliverRequestBo.getHoldExpirationDate() != null && !isExpiredOnHoldNotice(oleDeliverRequestBo)) {
2133                 Item oleItem = oleDeliverRequestBo.getOleItem();
2134                 OleNoticeBo oleNoticeBo = new OleNoticeBo();
2135                 Date currentDate = new Date();
2136                 DateFormat formatter = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE_NOTICE);
2137                 Date itemStatusEffectiveDate = (Date) formatter.parse(oleItem.getItemStatusEffectiveDate());
2138                 Integer numberOfDaysOnHold = determineDifferenceInDays(currentDate, itemStatusEffectiveDate);
2139                 Integer maxNumberOfDaysOnHold = determineDifferenceInDays(itemStatusEffectiveDate, oleDeliverRequestBo.getHoldExpirationDate());
2140                 OleCirculationDesk oleCirculationDesk = null;
2141                 if (oleDeliverRequestBo.getPickUpLocationId() != null) {
2142                     oleCirculationDesk = getCircDeskLocationResolver().getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId());
2143                     //String maxNumOfDays = oleCirculationDesk.getOnHoldDays() != null ? oleCirculationDesk.getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
2144                     //maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
2145                 }
2146                 String itemTypeName = null;
2147                 if (oleItem.getTemporaryItemType() != null && oleItem.getTemporaryItemType().getCodeValue() != "") {
2148                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getTemporaryItemType().getCodeValue());
2149                     itemTypeName = oleInstanceItemType.getInstanceItemTypeCode();
2150                 } else if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
2151                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
2152                     itemTypeName = oleInstanceItemType.getInstanceItemTypeCode();
2153                 }
2154                 OlePatronDocument olePatronDocument = oleDeliverRequestBo.getOlePatron();
2155                 String agendaName = OLEConstants.OleDeliverRequest.NOTICE_VALIDATION;
2156                 String patronId = olePatronDocument.getOlePatronId() != null ? olePatronDocument.getOlePatronId() : "";
2157                 String itemId = oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "";
2158                 dataCarrierService.removeData(patronId + itemId);
2159                 HashMap<String, Object> termValues = new HashMap<String, Object>();
2160                 Date expirationDate = olePatronDocument != null ? olePatronDocument.getExpirationDate() : null;
2161                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
2162                 termValues.put(OLEConstants.ITEM_TYPE, itemTypeName);
2163                 termValues.put(OLEConstants.OVERLAY_ITEM_LOCATION, oleDeliverRequestBo.getShelvingLocation());
2164                 termValues.put(OLEConstants.NO_OF_DAYS_ON_HOLD, numberOfDaysOnHold);
2165                 termValues.put(OLEConstants.MAX_NO_OF_DAYS_ONHOLD, maxNumberOfDaysOnHold);
2166                 termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
2167                 termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
2168                 termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
2169                 termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
2170                 termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
2171                 termValues.put(OLEConstants.REQUEST_TYPE, oleDeliverRequestBo.getRequestTypeCode());
2172                 termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
2173                 termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
2174                 termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
2175                 if (oleItem.getItemStatus() != null)
2176                     termValues.put(OLEConstants.ITEM_STATUS, oleItem.getItemStatus().getCodeValue());
2177                 if (LOG.isDebugEnabled()) {
2178                     LOG.debug("termValues.toString()" + termValues.toString());
2179                 }
2180                 EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
2181                 String notice = (String) engineResults.getAttribute(OLEConstants.NOTICE);
2182                 if (LOG.isDebugEnabled()) {
2183                     LOG.debug("notice" + notice);
2184                 }
2185                 agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
2186                 termValues = new HashMap<String, Object>();
2187                 String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
2188                 String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
2189                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
2190                 termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
2191                 termValues.put(OLEConstants.NOTICE, notice);
2192                 if (LOG.isDebugEnabled()) {
2193                     LOG.debug("termValues.toString()" + termValues.toString());
2194                 }
2195                 engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
2196                 dataCarrierService.removeData(patronId + itemId);
2197                 String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
2198                 if (LOG.isDebugEnabled()) {
2199                     LOG.debug("**************" + noticeType);
2200                 }
2201                 OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
2202                 if (notice != null) {
2203                     oleNoticeBo.setNoticeName(notice);
2204                     if (notice.equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
2205                         oleNoticeBo = getExpiredHoldNotice(oleDeliverRequestBo);
2206                         oleNoticeBo.setCirculationDeskName(deskLocationName);
2207                         oleNoticeBos.add(oleNoticeBo);
2208                         noticeType = noticeType == null ? getLoanProcessor().getParameter("HOLDCOURTESY_NOTICE_TYPE") : noticeType;
2209                     }
2210                     if (oleNoticeBos.size() > 0 && noticeType != null && (noticeType.equalsIgnoreCase(OLEConstants.EMAIL) || noticeType.equalsIgnoreCase(OLEConstants.MAIL))) {
2211                         oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
2212                     }
2213 
2214                 }
2215                 olePatronDocument = oleDeliverRequestBo.getOlePatron();
2216                 if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
2217                     if (olePatronDocument.getEmailAddress() != null && !olePatronDocument.getEmailAddress().isEmpty()) {
2218                         List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
2219                         String noticeContent = list.toString();
2220                         noticeContent = noticeContent.replace('[', ' ');
2221                         noticeContent = noticeContent.replace(']', ' ');
2222                         if (!noticeContent.trim().equals("")) {
2223                             OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
2224                             if (oleDeliverRequestBo.getOlePickUpLocation() != null && StringUtils.isNotBlank(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail())) {
2225                                 oleMailer.sendEmail(new EmailFrom(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail()), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(noticeContent), true);
2226                             } else {
2227                                 String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
2228                                 if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
2229                                     fromAddress = OLEConstants.KUALI_MAIL;
2230                                 }
2231                                 oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(noticeContent), true);
2232                             }
2233                         } else {
2234                             for (OleNoticeBo oleNoticeBo1 : oleNoticeBos) {
2235                                 if (LOG.isDebugEnabled()) {
2236                                     LOG.debug("Notice Type :" + oleNoticeBo1.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo1.getItemId() + " " + "Patron Name :" + oleNoticeBo1.getPatronName());
2237                                 }
2238                             }
2239                         }
2240 
2241                         if (LOG.isDebugEnabled()) {
2242                             LOG.debug("olePatronDocument.getEmailAddress()" + olePatronDocument.getEmailAddress());
2243                         }
2244                     }
2245                 } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
2246                     //TODO : sms in progress.
2247                 }
2248             } else if (oleDeliverRequestBo.getHoldExpirationDate() != null && isExpiredOnHoldNotice(oleDeliverRequestBo)) {
2249                 expiredOnHoldNoticeBos.add(oleDeliverRequestBo);
2250             }
2251         }
2252         if (CollectionUtils.isNotEmpty(expiredOnHoldNoticeBos)) {
2253             deleteExpiredOnHoldNotices(expiredOnHoldNoticeBos);
2254         }
2255     }
2256 
2257     private void deleteExpiredOnHoldNotices(List<OleDeliverRequestBo> expiredOnHoldNoticeBos) {
2258         List<OleDeliverRequestHistoryRecord> oleDeliverRequestHistoryRecords = new ArrayList<>();
2259         for (OleDeliverRequestBo oleDeliverRequestBo : expiredOnHoldNoticeBos) {
2260             try {
2261                 deleteRequest(oleDeliverRequestBo.getRequestId(), oleDeliverRequestBo.getItemUuid(), "  ", oleDeliverRequestBo.getLoanTransactionRecordNumber(), ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.HOLD_REQUEST_EXPIRED));
2262             } catch (Exception e) {
2263 
2264             }
2265         }
2266     }
2267 
2268     private boolean isExpiredOnHoldNotice(OleDeliverRequestBo oleDeliverRequestBo) {
2269         boolean isExpired = false;
2270         if (oleDeliverRequestBo.getHoldExpirationDate() != null && oleDeliverRequestBo.getHoldExpirationDate().compareTo(getDateTimeService().getCurrentDate()) < 0) {
2271             isExpired = true;
2272         }
2273         return isExpired;
2274     }
2275 
2276     public void deleteTemporaryHistoryRecord() throws Exception {
2277         List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePatronDocument.class);
2278         for (OlePatronDocument olePatronDocument : patronDocumentList) {
2279             Map<String, String> requestMap = new HashMap<String, String>();
2280             requestMap.put(OLEConstants.OlePatron.PATRON_ID, olePatronDocument.getOlePatronId());
2281             List<OleTemporaryCirculationHistory> oleTemporaryCirculationHistoryList = (List<OleTemporaryCirculationHistory>) KRADServiceLocator.getBusinessObjectService().findMatching(OleTemporaryCirculationHistory.class, requestMap);
2282             List<OleTemporaryCirculationHistory> deleteRecords = new ArrayList<OleTemporaryCirculationHistory>();
2283             for (OleTemporaryCirculationHistory oleTemporaryCirculationHistory : oleTemporaryCirculationHistoryList) {
2284                 String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
2285                 HashMap<String, Object> termValues = new HashMap<String, Object>();
2286                 termValues.put(OLEConstants.OleDeliverRequest.IS_TEMPORARY_HISTORY_RECORD, String.valueOf(Boolean.TRUE));
2287                 DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
2288                 dataCarrierService.addData(OLEConstants.DATE_CHECK_IN, oleTemporaryCirculationHistory.getCheckInDate());
2289                 EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
2290                 Boolean deleteRecord = (Boolean) engineResults.getAttribute(OLEConstants.OVERLAY_OPTION_DELETE);
2291                 if (deleteRecord != null && deleteRecord) {
2292                     deleteRecords.add(oleTemporaryCirculationHistory);
2293                 }
2294             }
2295             getBusinessObjectService().delete(deleteRecords);
2296         }
2297     }
2298 
2299     private OleNoticeBo getExpiredHoldNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
2300         LOG.debug("Expired Hold Notice");
2301         Item oleItem = oleDeliverRequestBo.getOleItem();
2302         EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
2303         OleNoticeBo oleNoticeBo = new OleNoticeBo();
2304         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleDeliverRequestBo.getItemUuid());
2305         String shelvingLocation = oleDeliverRequestBo.getShelvingLocation();
2306         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId());
2307         if (oleCirculationDesk != null)
2308             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
2309         else
2310             oleNoticeBo.setCirculationDeskName("");
2311         oleNoticeBo.setCirculationDeskAddress("");
2312         oleNoticeBo.setCirculationDeskEmailAddress("");
2313         oleNoticeBo.setCirculationDeskPhoneNumber("");
2314         oleNoticeBo.setCirculationDeskPhoneNumber("");
2315         oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
2316         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2317         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2318         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2319         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_HOLD_COURTESY);
2320         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.EXP_HOLD_NOTICE_CONTENT));
2321         oleNoticeBo.setTitle(item.getHolding().getBib().getTitle());
2322         oleNoticeBo.setAuthor(item.getHolding().getBib().getAuthor());
2323         /*oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
2324         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
2325         oleNoticeBo.setVolumeNumber(item.getVolumeNumber());
2326         oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
2327         //oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
2328         oleNoticeBo.setItemCallNumber((String) oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("") ? oleItem.getCallNumber().getNumber() : "");
2329         oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
2330         oleNoticeBo.setCirculationDeskName(oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
2331         oleNoticeBo.setCirculationDeskReplyToEmail(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail());
2332         oleNoticeBo.setOleItem(oleItem);
2333         oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
2334         //  oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo, oleDeliverRequestBo.getOlePatron());
2335         oleDeliverRequestBo.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
2336         return oleNoticeBo;
2337     }
2338 
2339     private OleNoticeBo getCourtesyNotice(OleLoanDocument oleLoanDocument) throws Exception {
2340         LOG.debug("Courtesy Notice");
2341         oleLoanDocument.setCourtesyNoticeFlag(true);
2342         Map<String, String> map = new HashMap<String, String>();
2343         map.put(OLEConstants.LOAN_ID, oleLoanDocument.getLoanId());
2344         KRADServiceLocator.getBusinessObjectService().save(oleLoanDocument);
2345         EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
2346         OleNoticeBo oleNoticeBo = new OleNoticeBo();
2347         //String itemId  = oleLoanDocument.getItemId();
2348         Item oleItem = oleLoanDocument.getOleItem();
2349         String shelvingLocation = oleLoanDocument.getItemLocation();
2350         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2351         if (oleCirculationDesk != null)
2352             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
2353         else
2354             oleNoticeBo.setCirculationDeskName("");
2355         oleNoticeBo.setCirculationDeskAddress("");
2356         oleNoticeBo.setCirculationDeskEmailAddress("");
2357         oleNoticeBo.setCirculationDeskPhoneNumber("");
2358         oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
2359         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2360         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2361         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2362         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_COURTESY);
2363         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.COURTESY_NOTICE_CONTENT));
2364        /* oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
2365         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
2366         oleNoticeBo.setTitle(oleLoanDocument.getTitle());
2367         oleNoticeBo.setAuthor(oleLoanDocument.getAuthor());
2368         oleNoticeBo.setVolumeNumber(oleLoanDocument.getItemVolumeNumber());
2369         oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
2370         // oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
2371         oleNoticeBo.setItemCallNumber(oleLoanDocument.getItemCallNumber());
2372         oleNoticeBo.setItemId(oleLoanDocument.getItemId());
2373         oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
2374         if (LOG.isDebugEnabled()) {
2375             LOG.debug("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
2376         }
2377         return oleNoticeBo;
2378     }
2379 
2380     private OleNoticeBo getOverdueNotice(OleLoanDocument oleLoanDocument) throws Exception {
2381         LOG.debug("Overdue Notice");
2382         EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
2383         OleNoticeBo oleNoticeBo = new OleNoticeBo();
2384         //   String itemId  = oleLoanDocument.getItemId();
2385         Item oleItem = oleLoanDocument.getOleItem();
2386         //  String itemUuid = oleItem.getItemIdentifier();
2387         //String shelvingLocation = oleLoanDocument.getItemLocation();
2388         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2389         if (oleCirculationDesk != null)
2390             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
2391         else
2392             oleNoticeBo.setCirculationDeskName("");
2393         oleNoticeBo.setCirculationDeskAddress("");
2394         oleNoticeBo.setCirculationDeskEmailAddress("");
2395         oleNoticeBo.setCirculationDeskPhoneNumber("");
2396         oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
2397         oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2398         oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2399         oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2400         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_OVERDUE);
2401         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.OVERDUE_NOTICE_CONTENT));
2402         oleNoticeBo.setTitle(oleLoanDocument.getTitle());
2403         oleNoticeBo.setAuthor(oleLoanDocument.getAuthor());
2404         /*oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
2405         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
2406 
2407         //oleNoticeBo.setVolumeNumber((String) docStoreDetails.get(OLEConstants.VOL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.VOL_NUM) : "");
2408         String volume = (String) oleItem.getEnumeration() != null && !oleItem.getEnumeration().equals("") ? oleItem.getEnumeration() : "";
2409         String issue = new String(" ");
2410         String copyNumber = (String) oleItem.getCopyNumber() != null && !oleItem.getCopyNumber().equals("") ? oleItem.getCopyNumber() : "";
2411         oleNoticeBo.setVolumeIssueCopyNumber(volume + "/" + issue + "/" + copyNumber);
2412         oleNoticeBo.setItemShelvingLocation(oleLoanDocument.getItemLocation());
2413         /*if (oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("")) {
2414             oleNoticeBo.setItemCallNumber((String) oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("") ? oleItem.getCallNumber().getNumber() : "");
2415         } else {
2416             oleNoticeBo.setItemCallNumber(getLoanProcessor().getItemCallNumber(oleItem, oleLoanDocument.getInstanceUuid()));
2417         }*/
2418         oleNoticeBo.setItemCallNumber(getLoanProcessor().getItemCallNumber(oleItem, oleLoanDocument.getInstanceUuid()));
2419         //oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
2420         oleNoticeBo.setItemId(oleLoanDocument.getItemId());
2421         //oleNoticeBo.setDueDate(oleLoanDocument.getLoanDueDate()!=null ? oleLoanDocument.getLoanDueDate().toString().substring(0, 10):null);
2422         oleNoticeBo.setDueDate(oleLoanDocument.getLoanDueDate() != null ? oleLoanDocument.getLoanDueDate() : null);
2423 
2424         oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
2425         if (LOG.isDebugEnabled()) {
2426             LOG.debug("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
2427         }
2428         int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
2429         noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
2430         if (LOG.isDebugEnabled()) {
2431             LOG.debug("Updated Loan Record : " + oleLoanDocument);
2432         }
2433         oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
2434         oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
2435         getBusinessObjectService().save(oleLoanDocument);
2436         return oleNoticeBo;
2437     }
2438 
2439     public void updateItem(Item oleItem, String itemUuid) throws Exception {
2440         ItemStatus itemStatus = new ItemStatus();
2441         itemStatus.setCodeValue(OLEConstants.OleDeliverRequest.MISSING);
2442         itemStatus.setFullValue(OLEConstants.OleDeliverRequest.MISSING);
2443         oleItem.setItemStatus(itemStatus);
2444         oleItem.setStaffOnlyFlag(true);
2445         String itemContent = new ItemOlemlRecordProcessor().toXML(oleItem);
2446         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2447         item.setId(itemUuid);
2448         item.setContent(itemContent);
2449         item.setCategory(OLEConstants.WORK_CATEGORY);
2450         item.setType(DocType.ITEM.getCode());
2451         item.setFormat(OLEConstants.OLEML_FORMAT);
2452         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2453     }
2454 
2455     public String getShelvingLocation(LocationLevel oleLocationLevel) {
2456         String location = null;
2457         if (oleLocationLevel != null) {
2458             if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
2459                 location = oleLocationLevel.getName();
2460             else
2461                 location = getShelvingLocation(oleLocationLevel.getLocationLevel());
2462         }
2463         if ("".equals(location) || location == null)
2464             return null;
2465         return location;
2466     }
2467 
2468 
2469     public String getIntervalForCourtesyNotice() {
2470         BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2471         Map<String, String> criteriaMap = new HashMap<String, String>();
2472         criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
2473         criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
2474         criteriaMap.put(OLEConstants.NAME, OLEParameterConstants.COURTESY_NOTICE_INTER);
2475         List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
2476         return parametersList.get(0).getValue();
2477     }
2478 
2479     public String getIntervalForOverdueNotice() {
2480         BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2481         Map<String, String> criteriaMap = new HashMap<String, String>();
2482         criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
2483         criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
2484         criteriaMap.put(OLEConstants.NAME, OLEConstants.OVERDUE_NOTICE_INTER);
2485         List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
2486         return parametersList.get(0).getValue();
2487     }
2488 
2489 
2490     private PatronBillPayment getPatronBillPayment(String patronId) {
2491         LOG.debug("Inside the getPatronBillPayment method");
2492         Map billMap = new HashMap();
2493         billMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, patronId);
2494         List<PatronBillPayment> patronBillPaymentList = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, billMap);
2495         return patronBillPaymentList != null && patronBillPaymentList.size() > 0 ? patronBillPaymentList.get(0) : null;
2496     }
2497 
2498     private OlePaymentStatus getPaymentStatus() {
2499         LOG.debug("Inside the getPaymentStatus method");
2500         Map statusMap = new HashMap();
2501         statusMap.put(OLEConstants.OleDeliverRequest.PAYMENT_STATUS_NAME, OLEConstants.PAYMENT_STATUS_OUTSTANDING);
2502         List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
2503         return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
2504     }
2505 
2506     private String getFeeTypeId(String feeTypeName) {
2507         LOG.debug("Inside the getOverdueFeeTypeId method");
2508         Map feeMap = new HashMap();
2509         feeMap.put(OLEConstants.FEE_TYPE_NAME, feeTypeName);
2510         List<OleFeeType> oleFeeTypes = (List<OleFeeType>) getBusinessObjectService().findMatching(OleFeeType.class, feeMap);
2511         return oleFeeTypes != null && oleFeeTypes.size() > 0 ? oleFeeTypes.get(0).getFeeTypeId() : null;
2512     }
2513 
2514     public String processItemType(String itemType) {
2515 
2516         LOG.debug("Inside process Item Type");
2517         Map<String, String> itemMap = new HashMap<String, String>();
2518         itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, itemType);
2519         List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) businessObjectService.findMatching(OleInstanceItemType.class, itemMap);
2520         if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
2521             OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
2522             return oleInstanceItemType.getInstanceItemTypeName();
2523         }
2524         return null;
2525     }
2526 
2527     public String placeRequest(String patronBarcode, String operatorId, String itemBarcode, String requestType, String pickUpLocation, String itemIdentifier, String itemLocation, String itemType, String title, String author, String callNumber, boolean externalItem, String bibId, String requestLevel, java.sql.Date requestExpiryDate) {
2528         OLEPlaceRequest olePlaceRequest = new OLEPlaceRequest();
2529         OLEPlaceRequestConverter olePlaceRequestConverter = new OLEPlaceRequestConverter();
2530         ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
2531         MaintenanceDocument newDocument = null;
2532         try {
2533             try {
2534                 if (null == GlobalVariables.getUserSession()) {
2535                     Person person = personService.getPerson(operatorId);
2536                     String principalName = person.getPrincipalName();
2537                     UserSession userSession = new UserSession(principalName);
2538                     GlobalVariables.setUserSession(userSession);
2539                 }
2540                 newDocument = (MaintenanceDocument) getDocumentService().getNewDocument(OLEConstants.REQUEST_DOC_TYPE);
2541             } catch (WorkflowException e) {
2542                 e.printStackTrace();
2543                 olePlaceRequest.setBlockOverride(true);
2544                 olePlaceRequest.setMessage("Cannot create");
2545                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2546             }
2547             OleDeliverRequestBo oleDeliverRequestBo = null;
2548             oleDeliverRequestBo = (OleDeliverRequestBo) newDocument.getNewMaintainableObject().getDataObject();
2549             oleDeliverRequestBo.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
2550             oleDeliverRequestBo.setRequestLevel(requestLevel);
2551             oleDeliverRequestBo.setBibId(bibId);
2552             if (requestExpiryDate != null) {
2553                 oleDeliverRequestBo.setRequestExpiryDate(requestExpiryDate);
2554             }
2555             OlePatronDocument olePatronDocument = null;
2556             Map<String, String> patronMap = new HashMap<String, String>();
2557             patronMap.put(OLEConstants.BARCODE, patronBarcode);
2558             OleNoticeBo oleNoticeBo = new OleNoticeBo();
2559             List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
2560             if (olePatronDocumentList.size() > 0) {
2561                 olePatronDocument = olePatronDocumentList.get(0);
2562                 olePatronDocument.setOleBorrowerType((OleBorrowerType) SpringContext.getBean(PersistenceDaoOjb.class).resolveProxy(olePatronDocument.getOleBorrowerType()));
2563                 oleDeliverRequestBo.setBorrowerId(olePatronDocument.getOlePatronId());
2564                 oleDeliverRequestBo.setBorrowerBarcode(olePatronDocument.getBarcode());
2565                 oleDeliverRequestBo.setOlePatron(olePatronDocument);
2566                 EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
2567                 try {
2568                     oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
2569                     oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2570                     oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2571                     oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2572                 } catch (Exception e) {
2573                     LOG.error("Exception", e);
2574                     olePlaceRequest.setBlockOverride(true);
2575                     if (LOG.isDebugEnabled()) {
2576                         LOG.debug("Exception Occured while setting the patron information for the patron . Patron Barcode : " + oleDeliverRequestBo.getBorrowerBarcode());
2577                     }
2578                 }
2579             } else {
2580                 olePlaceRequest.setBlockOverride(true);
2581                 olePlaceRequest.setCode("002");
2582                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.NO_PATRON_INFO));
2583                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2584             }
2585             if (requestType != null) {
2586                 Map<String, String> requestTypeMap = new HashMap<String, String>();
2587                 requestTypeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_CD, requestType);
2588                 List<OleDeliverRequestType> oleDeliverRequestTypeList = (List<OleDeliverRequestType>) getBusinessObjectService().findMatching(OleDeliverRequestType.class, requestTypeMap);
2589                 if (oleDeliverRequestTypeList != null && (oleDeliverRequestTypeList.size() > 0)) {
2590                     oleDeliverRequestBo.setRequestTypeId(oleDeliverRequestTypeList.get(0).getRequestTypeId());
2591                     oleDeliverRequestBo.setOleDeliverRequestType(oleDeliverRequestTypeList.get(0));
2592                 } else {
2593                     olePlaceRequest.setBlockOverride(true);
2594                     olePlaceRequest.setCode("012");
2595                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_RQST_TYP));
2596                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2597                 }
2598             }
2599             if (pickUpLocation != null) {
2600                 Map<String, String> circulationDeskMap = new HashMap<String, String>();
2601                 circulationDeskMap.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_CD, pickUpLocation);
2602                 List<OleCirculationDesk> oleCirculationDeskList = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, circulationDeskMap);
2603                 if (oleCirculationDeskList != null && oleCirculationDeskList.size() > 0) {
2604                     oleDeliverRequestBo.setPickUpLocationId(oleCirculationDeskList.get(0).getCirculationDeskId());
2605                     oleDeliverRequestBo.setPickUpLocationCode(oleCirculationDeskList.get(0).getCirculationDeskCode());
2606                     oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDeskList.get(0));
2607                 } else {
2608                     olePlaceRequest.setBlockOverride(true);
2609                     olePlaceRequest.setCode("013");
2610                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_PK_UP_LOCN));
2611                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2612                 }
2613 
2614             }
2615             try {
2616                 if (itemBarcode == null || (itemBarcode != null && itemBarcode.isEmpty())) {
2617                     olePlaceRequest.setBlockOverride(true);
2618                     olePlaceRequest.setCode("014");
2619                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2620                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2621 
2622                 }
2623                 oleDeliverRequestBo.setItemId(itemBarcode);
2624                 oleDeliverRequestBo.setItemUuid(itemIdentifier);
2625                 oleDeliverRequestBo.setItemStatus(OLEConstants.AVAILABLE);
2626                 oleDeliverRequestBo.setItemType(itemType);
2627                 oleDeliverRequestBo.setItemLocation(itemLocation);
2628                 if (itemIdentifier == null || itemLocation == null || itemType == null) {
2629                     Thread.sleep(500);
2630                     String itemUUID = null;
2631                     String holdingsId = null;
2632                     if (itemIdentifier == null) {
2633                         try {
2634                             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2635                             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
2636                             SearchResponse searchResponse = null;
2637                             search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, oleDeliverRequestBo.getItemId()), ""));
2638                             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
2639                             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode(), "id"));
2640                             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
2641                             for (SearchResult searchResult : searchResponse.getSearchResults()) {
2642                                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
2643                                     String fieldName = searchResultField.getFieldName();
2644                                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
2645                                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("holdings")) {
2646                                         holdingsId = fieldValue;
2647                                     } else {
2648                                         oleDeliverRequestBo.setItemUuid(fieldValue);
2649                                         itemUUID = fieldValue;
2650                                     }
2651                                 }
2652                             }
2653                         } catch (Exception ex) {
2654                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_EXIST));
2655                             LOG.error(OLEConstants.ITEM_EXIST + ex);
2656                         }
2657                     }
2658                     if (itemUUID == null) {
2659                         olePlaceRequest.setBlockOverride(true);
2660                         olePlaceRequest.setCode("014");
2661                         olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2662                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2663                     }
2664                     if (itemType == null || itemLocation == null) {
2665                         Map<String, Object> detailMap = retrieveBIbItemHoldingData(itemUUID);
2666                         Bib bib = (Bib) detailMap.get(OLEConstants.BIB);
2667                         Item item = (Item) detailMap.get(OLEConstants.ITEM);
2668                         OleHoldings oleHoldings = (OleHoldings) detailMap.get(OLEConstants.HOLDING);
2669                         org.kuali.ole.docstore.common.document.Item item1 = (org.kuali.ole.docstore.common.document.Item) detailMap.get("documentItem");
2670                         if (item != null) {
2671                             oleDeliverRequestBo.setOleItem(item);
2672                             if (item.getCallNumber() != null && item.getCallNumber().getNumber() != null) {
2673                                 oleDeliverRequestBo.setCallNumber(item.getCallNumber().getNumber());
2674                             }
2675                             if (item.getCopyNumber() != null) {
2676                                 oleDeliverRequestBo.setCopyNumber(item.getCopyNumber());
2677                             }
2678                             oleDeliverRequestBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
2679                             oleDeliverRequestBo.setEnumeration(item.getEnumeration() != null ? item.getEnumeration() : "");
2680                             oleDeliverRequestBo.setChronology(item.getChronology() != null ? item.getChronology() : "");
2681                         }
2682                         if (oleHoldings != null) {
2683                             if (oleDeliverRequestBo.getCallNumber() == null && oleHoldings.getCallNumber() != null && oleHoldings.getCallNumber().getNumber() != null) {
2684                                 oleDeliverRequestBo.setCallNumber(oleHoldings.getCallNumber().getNumber());
2685                             }
2686                             if (oleDeliverRequestBo.getCopyNumber() == null && oleHoldings.getCopyNumber() != null) {
2687                                 oleDeliverRequestBo.setCopyNumber(oleHoldings.getCopyNumber());
2688                             }
2689                         }
2690                         if (itemLocation == null) {
2691                             if (item1.getLocation() == null || (item1.getLocation() != null && item1.getLocation().trim().isEmpty())) {
2692                                 itemLocation = getDocstoreUtil().getLocation(oleHoldings.getLocation(), new StringBuffer(""));
2693                             } else {
2694                                 itemLocation = item1.getLocation();
2695                             }
2696                             oleDeliverRequestBo.setItemLocation(itemLocation);
2697                         }
2698                         if (item.getItemType() != null) {
2699                             oleDeliverRequestBo.setItemType(item.getItemType().getCodeValue());
2700                         }
2701                         if (item.getItemStatus() != null) {
2702                             oleDeliverRequestBo.setItemStatus(item.getItemStatus().getCodeValue());
2703                         }
2704 
2705                         if (bib != null) {
2706                             oleDeliverRequestBo.setTitle(bib.getTitle());
2707                             oleDeliverRequestBo.setAuthor(bib.getAuthor());
2708                         }
2709                     }
2710                 }
2711 
2712                 if (itemLocation != null) {
2713                     if (asrHelperService.isAnASRItem(itemLocation) && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && !oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))) {
2714                         olePlaceRequest.setCode("700");
2715                         olePlaceRequest.setBlockOverride(true);
2716                         olePlaceRequest.setMessage("Cannot create " + oleDeliverRequestBo.getRequestTypeCode() + " for this item");
2717                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2718                     } else if (asrHelperService.isAnASRItem(itemLocation) && !oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))) {
2719                         olePlaceRequest.setCode("701");
2720                         olePlaceRequest.setBlockOverride(true);
2721                         olePlaceRequest.setMessage("Cannot create " + oleDeliverRequestBo.getRequestTypeCode() + " for this item");
2722                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2723                     }
2724                     Map<String, String> locationMap = getCircDeskLocationResolver().getLocationMap(itemLocation);
2725                     oleDeliverRequestBo.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
2726                     oleDeliverRequestBo.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
2727                     oleDeliverRequestBo.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
2728                     oleDeliverRequestBo.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
2729                     oleDeliverRequestBo.setShelvingLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
2730                 }
2731                 oleDeliverRequestBo.setRequestCreator(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR);
2732                 oleDeliverRequestBo.setOperatorCreateId(operatorId);
2733                 oleDeliverRequestBo.setItemId(itemBarcode);
2734                /* if (!processOperator(operatorId)) {
2735                     olePlaceRequest.setCode("001");
2736                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_OPRTR_ID));
2737                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2738                 }*/
2739                 processRequestTypeByPickUpLocation(oleDeliverRequestBo);
2740                 String message = this.patronRecordExpired(oleDeliverRequestBo);
2741                 if (message != null) {
2742                     olePlaceRequest.setCode("015");
2743                     olePlaceRequest.setMessage(message);
2744                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2745                 }
2746                 boolean requestRaised = this.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo);
2747                 if (requestRaised) {
2748                     {
2749                         olePlaceRequest.setBlockOverride(true);
2750                         olePlaceRequest.setCode("016");
2751                         olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_ALRDY_RAISD));
2752                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2753                     }
2754                 }
2755                 boolean itemEligible = this.isItemEligible(oleDeliverRequestBo);
2756                 if (!itemEligible) {
2757                     {
2758                         olePlaceRequest.setBlockOverride(true);
2759                         olePlaceRequest.setCode("017");
2760                         olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITM_NOT_LOAN));
2761                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2762                     }
2763                 }
2764                 boolean alreadyLoaned = this.isAlreadyLoaned(oleDeliverRequestBo);
2765                 if (alreadyLoaned) {
2766                     olePlaceRequest.setBlockOverride(true);
2767                     olePlaceRequest.setCode("018");
2768                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITM_LOAN_BY_PTRN));
2769                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2770                 }
2771                 SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
2772                 boolean valid = false;
2773                 EngineResults engineResult = this.executeEngineResults(oleDeliverRequestBo);
2774                 if (engineResult != null) {
2775                     List<ResultEvent> allResults = engineResult.getAllResults();
2776                     if (allResults.size() > 0) {
2777                         if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
2778                             olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
2779                         }
2780                         for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
2781                             ResultEvent resultEvent = resultEventIterator.next();
2782                             if (resultEvent.getType().equals(RULE_EVALUATED))
2783                                 valid |= resultEvent.getResult();
2784                         }
2785                         if ((oleDeliverRequestBo.getMessage() != null && !oleDeliverRequestBo.getMessage().isEmpty())) {
2786                             olePlaceRequest.setCode("500");
2787                             olePlaceRequest.setMessage(oleDeliverRequestBo.getMessage().replaceAll("<br/>", ""));
2788                             return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2789                         }
2790 
2791                     }
2792                 }
2793 
2794                 OleDeliverRequestBo oleDeliverRequestBo1 = null;
2795                 boolean asrItem = false;
2796                 try {
2797                     oleDeliverRequestBo1 = oleDeliverRequestBo;
2798                     if (isItemAvailable(oleDeliverRequestBo1)) {
2799                         olePlaceRequest.setBlockOverride(true);
2800                         olePlaceRequest.setCode("019");
2801                         olePlaceRequest.setMessage(oleDeliverRequestBo1.getRequestTypeCode() + OLEConstants.RQST_CONDITION + oleDeliverRequestBo1.getItemStatus());
2802                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2803                     }
2804                     oleDeliverRequestBo.setOleItem(null);
2805                     asrItem = asrHelperService.isAnASRItem(oleDeliverRequestBo.getItemLocation());
2806                     if (asrItem && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS))) {
2807                         oleDeliverRequestBo.setAsrFlag(true);
2808                         oleDeliverRequestBo.setRequestStatus("1");
2809                     }
2810                     newDocument.getDocumentHeader().setDocumentDescription(OLEConstants.NEW_REQUEST_DOC);
2811                     newDocument.getNewMaintainableObject().setDataObject(oleDeliverRequestBo1);
2812 
2813                     newDocument = (MaintenanceDocument) getDocumentService().routeDocument(newDocument, null, null);
2814                     oleDeliverRequestBo = (OleDeliverRequestBo) newDocument.getNewMaintainableObject().getDataObject();
2815                 } catch (WorkflowException e) {
2816                     e.printStackTrace();
2817                 }
2818 
2819 
2820                 String requestId = "";
2821 
2822                 try {
2823                     requestId = ":" + OLEConstants.OleDeliverRequest.REQUEST_ID + ":" + oleDeliverRequestBo.getRequestId();
2824 
2825                     if (!oleDeliverRequestBo.getRequestTypeId().equals("8")) {
2826                         oleDeliverRequestBo = updateLoanDocument(oleDeliverRequestBo);
2827                         oleDeliverRequestBo.setOlePatron(null);
2828                         oleDeliverRequestBo.setOleProxyPatron(null);
2829                     }
2830                     if (LOG.isDebugEnabled()) {
2831                         LOG.debug("Request Raised Succesfully" + requestId);
2832                     }
2833                     if (externalItem) {
2834                         String noticeSendParameter = getLoanProcessor().getParameter(OLEParameterConstants.NCIP_ACCEPT_ITEM_NOTICE_INDICATOR);
2835                         if (noticeSendParameter != null && (noticeSendParameter.trim().isEmpty() || noticeSendParameter.equalsIgnoreCase("Y"))) {
2836                             oleNoticeBo.setNoticeName(OLEConstants.PICKUP_NOTICE);
2837                             Date pickupDate = new java.sql.Date(System.currentTimeMillis());
2838                             if (oleDeliverRequestBo.getOlePickUpLocation() != null && oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays() != null) {
2839                                 pickupDate = addDate(new java.sql.Date(System.currentTimeMillis()), new Integer(oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays()));
2840                             }
2841                             oleNoticeBo.setNoticeSpecificContent(OLEConstants.PICKUP_NOTICE_START_CONTENT + oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName() + OLEConstants.PICKUP_NOTICE_MIDDLE_CONTENT + pickupDate + OLEConstants.PICKUP_NOTICE_FINAL_CONTENT);
2842                             oleNoticeBo.setAuthor(author);
2843                             oleNoticeBo.setItemCallNumber(callNumber);
2844                             oleNoticeBo.setItemId(itemBarcode);
2845                             oleNoticeBo.setTitle(title);
2846                             oleNoticeBo.setCirculationDeskName(oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
2847                             oleNoticeBo.setCirculationDeskReplyToEmail(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail());
2848                             OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
2849                             String content = oleDeliverBatchService.getEmailPickUpNotice(oleNoticeBo);
2850                             try {
2851                                 if (!content.trim().equals("")) {
2852                                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
2853                                     if (oleDeliverRequestBo.getOlePickUpLocation() != null && StringUtils.isNotBlank(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail())) {
2854                                         oleMailer.sendEmail(new EmailFrom(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail()), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
2855                                     } else {
2856                                         String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
2857                                         if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
2858                                             fromAddress = OLEConstants.KUALI_MAIL;
2859                                         }
2860                                         oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
2861                                     }
2862                                     if (LOG.isDebugEnabled()) {
2863                                         LOG.debug("Mail send Successfully to " + oleNoticeBo.getPatronEmailAddress());
2864                                     }
2865                                     oleDeliverBatchService.getPdfPickUpNotice(oleNoticeBo);
2866                                 } else {
2867                                     if (LOG.isDebugEnabled()) {
2868                                         LOG.debug("Notice Type :" + oleNoticeBo.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo.getItemId() + " " + "Patron Name :" + oleNoticeBo.getPatronName());
2869                                     }
2870                                 }
2871                             } catch (Exception e) {
2872                                 LOG.error("Exception", e);
2873                                 olePlaceRequest.setCode("020");
2874                                 olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2875                                 olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.NTCE_PRBLM);
2876                                 olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
2877                                 olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2878                                 if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
2879                                     olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
2880                                 }
2881                                 olePlaceRequest.setBlockOverride(true);
2882                                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2883                             }
2884                         }
2885                     }
2886 
2887                 } catch (Exception e) {
2888                     LOG.error("Exception", e);
2889                     olePlaceRequest.setCode("020");
2890                     olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2891                     olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.RQST_PRBLM);
2892                     olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
2893                     olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2894                     if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
2895                         olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
2896                     }
2897                     olePlaceRequest.setBlockOverride(true);
2898                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2899 
2900                 }
2901                 olePlaceRequest.setCode("021");
2902                 olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
2903                 olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2904                 olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2905                 if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
2906                     olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
2907                 }
2908                 olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId);
2909                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2910             } catch (Exception e) {
2911                 LOG.error("Exception", e);
2912                 olePlaceRequest.setBlockOverride(true);
2913                 if (e.getMessage() != null && e.getMessage().equalsIgnoreCase("Item barcode does not exist.")) {
2914                     olePlaceRequest.setCode("014");
2915                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2916                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2917                 }
2918                 olePlaceRequest.setCode("023");
2919                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_FAIL));
2920                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2921             }
2922         } catch (Exception e) {
2923             LOG.error("Exception", e);
2924             olePlaceRequest.setBlockOverride(true);
2925             olePlaceRequest.setCode("023");
2926             olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_FAIL));
2927             return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2928         }
2929     }
2930 
2931     private DocumentService getDocumentService() {
2932         if (null == documentService) {
2933             documentService = GlobalResourceLoader.getService(OLEConstants.DOCUMENT_HEADER_SERVICE);
2934         }
2935         return documentService;
2936     }
2937 
2938     public void setDocumentService(DocumentService documentService) {
2939         this.documentService = documentService;
2940     }
2941 
2942     public String overridePlaceRequest(String patronBarcode, String operatorId, String itemBarcode, String requestType, String pickUpLocation, String itemIdentifier, String itemLocation, String itemType, String title, String author, String callNumber, boolean externalItem, String bibId, String requestLevel, java.sql.Date requestExpiryDate) {
2943         OLEPlaceRequest olePlaceRequest = new OLEPlaceRequest();
2944         OLEPlaceRequestConverter olePlaceRequestConverter = new OLEPlaceRequestConverter();
2945         ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
2946         MaintenanceDocument newDocument = null;
2947         try {
2948             try {
2949                 if (null == GlobalVariables.getUserSession()) {
2950                     Person person = personService.getPerson(operatorId);
2951                     String principalName = person.getPrincipalName();
2952                     UserSession userSession = new UserSession(principalName);
2953                     GlobalVariables.setUserSession(userSession);
2954                 }
2955                 newDocument = (MaintenanceDocument) getDocumentService().getNewDocument(OLEConstants.REQUEST_DOC_TYPE);
2956             } catch (WorkflowException e) {
2957                 e.printStackTrace();
2958                 olePlaceRequest.setMessage("Cannot create");
2959                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2960             }
2961             OleDeliverRequestBo oleDeliverRequestBo = null;
2962             oleDeliverRequestBo = (OleDeliverRequestBo) newDocument.getNewMaintainableObject().getDataObject();
2963             oleDeliverRequestBo.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
2964             oleDeliverRequestBo.setRequestLevel(requestLevel);
2965             oleDeliverRequestBo.setBibId(bibId);
2966             if (requestExpiryDate != null) {
2967                 oleDeliverRequestBo.setRequestExpiryDate(requestExpiryDate);
2968             }
2969             OlePatronDocument olePatronDocument = null;
2970             Map<String, String> patronMap = new HashMap<String, String>();
2971             patronMap.put(OLEConstants.BARCODE, patronBarcode);
2972             OleNoticeBo oleNoticeBo = new OleNoticeBo();
2973             List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
2974             if (olePatronDocumentList.size() > 0) {
2975                 olePatronDocument = olePatronDocumentList.get(0);
2976                 oleDeliverRequestBo.setBorrowerId(olePatronDocument.getOlePatronId());
2977                 oleDeliverRequestBo.setBorrowerBarcode(olePatronDocument.getBarcode());
2978                 oleDeliverRequestBo.setOlePatron(olePatronDocument);
2979                 EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
2980                 try {
2981                     oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
2982                     oleNoticeBo.setPatronAddress(getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2983                     oleNoticeBo.setPatronEmailAddress(getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2984                     oleNoticeBo.setPatronPhoneNumber(getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2985                 } catch (Exception e) {
2986                     LOG.error("Exception", e);
2987                     if (LOG.isDebugEnabled()) {
2988                         LOG.debug("Exception Occured while setting the patron information for the patron . Patron Barcode : " + oleDeliverRequestBo.getBorrowerBarcode());
2989                     }
2990                 }
2991             }
2992             if (requestType != null) {
2993                 Map<String, String> requestTypeMap = new HashMap<String, String>();
2994                 requestTypeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_CD, requestType);
2995                 List<OleDeliverRequestType> oleDeliverRequestTypeList = (List<OleDeliverRequestType>) getBusinessObjectService().findMatching(OleDeliverRequestType.class, requestTypeMap);
2996                 if (oleDeliverRequestTypeList != null && (oleDeliverRequestTypeList.size() > 0)) {
2997                     oleDeliverRequestBo.setRequestTypeId(oleDeliverRequestTypeList.get(0).getRequestTypeId());
2998                     oleDeliverRequestBo.setOleDeliverRequestType(oleDeliverRequestTypeList.get(0));
2999                 }
3000             }
3001             if (pickUpLocation != null) {
3002                 Map<String, String> circulationDeskMap = new HashMap<String, String>();
3003                 circulationDeskMap.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_CD, pickUpLocation);
3004                 List<OleCirculationDesk> oleCirculationDeskList = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, circulationDeskMap);
3005                 if (oleCirculationDeskList != null && oleCirculationDeskList.size() > 0) {
3006                     oleDeliverRequestBo.setPickUpLocationId(oleCirculationDeskList.get(0).getCirculationDeskId());
3007                     oleDeliverRequestBo.setPickUpLocationCode(oleCirculationDeskList.get(0).getCirculationDeskCode());
3008                     oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDeskList.get(0));
3009                 }
3010             }
3011             try {
3012                 oleDeliverRequestBo.setItemId(itemBarcode);
3013                 oleDeliverRequestBo.setItemUuid(itemIdentifier);
3014                 oleDeliverRequestBo.setItemStatus(OLEConstants.AVAILABLE);
3015                 oleDeliverRequestBo.setItemType(itemType);
3016                 oleDeliverRequestBo.setItemLocation(itemLocation);
3017                 if (itemIdentifier == null || itemLocation == null || itemType == null) {
3018                     Thread.sleep(500);
3019                     String itemUUID = null;
3020                     String holdingsId = null;
3021                     if (itemIdentifier == null) {
3022                         try {
3023                             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
3024                             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
3025                             SearchResponse searchResponse = null;
3026                             search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, oleDeliverRequestBo.getItemId()), ""));
3027                             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
3028                             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode(), "id"));
3029                             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
3030                             for (SearchResult searchResult : searchResponse.getSearchResults()) {
3031                                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
3032                                     String fieldName = searchResultField.getFieldName();
3033                                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
3034                                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("holdings")) {
3035                                         holdingsId = fieldValue;
3036                                     } else {
3037                                         oleDeliverRequestBo.setItemUuid(fieldValue);
3038                                         itemUUID = fieldValue;
3039                                     }
3040                                 }
3041                             }
3042                         } catch (Exception ex) {
3043                             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_EXIST));
3044                             LOG.error(OLEConstants.ITEM_EXIST + ex);
3045                         }
3046                     }
3047                     if (itemType == null || itemLocation == null) {
3048                         Map<String, Object> detailMap = retrieveBIbItemHoldingData(itemUUID);
3049                         Bib bib = (Bib) detailMap.get(OLEConstants.BIB);
3050                         Item item = (Item) detailMap.get(OLEConstants.ITEM);
3051                         OleHoldings oleHoldings = (OleHoldings) detailMap.get(OLEConstants.HOLDING);
3052                         org.kuali.ole.docstore.common.document.Item item1 = (org.kuali.ole.docstore.common.document.Item) detailMap.get("documentItem");
3053                         if (item != null) {
3054                             oleDeliverRequestBo.setOleItem(item);
3055                             if (item.getCallNumber() != null && item.getCallNumber().getNumber() != null) {
3056                                 oleDeliverRequestBo.setCallNumber(item.getCallNumber().getNumber());
3057                             }
3058                             if (item.getCopyNumber() != null) {
3059                                 oleDeliverRequestBo.setCopyNumber(item.getCopyNumber());
3060                             }
3061                             oleDeliverRequestBo.setVolumeNumber(item.getEnumeration() != null ? item.getEnumeration() : "");
3062                         }
3063                         if (oleHoldings != null) {
3064                             if (oleDeliverRequestBo.getCallNumber() == null && oleHoldings.getCallNumber() != null && oleHoldings.getCallNumber().getNumber() != null) {
3065                                 oleDeliverRequestBo.setCallNumber(oleHoldings.getCallNumber().getNumber());
3066                             }
3067                             if (oleDeliverRequestBo.getCopyNumber() == null && oleHoldings.getCopyNumber() != null) {
3068                                 oleDeliverRequestBo.setCopyNumber(oleHoldings.getCopyNumber());
3069                             }
3070                         }
3071                         if (itemLocation == null) {
3072                             if (item1.getLocation() == null || (item1.getLocation() != null && item1.getLocation().trim().isEmpty())) {
3073                                 itemLocation = getDocstoreUtil().getLocation(oleHoldings.getLocation(), new StringBuffer(""));
3074                             } else {
3075                                 itemLocation = item1.getLocation();
3076                             }
3077                             oleDeliverRequestBo.setItemLocation(itemLocation);
3078                         }
3079                         if (item.getItemType() != null) {
3080                             oleDeliverRequestBo.setItemType(item.getItemType().getCodeValue());
3081                         }
3082                         if (item.getItemStatus() != null) {
3083                             oleDeliverRequestBo.setItemStatus(item.getItemStatus().getCodeValue());
3084                         }
3085 
3086                         if (bib != null) {
3087                             oleDeliverRequestBo.setTitle(bib.getTitle());
3088                             oleDeliverRequestBo.setAuthor(bib.getAuthor());
3089                         }
3090                     }
3091                 }
3092 
3093                 if (itemLocation != null) {
3094                     if (asrHelperService.isAnASRItem(itemLocation) && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && !oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))) {
3095                         olePlaceRequest.setCode("700");
3096                         olePlaceRequest.setMessage("Cannot create " + oleDeliverRequestBo.getRequestTypeCode() + " for this item");
3097                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3098                     } else if (asrHelperService.isAnASRItem(itemLocation) && !oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))) {
3099                         olePlaceRequest.setCode("701");
3100                         olePlaceRequest.setMessage("Cannot create " + oleDeliverRequestBo.getRequestTypeCode() + " for this item");
3101                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3102                     }
3103                     Map<String, String> locationMap = getCircDeskLocationResolver().getLocationMap(itemLocation);
3104                     oleDeliverRequestBo.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
3105                     oleDeliverRequestBo.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
3106                     oleDeliverRequestBo.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
3107                     oleDeliverRequestBo.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
3108                     oleDeliverRequestBo.setShelvingLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
3109                 }
3110                 oleDeliverRequestBo.setRequestCreator(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR);
3111                 oleDeliverRequestBo.setOperatorCreateId(operatorId);
3112                 oleDeliverRequestBo.setItemId(itemBarcode);
3113                 processRequestTypeByPickUpLocation(oleDeliverRequestBo);
3114                 SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
3115                 boolean valid = false;
3116                 EngineResults engineResult = this.executeEngineResultsForOverride(oleDeliverRequestBo);
3117                 if (engineResult != null) {
3118                     List<ResultEvent> allResults = engineResult.getAllResults();
3119                     if (allResults.size() > 0) {
3120                         if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
3121                             olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
3122                         }
3123                         for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
3124                             ResultEvent resultEvent = resultEventIterator.next();
3125                             if (resultEvent.getType().equals(RULE_EVALUATED))
3126                                 valid |= resultEvent.getResult();
3127                         }
3128 
3129                     }
3130                 }
3131 
3132                 OleDeliverRequestBo oleDeliverRequestBo1 = null;
3133                 boolean asrItem = false;
3134                 try {
3135                     oleDeliverRequestBo1 = oleDeliverRequestBo;
3136                     oleDeliverRequestBo.setOleItem(null);
3137                     asrItem = asrHelperService.isAnASRItem(oleDeliverRequestBo.getItemLocation());
3138                     if (asrItem && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS))) {
3139                         oleDeliverRequestBo.setAsrFlag(true);
3140                         oleDeliverRequestBo.setRequestStatus("1");
3141                     }
3142                     newDocument.getDocumentHeader().setDocumentDescription(OLEConstants.NEW_REQUEST_DOC);
3143                     if (StringUtils.isNotBlank(oleDeliverRequestBo1.getRequestTypeId()) && (oleDeliverRequestBo1.getRequestTypeId().equals("1") || oleDeliverRequestBo1.getRequestTypeId().equals("2"))) {
3144                         oleDeliverRequestBo1.setRecallNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
3145                     }
3146                     newDocument.getNewMaintainableObject().setDataObject(oleDeliverRequestBo1);
3147 
3148                     newDocument = (MaintenanceDocument) getDocumentService().routeDocument(newDocument, null, null);
3149                     oleDeliverRequestBo = (OleDeliverRequestBo) newDocument.getNewMaintainableObject().getDataObject();
3150                 } catch (WorkflowException e) {
3151                     e.printStackTrace();
3152                 }
3153 
3154 
3155                 String requestId = "";
3156                 //  SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
3157                 try {
3158                     requestId = ":" + OLEConstants.OleDeliverRequest.REQUEST_ID + ":" + oleDeliverRequestBo.getRequestId();
3159 
3160                     if (!oleDeliverRequestBo.getRequestTypeId().equals("8")) {
3161                         oleDeliverRequestBo = updateLoanDocument(oleDeliverRequestBo);
3162                         oleDeliverRequestBo.setOlePatron(null);
3163                         oleDeliverRequestBo.setOleProxyPatron(null);
3164                     }
3165                     if (LOG.isDebugEnabled()) {
3166                         LOG.debug("Request Raised Succesfully" + requestId);
3167                     }
3168                     if (externalItem) {
3169                         String noticeSendParameter = getLoanProcessor().getParameter(OLEParameterConstants.NCIP_ACCEPT_ITEM_NOTICE_INDICATOR);
3170                         if (noticeSendParameter != null && (noticeSendParameter.trim().isEmpty() || noticeSendParameter.equalsIgnoreCase("Y"))) {
3171                             oleNoticeBo.setNoticeName(OLEConstants.PICKUP_NOTICE);
3172                             Date pickupDate = new java.sql.Date(System.currentTimeMillis());
3173                             if (oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays() != null) {
3174                                 pickupDate = addDate(new java.sql.Date(System.currentTimeMillis()), new Integer(oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays()));
3175                             }
3176                             oleNoticeBo.setNoticeSpecificContent(OLEConstants.PICKUP_NOTICE_START_CONTENT + oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName() + OLEConstants.PICKUP_NOTICE_MIDDLE_CONTENT + pickupDate + OLEConstants.PICKUP_NOTICE_FINAL_CONTENT);
3177                             oleNoticeBo.setAuthor(author);
3178                             oleNoticeBo.setItemCallNumber(callNumber);
3179                             oleNoticeBo.setItemId(itemBarcode);
3180                             oleNoticeBo.setTitle(title);
3181                             oleNoticeBo.setCirculationDeskName(oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
3182                             oleNoticeBo.setCirculationDeskReplyToEmail(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail());
3183                             OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
3184                             String content = oleDeliverBatchService.getEmailPickUpNotice(oleNoticeBo);
3185                             try {
3186                                 if (!content.trim().equals("")) {
3187                                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
3188                                     if (oleDeliverRequestBo.getOlePickUpLocation() != null && StringUtils.isNotBlank(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail())) {
3189                                         oleMailer.sendEmail(new EmailFrom(oleDeliverRequestBo.getOlePickUpLocation().getReplyToEmail()), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
3190                                     } else {
3191                                         String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
3192                                         if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
3193                                             fromAddress = OLEConstants.KUALI_MAIL;
3194                                         }
3195                                         oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
3196                                     }
3197                                     if (LOG.isDebugEnabled()) {
3198                                         LOG.debug("Mail send Successfully to " + oleNoticeBo.getPatronEmailAddress());
3199                                     }
3200                                     oleDeliverBatchService.getPdfPickUpNotice(oleNoticeBo);
3201                                 } else {
3202                                     if (LOG.isDebugEnabled()) {
3203                                         LOG.debug("Notice Type :" + oleNoticeBo.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo.getItemId() + " " + "Patron Name :" + oleNoticeBo.getPatronName());
3204                                     }
3205                                 }
3206                             } catch (Exception e) {
3207                                 LOG.error("Exception", e);
3208                                 olePlaceRequest.setCode("020");
3209                                 olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
3210                                 olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.NTCE_PRBLM);
3211                                 olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
3212                                 olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
3213                                 if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
3214                                     olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
3215                                 }
3216                                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3217                             }
3218                         }
3219                     }
3220 
3221                 } catch (Exception e) {
3222                     LOG.error("Exception", e);
3223                     olePlaceRequest.setCode("020");
3224                     olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
3225                     olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.RQST_PRBLM);
3226                     olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
3227                     olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
3228                     if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
3229                         olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
3230                     }
3231                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3232 
3233                 }
3234                 olePlaceRequest.setCode("021");
3235                 olePlaceRequest.setRequestId(oleDeliverRequestBo.getRequestId());
3236                 olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
3237                 olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
3238                 olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId);
3239                 if (oleDeliverRequestBo.getRequestExpiryDate() != null) {
3240                     olePlaceRequest.setExpirationDate(fmt.format(oleDeliverRequestBo.getRequestExpiryDate()));
3241                 }
3242                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3243             } catch (Exception e) {
3244                 LOG.error("Exception", e);
3245                 olePlaceRequest.setCode("023");
3246                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_FAIL));
3247                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3248             }
3249         } catch (Exception e) {
3250             LOG.error("Exception", e);
3251             olePlaceRequest.setCode("023");
3252             olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_FAIL));
3253             return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
3254         }
3255     }
3256 
3257     public String getAvailableDate(String itemBarcode) {
3258         Map<String, String> loanMap = new HashMap<>();
3259         SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
3260         simpleDateFormat.applyPattern(OLEConstants.GREGORIAN_PATTERN);
3261         loanMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemBarcode);
3262         String date = null;
3263         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
3264         if (loanDocuments.size() > 0) {
3265             if (loanDocuments.get(0).getLoanDueDate() != null) {
3266                 date = loanDocuments.get(0).getLoanDueDate().toString();
3267             } else {
3268                 date = simpleDateFormat.format(new Timestamp(2025, 1, 1, 1, 1, 1, 1));
3269             }
3270         } else {
3271             date = simpleDateFormat.format(new Timestamp(new java.sql.Date(System.currentTimeMillis()).getTime()));
3272         }
3273         return date;
3274     }
3275 
3276 
3277     public java.sql.Date addDate(java.sql.Date in, int daysToAdd) {
3278         if (in == null) {
3279             return null;
3280         }
3281         GregorianCalendar cal = new GregorianCalendar();
3282         cal.setTime(in);
3283         cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
3284         return new java.sql.Date(cal.getTime().getTime());
3285     }
3286 
3287 
3288     private boolean isRecallRequestExist(String requestTypeId, String itemBarcode) {
3289         HashMap<String, String> map = new HashMap<String, String>();
3290         map.put("itemId", itemBarcode);
3291         map.put("requestTypeId", requestTypeId);
3292         List<OleDeliverRequestBo> matchBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, map);
3293         if (matchBos != null && matchBos.size() > 0) {
3294             return false;
3295         }
3296         return true;
3297     }
3298 
3299     public EngineResults executeEngineResults(OleDeliverRequestBo oleDeliverRequestBo) {
3300         List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
3301         List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
3302         List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
3303         List<OleDeliverRequestBo> asrList = new ArrayList<OleDeliverRequestBo>();
3304         List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
3305         Engine engine = KrmsApiServiceLocator.getEngine();
3306         ContextDefinition contextDefinition = KrmsRepositoryServiceLocator.getContextBoService().getContextByNameAndNamespace("OLE-CONTEXT", "OLE");
3307         AgendaDefinition agendaDefinition = KrmsRepositoryServiceLocator.getAgendaBoService().getAgendaByNameAndContextId(OLEConstants.REQUEST_AGENDA_NM, contextDefinition.getId());
3308         HashMap<String, String> map = new HashMap<String, String>();
3309         map.put(OLEConstants.AGENDA_NAME, agendaDefinition.getName());
3310         List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
3311 
3312         SelectionCriteria selectionCriteria =
3313                 SelectionCriteria.createCriteria(null, getSelectionContext(contextDefinition.getName()), getAgendaContext(OLEConstants.REQUEST_AGENDA_NM));
3314         EngineResults engineResult = null;
3315 
3316         if (agendaDefinition != null) {
3317 
3318             ExecutionOptions executionOptions = new ExecutionOptions();
3319             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
3320 
3321             Facts.Builder factBuilder = Facts.Builder.create();
3322 
3323             String borrowerType = "";
3324             if (oleDeliverRequestBo.getOlePatron() != null && oleDeliverRequestBo.getOlePatron().getOleBorrowerType() != null) {
3325                 borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeCode();
3326             }
3327             String itemType = oleDeliverRequestBo.getItemType();
3328 
3329             String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
3330 
3331             String requestType = oleDeliverRequestBo.getRequestTypeCode();
3332 
3333             String location = oleDeliverRequestBo.getShelvingLocation();
3334             OleLoanDocument oleLoanDocument = getLoanProcessor().getOleLoanDocumentUsingItemUUID(oleDeliverRequestBo.getItemUuid());
3335             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
3336             dataCarrierService.addData(OLEConstants.LOANED_DATE, oleLoanDocument != null ? oleLoanDocument.getCreateDate() : null);
3337             dataCarrierService.addData(OLEConstants.DUE_DATE, oleLoanDocument != null ? oleLoanDocument.getLoanDueDate() : null);
3338             String patronId = oleDeliverRequestBo.getBorrowerId() != null ? oleDeliverRequestBo.getBorrowerId() : "";
3339             String itemId = oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "";
3340             dataCarrierService.removeData(patronId + itemId);
3341             String borrowerId = oleDeliverRequestBo.getBorrowerId();
3342 
3343             List<FeeType> feeTypeList = getOleCirculationPolicyService().getPatronBillPayment(oleDeliverRequestBo.getBorrowerId());
3344             Integer overdueFineAmt = 0;
3345             Integer replacementFeeAmt = 0;
3346             Integer serviceFeeAmt = 0;
3347             for (FeeType feeType : feeTypeList) {
3348                 Integer fineAmount = feeType.getFeeAmount().subtract(feeType.getPaidAmount()).intValue();
3349                 overdueFineAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.OVERDUE_FINE) ? fineAmount : 0;
3350                 replacementFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.REPLACEMENT_FEE) ? fineAmount : 0;
3351                 serviceFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.SERVICE_FEE) ? fineAmount : 0;
3352             }
3353             Map<String, String> requestMap = new HashMap<String, String>();
3354             requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
3355             if (requestTypeId != null && (requestTypeId.equals("1") || requestTypeId.equals("2"))) {
3356                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
3357                 recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3358                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
3359                 recallList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3360             } else if (requestTypeId != null && (requestTypeId.equals("3") || requestTypeId.equals("4"))) {
3361                 //  holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
3362                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
3363                 holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3364                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
3365                 holdList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3366             } else if (requestTypeId != null && (requestTypeId.equals("5") || requestTypeId.equals("6"))) {
3367                 // pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
3368                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
3369                 pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3370                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
3371                 pageList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3372             } else if (requestTypeId != null && (requestTypeId.equals("9"))) {
3373                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
3374                 asrList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3375             }
3376             Map<String, String> requestByBorrower = new HashMap<String, String>();
3377             requestByBorrower.put(OLEConstants.OleDeliverRequest.BORROWER_ID, borrowerId);
3378             requestsByBorrower = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestByBorrower);
3379             HashMap<String, Object> termValues = new HashMap<String, Object>();
3380             termValues.put(OLEConstants.BORROWER_TYPE, borrowerType);
3381             termValues.put(OLEConstants.ITEM_TYPE, itemType);
3382             termValues.put(OLEConstants.LOCATION, location);
3383             termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
3384             termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
3385             termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
3386             termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
3387             termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
3388             termValues.put(OLEConstants.MAX_NO_OF_RECALL_REQUEST, new Integer(recallList.size()) + 1);
3389             termValues.put(OLEConstants.MAX_NO_OF_HOLD_REQUEST, new Integer(holdList.size()) + 1);
3390             termValues.put(OLEConstants.MAX_NO_OF_PAGE_REQUEST, new Integer(pageList.size()) + 1);
3391             termValues.put(OLEConstants.MAX_NO_OF_ASR_REQUEST, new Integer(asrList.size()) + 1);
3392             termValues.put(OLEConstants.FINE_AMOUNT, overdueFineAmt + replacementFeeAmt + serviceFeeAmt);
3393             // termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
3394             // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
3395             termValues.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, requestTypeId);
3396             termValues.put(OLEConstants.REQUEST_TYPE, requestType);
3397             termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
3398             termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
3399 
3400             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
3401                 MatchBo matchBo = matchBoIterator.next();
3402                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
3403             }
3404             if (LOG.isDebugEnabled()) {
3405                 LOG.debug("termValues.toString()" + termValues.toString());
3406             }
3407             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
3408             dataCarrierService.removeData(patronId + itemId);
3409             List<String> errorMessage = (List<String>) engineResult.getAttribute(OLEConstants.ERROR_ACTION);
3410             java.sql.Date d = (java.sql.Date) engineResult.getAttribute(OLEConstants.REQ_EXPIRATION_DATE);
3411             Timestamp recallDueDate = (Timestamp) engineResult.getAttribute(OLEConstants.RECALL_DUE_DATE);
3412             String notice = (String) engineResult.getAttribute(OLEConstants.NOTICE);
3413             oleDeliverRequestBo.setNoticeType(notice);
3414             if (oleDeliverRequestBo.getRequestExpiryDate() == null) {
3415                 oleDeliverRequestBo.setRequestExpiryDate(d);
3416             }
3417             StringBuffer failures = new StringBuffer();
3418             if (errorMessage != null && errorMessage.size() > 0) {
3419                 int i = 1;
3420                 for (String errMsg : errorMessage) {
3421                     failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
3422                 }
3423             }
3424             if (!failures.toString().isEmpty()) {
3425                 oleDeliverRequestBo.setMessage(failures.toString());
3426             } else if (failures.toString().trim().isEmpty()) {
3427                 boolean overrideKRMS = true;
3428                 if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2")) {
3429                     overrideKRMS = isRecallRequestExist(oleDeliverRequestBo.getRequestTypeId(), oleDeliverRequestBo.getItemId());
3430                 }
3431                 if (overrideKRMS) {
3432                     if (oleLoanDocument != null && (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2"))) {
3433                         Timestamp itemDueDate = null;
3434                         if (ObjectUtils.isNotNull(oleLoanDocument)) {
3435                             itemDueDate = oleLoanDocument.getLoanDueDate();
3436                         }
3437                         Item oleItem = oleDeliverRequestBo.getOleItem();
3438                         if (itemDueDate == null && recallDueDate != null) {
3439                             oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
3440                             oleLoanDocument.setLoanDueDate(recallDueDate);
3441                             oleDeliverRequestBo.setRecallDueDate(recallDueDate);
3442                             oleItem.setDueDateTime(recallDueDate.toString());
3443                             getBusinessObjectService().save(oleLoanDocument);
3444                             OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
3445                                     getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
3446                             oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
3447                             OLEDeliverNoticeHelperService oleDeliverNoticeHelperService = getOleDeliverNoticeHelperService();
3448                             oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
3449                             try {
3450                                 List<OLEDeliverNotice> deliverNotices = (List<OLEDeliverNotice>) engineResult.getAttribute("deliverNotices");
3451                                 if (deliverNotices != null) {
3452                                     for (OLEDeliverNotice deliverNotice : deliverNotices) {
3453                                         deliverNotice.setLoanId(oleLoanDocument.getLoanId());
3454                                         deliverNotice.setPatronId(oleLoanDocument.getPatronId());
3455                                     }
3456                                     getBusinessObjectService().save(deliverNotices);
3457                                 }
3458                             } catch (Exception e) {
3459                                 LOG.info("Exception occured while updating the date in notice table");
3460                                 LOG.error(e, e);
3461                             }
3462                             oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate, "MM/dd/yyyy HH:mm:ss"));
3463                             try {
3464                                 updateItem(oleItem);
3465                             } catch (Exception e) {
3466                                 if (LOG.isInfoEnabled()) {
3467                                     LOG.info("Exception occured while updating the item . " + e.getMessage());
3468                                 }
3469                                 LOG.error(e, e);
3470                             }
3471                         }
3472                         if (recallDueDate != null && itemDueDate != null) {
3473                             // if(itemDueDate.compareTo(recallDueDate) > 0){
3474                             oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
3475                             oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
3476                             oleLoanDocument.setLoanDueDate(recallDueDate);
3477                             oleDeliverRequestBo.setRecallDueDate(recallDueDate);
3478                             getBusinessObjectService().save(oleLoanDocument);
3479                             OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
3480                                     getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
3481                             oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
3482                             OLEDeliverNoticeHelperService oleDeliverNoticeHelperService = getOleDeliverNoticeHelperService();
3483                             oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
3484                             try {
3485                                 List<OLEDeliverNotice> deliverNotices = (List<OLEDeliverNotice>) engineResult.getAttribute("deliverNotices");
3486                                 if (deliverNotices != null) {
3487                                     for (OLEDeliverNotice deliverNotice : deliverNotices) {
3488                                         deliverNotice.setLoanId(oleLoanDocument.getLoanId());
3489                                         deliverNotice.setPatronId(oleLoanDocument.getPatronId());
3490                                     }
3491                                     getBusinessObjectService().save(deliverNotices);
3492                                 }
3493                             } catch (Exception e) {
3494                                 LOG.info("Exception occured while updating the date in notice table");
3495                                 LOG.error(e, e);
3496                             }
3497                             oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate, "MM/dd/yyyy HH:mm:ss"));
3498                             try {
3499                                 updateItem(oleItem);
3500                             } catch (Exception e) {
3501                                 if (LOG.isInfoEnabled()) {
3502                                     LOG.info("Exception occured while updating the item . " + e.getMessage());
3503                                 }
3504                                 LOG.error(e, e);
3505                             }
3506                        /* }else{
3507                             oleDeliverRequestBo.setNewDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
3508                             oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
3509                         }*/
3510                         }
3511                     }
3512                 }
3513             }
3514             dataCarrierService.addData(OLEConstants.ERROR_ACTION, null);
3515         }
3516         return engineResult;
3517     }
3518 
3519 
3520     public EngineResults executeEngineResultsForOverride(OleDeliverRequestBo oleDeliverRequestBo) {
3521         List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
3522         List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
3523         List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
3524         List<OleDeliverRequestBo> asrList = new ArrayList<OleDeliverRequestBo>();
3525         List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
3526         Engine engine = KrmsApiServiceLocator.getEngine();
3527         ContextDefinition contextDefinition = KrmsRepositoryServiceLocator.getContextBoService().getContextByNameAndNamespace("OLE-CONTEXT", "OLE");
3528         AgendaDefinition agendaDefinition = KrmsRepositoryServiceLocator.getAgendaBoService().getAgendaByNameAndContextId(OLEConstants.REQUEST_AGENDA_NM, contextDefinition.getId());
3529         HashMap<String, String> map = new HashMap<String, String>();
3530         map.put(OLEConstants.AGENDA_NAME, agendaDefinition.getName());
3531         List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
3532 
3533         SelectionCriteria selectionCriteria =
3534                 SelectionCriteria.createCriteria(null, getSelectionContext(contextDefinition.getName()), getAgendaContext(OLEConstants.REQUEST_AGENDA_NM));
3535         EngineResults engineResult = null;
3536 
3537         if (agendaDefinition != null) {
3538 
3539             ExecutionOptions executionOptions = new ExecutionOptions();
3540             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
3541 
3542             Facts.Builder factBuilder = Facts.Builder.create();
3543 
3544             String borrowerType = "";
3545             if (oleDeliverRequestBo.getOlePatron() != null && oleDeliverRequestBo.getOlePatron().getOleBorrowerType() != null) {
3546                 borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeCode();
3547             }
3548             String itemType = oleDeliverRequestBo.getItemType();
3549 
3550             String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
3551 
3552             String requestType = oleDeliverRequestBo.getRequestTypeCode();
3553 
3554             String location = oleDeliverRequestBo.getShelvingLocation();
3555             OleLoanDocument oleLoanDocument = getLoanProcessor().getOleLoanDocumentUsingItemUUID(oleDeliverRequestBo.getItemUuid());
3556             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
3557             dataCarrierService.addData(OLEConstants.LOANED_DATE, oleLoanDocument != null ? oleLoanDocument.getCreateDate() : null);
3558             dataCarrierService.addData(OLEConstants.DUE_DATE, oleLoanDocument != null ? oleLoanDocument.getLoanDueDate() : null);
3559             String patronId = oleDeliverRequestBo.getBorrowerId() != null ? oleDeliverRequestBo.getBorrowerId() : "";
3560             String itemId = oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "";
3561             dataCarrierService.removeData(patronId + itemId);
3562             String borrowerId = oleDeliverRequestBo.getBorrowerId();
3563 
3564             List<FeeType> feeTypeList = getOleCirculationPolicyService().getPatronBillPayment(oleDeliverRequestBo.getBorrowerId());
3565             Integer overdueFineAmt = 0;
3566             Integer replacementFeeAmt = 0;
3567             Integer serviceFeeAmt = 0;
3568             for (FeeType feeType : feeTypeList) {
3569                 Integer fineAmount = feeType.getFeeAmount().subtract(feeType.getPaidAmount()).intValue();
3570                 overdueFineAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.OVERDUE_FINE) ? fineAmount : 0;
3571                 replacementFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.REPLACEMENT_FEE) ? fineAmount : 0;
3572                 serviceFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.SERVICE_FEE) ? fineAmount : 0;
3573             }
3574             Map<String, String> requestMap = new HashMap<String, String>();
3575             requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
3576             if (requestTypeId != null && (requestTypeId.equals("1") || requestTypeId.equals("2"))) {
3577                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
3578                 recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3579                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
3580                 recallList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3581             } else if (requestTypeId != null && (requestTypeId.equals("3") || requestTypeId.equals("4"))) {
3582                 //  holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
3583                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
3584                 holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3585                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
3586                 holdList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3587             } else if (requestTypeId != null && (requestTypeId.equals("5") || requestTypeId.equals("6"))) {
3588                 // pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
3589                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
3590                 pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
3591                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
3592                 pageList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3593             } else if (requestTypeId != null && (requestTypeId.equals("9"))) {
3594                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
3595                 asrList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
3596             }
3597             Map<String, String> requestByBorrower = new HashMap<String, String>();
3598             requestByBorrower.put(OLEConstants.OleDeliverRequest.BORROWER_ID, borrowerId);
3599             requestsByBorrower = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestByBorrower);
3600             HashMap<String, Object> termValues = new HashMap<String, Object>();
3601             termValues.put(OLEConstants.BORROWER_TYPE, borrowerType);
3602             termValues.put(OLEConstants.ITEM_TYPE, itemType);
3603             termValues.put(OLEConstants.LOCATION, location);
3604             termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
3605             termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
3606             termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
3607             termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
3608             termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
3609             termValues.put(OLEConstants.MAX_NO_OF_RECALL_REQUEST, new Integer(recallList.size()) + 1);
3610             termValues.put(OLEConstants.MAX_NO_OF_HOLD_REQUEST, new Integer(holdList.size()) + 1);
3611             termValues.put(OLEConstants.MAX_NO_OF_PAGE_REQUEST, new Integer(pageList.size()) + 1);
3612             termValues.put(OLEConstants.MAX_NO_OF_ASR_REQUEST, new Integer(asrList.size()) + 1);
3613             termValues.put(OLEConstants.FINE_AMOUNT, overdueFineAmt + replacementFeeAmt + serviceFeeAmt);
3614             // termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
3615             // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
3616             termValues.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, requestTypeId);
3617             termValues.put(OLEConstants.REQUEST_TYPE, requestType);
3618             termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
3619             termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
3620 
3621             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
3622                 MatchBo matchBo = matchBoIterator.next();
3623                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
3624             }
3625             if (LOG.isDebugEnabled()) {
3626                 LOG.debug("termValues.toString()" + termValues.toString());
3627             }
3628             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
3629             dataCarrierService.removeData(patronId + itemId);
3630             List<String> errorMessage = (List<String>) engineResult.getAttribute(OLEConstants.ERROR_ACTION);
3631             java.sql.Date d = (java.sql.Date) engineResult.getAttribute(OLEConstants.REQ_EXPIRATION_DATE);
3632             Timestamp recallDueDate = (Timestamp) engineResult.getAttribute(OLEConstants.RECALL_DUE_DATE);
3633             String notice = (String) engineResult.getAttribute(OLEConstants.NOTICE);
3634             oleDeliverRequestBo.setNoticeType(notice);
3635             if (oleDeliverRequestBo.getRequestExpiryDate() == null) {
3636                 oleDeliverRequestBo.setRequestExpiryDate(d);
3637             }
3638             StringBuffer failures = new StringBuffer();
3639 
3640 
3641             boolean overrideKRMS = true;
3642             if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2")) {
3643                 overrideKRMS = isRecallRequestExist(oleDeliverRequestBo.getRequestTypeId(), oleDeliverRequestBo.getItemId());
3644             }
3645             if (overrideKRMS) {
3646                 if (oleLoanDocument != null && (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2"))) {
3647                     Timestamp itemDueDate = null;
3648                     if (ObjectUtils.isNotNull(oleLoanDocument)) {
3649                         itemDueDate = oleLoanDocument.getLoanDueDate();
3650                     }
3651                     Item oleItem = oleDeliverRequestBo.getOleItem();
3652                     if (itemDueDate == null && recallDueDate != null) {
3653                         oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
3654                         oleLoanDocument.setLoanDueDate(recallDueDate);
3655                         oleDeliverRequestBo.setRecallDueDate(recallDueDate);
3656                         oleItem.setDueDateTime(recallDueDate.toString());
3657                         getBusinessObjectService().save(oleLoanDocument);
3658                         OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
3659                                 getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
3660                         oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
3661                         OLEDeliverNoticeHelperService oleDeliverNoticeHelperService = getOleDeliverNoticeHelperService();
3662                         oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
3663                         try {
3664                             List<OLEDeliverNotice> deliverNotices = (List<OLEDeliverNotice>) engineResult.getAttribute("deliverNotices");
3665                             if (deliverNotices != null) {
3666                                 for (OLEDeliverNotice deliverNotice : deliverNotices) {
3667                                     deliverNotice.setLoanId(oleLoanDocument.getLoanId());
3668                                     deliverNotice.setPatronId(oleLoanDocument.getPatronId());
3669                                 }
3670                                 getBusinessObjectService().save(deliverNotices);
3671                             }
3672                         } catch (Exception e) {
3673                             LOG.info("Exception occured while updating the date in notice table");
3674                             LOG.error(e, e);
3675                         }
3676                         oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate, "MM/dd/yyyy HH:mm:ss"));
3677                         try {
3678                             updateItem(oleItem);
3679                         } catch (Exception e) {
3680                             if (LOG.isInfoEnabled()) {
3681                                 LOG.info("Exception occured while updating the item . " + e.getMessage());
3682                             }
3683                             LOG.error(e, e);
3684                         }
3685                     }
3686                     if (recallDueDate != null && itemDueDate != null) {
3687                         // if(itemDueDate.compareTo(recallDueDate) > 0){
3688                         oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
3689                         oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
3690                         oleLoanDocument.setLoanDueDate(recallDueDate);
3691                         oleDeliverRequestBo.setRecallDueDate(recallDueDate);
3692                         getBusinessObjectService().save(oleLoanDocument);
3693                         OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
3694                                 getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
3695                         oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
3696                         OLEDeliverNoticeHelperService oleDeliverNoticeHelperService = getOleDeliverNoticeHelperService();
3697                         oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
3698                         try {
3699                             List<OLEDeliverNotice> deliverNotices = (List<OLEDeliverNotice>) engineResult.getAttribute("deliverNotices");
3700                             if (deliverNotices != null) {
3701                                 for (OLEDeliverNotice deliverNotice : deliverNotices) {
3702                                     deliverNotice.setLoanId(oleLoanDocument.getLoanId());
3703                                     deliverNotice.setPatronId(oleLoanDocument.getPatronId());
3704                                 }
3705                                 getBusinessObjectService().save(deliverNotices);
3706                             }
3707                         } catch (Exception e) {
3708                             LOG.info("Exception occured while updating the date in notice table");
3709                             LOG.error(e, e);
3710                         }
3711                         oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate, "MM/dd/yyyy HH:mm:ss"));
3712                         try {
3713                             updateItem(oleItem);
3714                         } catch (Exception e) {
3715                             if (LOG.isInfoEnabled()) {
3716                                 LOG.info("Exception occured while updating the item . " + e.getMessage());
3717                             }
3718                             LOG.error(e, e);
3719                         }
3720 
3721                     }
3722                 }
3723             }
3724 
3725             dataCarrierService.addData(OLEConstants.ERROR_ACTION, null);
3726         }
3727         return engineResult;
3728     }
3729 
3730     /**
3731      * This method returns SelectionContext using contextName.
3732      *
3733      * @param contextName
3734      * @return Map
3735      */
3736     protected Map<String, String> getSelectionContext(String contextName) {
3737         Map<String, String> selector = new HashMap<String, String>();
3738         selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
3739         selector.put(NAME_SELECTOR, contextName);
3740         return selector;
3741     }
3742 
3743     /**
3744      * This method returns AgendaContext using agendaName..
3745      *
3746      * @param agendaName
3747      * @return Map
3748      */
3749     protected Map<String, String> getAgendaContext(String agendaName) {
3750         Map<String, String> selector = new HashMap<String, String>();
3751         selector.put(NAME_SELECTOR, agendaName);
3752         return selector;
3753     }
3754 
3755     public OleCirculationDesk getOleCirculationDesk(String circulationDeskId) {
3756         Map<String, String> circulationDeskMap = new HashMap<String, String>();
3757         circulationDeskMap.put(OLEConstants.CIRCULATION_DESK_ID, circulationDeskId);
3758         List<OleCirculationDesk> oleCirculationDeskList = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, circulationDeskMap);
3759         if (oleCirculationDeskList != null && oleCirculationDeskList.size() > 0) {
3760             return oleCirculationDeskList.get(0);
3761         } else
3762             return null;
3763     }
3764 
3765     private RoleService getRoleService() {
3766         RoleService service = KimApiServiceLocator.getRoleService();
3767         return service;
3768     }
3769 
3770     public boolean checkForOverdueNotice(Date expDate) {
3771         Date curDat = new Date();
3772         if (expDate != null && curDat.compareTo(expDate) <= 0) {
3773             return false;
3774         }
3775         return true;
3776     }
3777 
3778 
3779 
3780 
3781 
3782     public org.kuali.ole.docstore.common.document.Item retrieveItemWithBibAndHoldingData(String itemUUID) {
3783         org.kuali.ole.docstore.common.document.Item item = null;
3784         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
3785         HoldingOlemlRecordProcessor holdingsOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
3786         try {
3787             //retrieve the item information from docstore
3788             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
3789             //retrieve item content
3790             Item item1 = itemOlemlRecordProcessor.fromXML(item.getContent());
3791             item = populateInfoFromInstanceItemToDocItem(item1, item);
3792             OleHoldings oleHoldings = holdingsOlemlRecordProcessor.fromXML(item.getHolding().getContent());
3793             Holdings holdings = populateInfoFromInstanceHoldingToDocHoldings(oleHoldings, item.getHolding());
3794             item.setHolding(holdings);
3795         } catch (Exception e) {
3796             LOG.error(e);
3797         }
3798         return item;
3799     }
3800 
3801 
3802     public org.kuali.ole.docstore.common.document.Item populateInfoFromInstanceItemToDocItem(Item instanceItem, org.kuali.ole.docstore.common.document.Item documentItem) {
3803 
3804         documentItem.setBarcode(instanceItem.getAccessInformation().getBarcode());
3805         documentItem.setAnalytic(Boolean.valueOf(instanceItem.getAnalytic()));
3806         if (instanceItem.getCallNumber() != null) {
3807             documentItem.setCallNumber(instanceItem.getCallNumber().getNumber());
3808             documentItem.setCallNumberType(instanceItem.getCallNumber().getType());
3809             documentItem.setCallNumberPrefix(instanceItem.getCallNumber().getPrefix());
3810         }
3811         documentItem.setChronology(instanceItem.getChronology());
3812         documentItem.setCopyNumber(instanceItem.getCopyNumber());
3813         if (instanceItem.getItemStatus() != null) {
3814             documentItem.setItemStatus(instanceItem.getItemStatus().getCodeValue());
3815         }
3816         if (instanceItem.getItemType() != null) {
3817             documentItem.setItemType(instanceItem.getItemType().getCodeValue());
3818         }
3819         documentItem.setEnumeration(instanceItem.getEnumeration());
3820         documentItem.setVolumeNumber(instanceItem.getVolumeNumber());
3821 
3822         return documentItem;
3823     }
3824 
3825     public org.kuali.ole.docstore.common.document.Holdings populateInfoFromInstanceHoldingToDocHoldings(OleHoldings oleHoldings, Holdings holdings) {
3826         if (oleHoldings.getCallNumber() != null) {
3827             holdings.setCallNumber(oleHoldings.getCallNumber().getNumber());
3828             holdings.setCallNumberPrefix(oleHoldings.getCallNumber().getPrefix());
3829             holdings.setCallNumberType(oleHoldings.getCallNumber().getType());
3830         }
3831         holdings.setCopyNumber(oleHoldings.getCopyNumber());
3832         holdings.setHoldingsType(oleHoldings.getHoldingsType());
3833         //  holdings.setLocationName(getLocation(oleHoldings.getLocation()));
3834         return holdings;
3835     }
3836 
3837 
3838     public Map retrieveBIbItemHoldingData(String itemUUID) {
3839         Map<String, Object> bibMap = new HashMap<String, Object>();
3840         org.kuali.ole.docstore.common.document.Item item = null;
3841         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
3842         HoldingOlemlRecordProcessor holdingsOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
3843         try {
3844             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID); // retrieving item object using itemUUID.
3845             bibMap.put(OLEConstants.DOCUMENT_ITEM, item);
3846             bibMap.put(OLEConstants.BIB, item.getHolding().getBib()); // retrieving bib object from holding.
3847             Item item1 = itemOlemlRecordProcessor.fromXML(item.getContent());
3848             bibMap.put(OLEConstants.ITEM, item1);
3849             OleHoldings oleHoldings = holdingsOlemlRecordProcessor.fromXML(item.getHolding().getContent());
3850             bibMap.put(OLEConstants.HOLDING, oleHoldings); // retrieving holding object.
3851         } catch (Exception e) {
3852             LOG.error(e);
3853         }
3854         return bibMap; // set all the objects in Map.
3855     }
3856 
3857     private void getNoticeList(List<OleLoanDocument> oleLoanDocuments, OlePatronDocument olePatronDocument, boolean overdue, List<String> itemUUIDS) {
3858         Long b1 = System.currentTimeMillis();
3859         List<OleLoanDocument> oleOverDueNoticeBoList = new ArrayList<>();
3860         List<OleLoanDocument> oleCourtesyNoticeList = new ArrayList<>();
3861         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
3862         StringBuffer mailContent = new StringBuffer();
3863         Document document = null;
3864         OutputStream outputStream = null;
3865         Set<String> overdueItemLocations = new HashSet<>();
3866         Set<String> courtesyItemLocations = new HashSet<>();
3867         try {
3868             String overdueNoticeType = getLoanProcessor().getParameter(OLEParameterConstants.OVERDUE_NOTICE_TYPE);
3869             String courtesyNoticeType = getLoanProcessor().getParameter(OLEParameterConstants.COURTESY_NOTICE_TYPE);
3870             mailContent.append(oleDeliverBatchService.getHeaderAndPatronContent(olePatronDocument, overdue));
3871             oleDeliverBatchService.getHeaderAndPatronPDFContent(olePatronDocument, overdue);
3872             document = oleDeliverBatchService.getOverdueDocument();
3873             outputStream = oleDeliverBatchService.getOverdueOutPutStream();
3874             for (OleLoanDocument oleLoanDocument : oleLoanDocuments) {
3875                 boolean overdueExists = false;
3876                 oleLoanDocument.setOlePatron(olePatronDocument);
3877                 if (LOG.isInfoEnabled()) {
3878                     LOG.info("oleLoanDocument---->ItemID--" + oleLoanDocument.getItemId() + ": Patron Barcode--" + oleLoanDocument.getPatronBarcode());
3879                     LOG.info("oleItem.getItemStatusEffectiveDate()" + oleLoanDocument.getItemStatusEffectiveDate());
3880                 }
3881                 if (oleLoanDocument.getItemTypeName() != null) {
3882                     oleLoanDocument.setItemType(getItemTypeCodeByName(oleLoanDocument.getItemTypeName()));
3883                 }
3884                 for (OLEDeliverNotice oleDeliverNotice : oleLoanDocument.getDeliverNotices()) {
3885                     String noticeType = oleDeliverNotice.getNoticeType();
3886                     if (oleLoanDocument.getReplacementBill() != null && oleLoanDocument.getReplacementBill().intValue() > 0 && noticeType.equalsIgnoreCase(OLEConstants.NOTICE_LOST)) {
3887                         int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
3888                         noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
3889                         oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
3890                         oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
3891                         String billNumber = getLoanProcessor().generatePatronBillPayment(oleLoanDocument, OLEConstants.REPLACEMENT_FEE, oleLoanDocument.getReplacementBill());
3892                         oleLoanDocument.setRepaymentFeePatronBillId(billNumber);
3893                         itemUUIDS.add(oleLoanDocument.getItemUuid());
3894                         getBusinessObjectService().delete(oleDeliverNotice);
3895                     }
3896                     if (noticeType.equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
3897                         oleOverDueNoticeBoList.add(oleLoanDocument);
3898                         if (!overdueExists) {
3899                             mailContent.append(oleDeliverBatchService.getOverdueNoticeHTMLContent(oleLoanDocument));
3900                         }
3901                         overdueItemLocations.add(oleLoanDocument.getItemLocation());
3902                         noticeType = noticeType == null ? overdueNoticeType : noticeType;
3903                         if (!overdueExists) {
3904                             oleDeliverBatchService.getOverdueNoticePDFContent(oleLoanDocument, overdue, document);
3905                         }
3906                         int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
3907                         noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
3908                         if (LOG.isDebugEnabled()) {
3909                             LOG.debug("Updated Loan Record : " + oleLoanDocument);
3910                         }
3911                         oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
3912                         oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
3913                         overdueExists = true;
3914                         getBusinessObjectService().delete(oleDeliverNotice);
3915                     } else if (noticeType.equalsIgnoreCase(OLEConstants.NOTICE_COURTESY) && olePatronDocument.isCourtesyNotice() && !oleLoanDocument.isCourtesyNoticeFlag()) {
3916                         oleCourtesyNoticeList.add(oleLoanDocument);
3917                         mailContent.append(oleDeliverBatchService.getOverdueNoticeHTMLContent(oleLoanDocument));
3918                         courtesyItemLocations.add(oleLoanDocument.getItemLocation());
3919                         oleDeliverBatchService.getOverdueNoticePDFContent(oleLoanDocument, overdue, document);
3920                         noticeType = noticeType == null ? courtesyNoticeType : noticeType;
3921                         oleLoanDocument.setCourtesyNoticeFlag(!overdue);
3922                         getBusinessObjectService().delete(oleDeliverNotice);
3923                     }
3924 
3925                     olePatronDocument = oleLoanDocument.getOlePatron();
3926                     if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
3927                         //TODO : sms in progress.
3928                     }
3929                 }
3930                 getBusinessObjectService().save(oleLoanDocument);
3931                 saveOLEDeliverNoticeHistory(oleLoanDocument);
3932             }
3933 
3934         } catch (Exception e) {
3935             LOG.error("Exception in generateNotices()" + e.getMessage(), e);
3936         }
3937         Long b2 = System.currentTimeMillis();
3938         Long b3 = b2 - b1;
3939         LOG.info("Time taken to send the notices " + b3);
3940         boolean isFileNeedToDelete = true;
3941         if (overdue) {
3942             if (oleOverDueNoticeBoList != null && oleOverDueNoticeBoList.size() > 0) {
3943                 String replyToEmail = null;
3944                 if (overdueItemLocations.size() == 1) {
3945                     replyToEmail = getCircDeskLocationResolver().getReplyToEmail(overdueItemLocations.iterator().next());
3946                 }
3947                 if (replyToEmail != null) {
3948                     sendMailsToPatron(olePatronDocument, mailContent.toString(), replyToEmail);
3949                 } else {
3950                     String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
3951                     sendMailsToPatron(olePatronDocument, mailContent.toString(), fromAddress);
3952                 }
3953                 try {
3954                     if (document != null && outputStream != null) {
3955                         oleDeliverBatchService.getPdfFooter(document, outputStream);
3956                         isFileNeedToDelete = false;
3957                     }
3958                 } catch (Exception e) {
3959                     LOG.error("PDF overdue notice error");
3960                 }
3961 
3962             }
3963         } else {
3964             if (oleCourtesyNoticeList != null && oleCourtesyNoticeList.size() > 0) {
3965                 String replyToEmail = null;
3966                 if (courtesyItemLocations.size() == 1) {
3967                     replyToEmail = getCircDeskLocationResolver().getReplyToEmail(courtesyItemLocations.iterator().next());
3968                 }
3969                 if (replyToEmail != null) {
3970                     sendMailsToPatron(olePatronDocument, mailContent.toString(), replyToEmail);
3971                 } else {
3972                     String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
3973                     sendMailsToPatron(olePatronDocument, mailContent.toString(), fromAddress);
3974                 }
3975                 try {
3976                     if (document != null && outputStream != null) {
3977                         oleDeliverBatchService.getPdfFooter(document, outputStream);
3978                         isFileNeedToDelete = false;
3979                     }
3980                 } catch (Exception e) {
3981                     LOG.error("PDF courtesy notice error");
3982                 }
3983             }
3984         }
3985         if (isFileNeedToDelete) {
3986             oleDeliverBatchService.cleanZeroByteFiles();
3987         }
3988     }
3989 
3990     public void sendMailsToPatron(OlePatronDocument olePatronDocument, String noticeContent, String fromAddress) {
3991 
3992         Long b1 = System.currentTimeMillis();
3993         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
3994         String emailAddress = "";
3995         try {
3996             EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
3997             emailAddress = getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "";
3998         } catch (Exception e) {
3999             LOG.error("Unable to get Patron Email Address --sendMailsToPatron--" + e.getMessage(), e);
4000         }
4001         try {
4002             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
4003                 fromAddress = OLEConstants.KUALI_MAIL;
4004             }
4005             //   oleDeliverBatchService.generatePdfForOverdueCourtesyNotice(oleLoanDocuments,true,olePatronDocument);
4006             if (emailAddress != null && !emailAddress.isEmpty()) {
4007                 noticeContent = noticeContent.replace('[', ' ');
4008                 noticeContent = noticeContent.replace(']', ' ');
4009                 if (!noticeContent.trim().equals("")) {
4010                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
4011                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(emailAddress), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(noticeContent), true);
4012                 }
4013             } else {
4014                 LOG.error("Patron Email Address --sendMailsToPatron-- is Empty or Null");
4015             }
4016         } catch (Exception e) {
4017             LOG.error("Exception in generateNotices()" + e.getMessage(), e);
4018         }
4019         Long b2 = System.currentTimeMillis();
4020         Long total = b2 - b1;
4021         LOG.info("The time taken sending mail :" + total);
4022     }
4023 
4024     /**
4025      * This method is used to set the item information in the loan documents
4026      *
4027      * @param oleLoanDocuments
4028      * @return
4029      */
4030     public List<OleLoanDocument> getLoanDocumentWithItemInfo(List<OleLoanDocument> oleLoanDocuments) throws Exception {
4031         Long startTime = System.currentTimeMillis();
4032         List<OleLoanDocument> loanDocumentsWithItemInfo = new ArrayList<OleLoanDocument>();
4033         if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
4034             Map<String, OleLoanDocument> loanDocumentMap = new HashMap<String, OleLoanDocument>();
4035             SearchParams searchParams = new SearchParams();
4036             List<SearchCondition> searchConditions = new ArrayList<>();
4037             SearchResponse searchResponse = new SearchResponse();
4038             String numberOfRecords = getLoanProcessor().getParameter(OLEConstants.NUMBER_OF_ITEM_INFO);
4039             List<List<OleLoanDocument>> slicedList = (List<List<OleLoanDocument>>) splitListToSubList(oleLoanDocuments, Integer.valueOf(numberOfRecords).intValue());
4040             for (List<OleLoanDocument> oleLoanDocumentList : slicedList) {
4041                 try {
4042                     searchConditions = new ArrayList<>();
4043                     searchResponse = new SearchResponse();
4044                     searchParams = new SearchParams();
4045                     for (OleLoanDocument oleLoanDocument : oleLoanDocumentList) {
4046                         loanDocumentMap.put(oleLoanDocument.getItemUuid(), oleLoanDocument);
4047                         searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField("item", "id", oleLoanDocument.getItemUuid()), "OR"));
4048                     }
4049                     searchParams.setPageSize(Integer.parseInt(OLEConstants.MAX_PAGE_SIZE_FOR_LOAN));
4050                     buildSearchParams(searchParams);
4051                     searchParams.getSearchConditions().addAll(searchConditions);
4052                     try {
4053                         searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
4054                     } catch (Exception e) {
4055                         LOG.error(e, e);
4056                         throw new Exception("Exception occured while fetching data from solr");
4057                     }
4058                     try {
4059                         List<OleLoanDocument> processedLoanDocuments = buildSearchResultsFields(searchResponse, loanDocumentMap);
4060                         loanDocumentsWithItemInfo.addAll(processedLoanDocuments);
4061                     } catch (Exception e) {
4062                         LOG.error(e, e);
4063                         throw new Exception("Exception occured while setting the item information to loan documents");
4064                     }
4065                 } catch (Exception e) {
4066                     LOG.info("Exception occured while setting the item information to the loan documents");
4067                     LOG.error(e, e);
4068                 }
4069             }
4070         }
4071         Long endTime = System.currentTimeMillis();
4072         Long timeDifference = endTime - startTime;
4073         LOG.info("Time Taken to set the item information in the loan records in milliseconds : " + timeDifference);
4074         return loanDocumentsWithItemInfo;
4075     }
4076 
4077     /**
4078      * This method is used to set the values from the docstore response
4079      *
4080      * @param searchResponse
4081      * @param loanDocumentMap
4082      * @return
4083      * @throws Exception
4084      */
4085     public List<OleLoanDocument> buildSearchResultsFields(SearchResponse searchResponse, Map<String, OleLoanDocument> loanDocumentMap) throws Exception {
4086         int count = 0;
4087         Map<String, String> itemTypeNameMap = new HashMap<String, String>();
4088         List<OleInstanceItemType> instanceItemTypeList = (List<OleInstanceItemType>) getBusinessObjectService().findAll(OleInstanceItemType.class);
4089         if (instanceItemTypeList != null && instanceItemTypeList.size() > 0) {
4090             for (OleInstanceItemType oleInstanceItemType : instanceItemTypeList) {
4091                 itemTypeNameMap.put(oleInstanceItemType.getInstanceItemTypeName(), oleInstanceItemType.getInstanceItemTypeCode());
4092             }
4093         }
4094         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
4095         List<OleLoanDocument> oleLoanDocuments = new ArrayList<>();
4096         if (searchResponse != null) {
4097             for (SearchResult searchResult : searchResponse.getSearchResults()) {
4098                 try {
4099                     OleLoanDocument oleLoanDocument = null;
4100                     boolean found = false;
4101                     for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
4102                         if (searchResultField.getFieldValue() != null) {
4103                             if (searchResultField.getFieldName().equalsIgnoreCase("id")) {
4104                                 found = loanDocumentMap.containsKey(searchResultField.getFieldValue());
4105                             }
4106                             if (found) {
4107                                 if (searchResultField.getFieldName().equalsIgnoreCase("id")) {
4108                                     oleLoanDocument = loanDocumentMap.get(searchResultField.getFieldValue());
4109                                     oleLoanDocument.setItemUuid(searchResultField.getFieldValue());
4110                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ItemBarcode_display")) {
4111                                     oleLoanDocument.setItemId(searchResultField.getFieldValue());
4112                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("bibIdentifier")) {
4113                                     oleLoanDocument.setBibUuid(searchResultField.getFieldValue());
4114                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("Title_display")) {
4115                                     oleLoanDocument.setTitle(searchResultField.getFieldValue());
4116                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("Author_display")) {
4117                                     oleLoanDocument.setAuthor(searchResultField.getFieldValue());
4118                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("holdingsIdentifier")) {
4119                                     oleLoanDocument.setInstanceUuid(searchResultField.getFieldValue());
4120                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedNote")) {
4121                                     oleLoanDocument.setClaimsReturnNote(searchResultField.getFieldValue());
4122                                     //  count++;
4123                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ClaimsReturnedFlag_display") && searchResultField.getFieldValue().equalsIgnoreCase("true")) {
4124                                     oleLoanDocument.setClaimsReturnedIndicator(true);
4125                                     count++;
4126                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("Location_display")) {
4127                                     getLoanProcessor().getLocationBySolr(searchResultField, oleLoanDocument);
4128                                     oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
4129                                     Map<String, String> locationMap = getCircDeskLocationResolver().getLocationMap(oleLoanDocument.getItemFullLocation());
4130                                     oleLoanDocument.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
4131                                     oleLoanDocument.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
4132                                     oleLoanDocument.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
4133                                     oleLoanDocument.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
4134                                     oleLoanDocument.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
4135 
4136                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsLocation_search") &&
4137                                         (oleLoanDocument.getItemLocation() == null || oleLoanDocument.getItemLocation().isEmpty())) {
4138                                     getLoanProcessor().getLocationBySolr(searchResultField, oleLoanDocument);
4139                                     oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
4140                                     Map<String, String> locationMap = getCircDeskLocationResolver().getLocationMap(oleLoanDocument.getItemFullLocation());
4141                                     oleLoanDocument.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
4142                                     oleLoanDocument.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
4143                                     oleLoanDocument.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
4144                                     oleLoanDocument.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
4145                                     oleLoanDocument.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
4146 
4147                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedFlagCreateDate")) {
4148                                     String[] formatStrings = new String[]{"MM/dd/yyyy hh:mm:ss", "MM/dd/yyyy", "yyyy-MM-dd hh:mm:ss"};
4149                                     Date date = getLoanProcessor().tryParse(formatStrings, searchResultField.getFieldValue());
4150                                     oleLoanDocument.setClaimsReturnedDate(new Timestamp(date.getTime()));
4151 
4152                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("CallNumber_display")) {
4153                                     oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
4154                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("TemporaryItemTypeFullValue_search")) {
4155                                     oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
4156                                     oleLoanDocument.setItemType(itemTypeNameMap.get(oleLoanDocument.getItemTypeName()));
4157                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ItemTypeFullValue_display") &&
4158                                         (oleLoanDocument.getItemTypeName() == null || oleLoanDocument.getItemTypeName().isEmpty())) {
4159                                     oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
4160                                     oleLoanDocument.setItemType(itemTypeNameMap.get(oleLoanDocument.getItemTypeName()));
4161                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("Enumeration_display")) {
4162                                     oleLoanDocument.setEnumeration(searchResultField.getFieldValue());
4163                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("Chronology_display")) {
4164                                     oleLoanDocument.setChronology(searchResultField.getFieldValue());
4165                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ItemStatus_display")) {
4166                                     oleLoanDocument.setItemStatus(searchResultField.getFieldValue());
4167                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ItemDamagedStatus_display")) {
4168                                     oleLoanDocument.setItemDamagedStatus(searchResultField.getFieldValue().equalsIgnoreCase("true"));
4169                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("DamagedItemNote_search")) {
4170                                     oleLoanDocument.setItemDamagedNote(searchResultField.getFieldValue());
4171                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlagNote_search")) {
4172                                     oleLoanDocument.setMissingPieceNote(searchResultField.getFieldValue());
4173                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlag_display")) {
4174                                     oleLoanDocument.setMissingPieceFlag(searchResultField.getFieldValue().equalsIgnoreCase("true"));
4175                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("CopyNumber_search")) {
4176                                     oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
4177                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCopyNumber_search") &&
4178                                         (oleLoanDocument.getItemCopyNumber() == null || oleLoanDocument.getItemCopyNumber().isEmpty())) {
4179                                     oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
4180                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCallNumber_search") &&
4181                                         (oleLoanDocument.getItemCallNumber() == null || oleLoanDocument.getItemCallNumber().isEmpty())) {
4182                                     oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
4183                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceCount_search")) {
4184                                     oleLoanDocument.setMissingPiecesCount(searchResultField.getFieldValue());
4185                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("NumberOfPieces_search")) {
4186                                     oleLoanDocument.setItemNumberOfPieces(Integer.parseInt(searchResultField.getFieldValue()));
4187                                     oleLoanDocument.setBackUpNoOfPieces(searchResultField.getFieldValue());
4188                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("ClaimsReturnedFlag_search")) {
4189                                     oleLoanDocument.setClaimsReturnedIndicator(Boolean.valueOf(searchResultField.getFieldValue()));
4190                                 } else if (searchResultField.getFieldName().equalsIgnoreCase("itemStatusEffectiveDate")) {
4191                                     oleLoanDocument.setItemStatusEffectiveDate(searchResultField.getFieldValue());
4192                                     // LOG.info("Item status Effective date from solr : " + searchResultField.getFieldValue() );
4193                                 }
4194                             }
4195                         }
4196 
4197                     }
4198                     found = false;
4199                     if (oleLoanDocument.getOlePatron() != null) {
4200                         oleLoanDocument.getOlePatron().setNumberOfClaimsReturned(count);
4201                     }
4202                     oleLoanDocuments.add(oleLoanDocument);
4203                 } catch (Exception e) {
4204                     LOG.info("Exception occured while setting the item info for the loan ");
4205                 }
4206             }
4207         }
4208         return oleLoanDocuments;
4209     }
4210 
4211 
4212     public String getItemTypeCodeByName(String itemTypeName) {
4213         String itemTypeCode = "";
4214         List<OleInstanceItemType> instanceItemTypeList = null;
4215         Map<String, String> instanceItemTypeMap = new HashMap<String, String>();
4216         instanceItemTypeMap.put("instanceItemTypeName", itemTypeName);
4217         instanceItemTypeList = (List<OleInstanceItemType>) getBusinessObjectService().findMatching(OleInstanceItemType.class, instanceItemTypeMap);
4218         if (instanceItemTypeList != null && instanceItemTypeList.size() > 0) {
4219             itemTypeCode = instanceItemTypeList.get(0).getInstanceItemTypeCode();
4220         }
4221         return itemTypeCode;
4222     }
4223 
4224     /**
4225      * This method is to update the item
4226      *
4227      * @param oleItem
4228      * @throws Exception
4229      */
4230     public void updateItem(Item oleItem) throws Exception {
4231         String itemUuid = oleItem.getItemIdentifier();
4232         String itemXmlContent = getItemOlemlRecordProcessor().toXML(oleItem);
4233         try {
4234             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
4235             item.setId(itemUuid);
4236             item.setContent(itemXmlContent);
4237             item.setCategory(OLEConstants.WORK_CATEGORY);
4238             item.setType(DocType.ITEM.getCode());
4239             item.setFormat(OLEConstants.OLEML_FORMAT);
4240             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
4241         } catch (Exception e) {
4242             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
4243             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
4244         }
4245 
4246     }
4247 
4248 
4249     public List splitListToSubList(List<OleLoanDocument> parentList, int childListSize) {
4250         List<List<OleLoanDocument>> childList = new ArrayList<List<OleLoanDocument>>();
4251         List<OleLoanDocument> tempList = new ArrayList<OleLoanDocument>();
4252         int count = 0;
4253         if (parentList != null) {
4254             for (OleLoanDocument obj : parentList) {
4255                 if (count < childListSize) {
4256                     count = count + 1;
4257                     tempList.add(obj);
4258                 } else {
4259                     childList.add(tempList);
4260                     tempList = new ArrayList<OleLoanDocument>();
4261                     tempList.add(obj);
4262                     count = 1;
4263                 }
4264             }
4265             if (tempList.size() <= childListSize) {
4266                 childList.add(tempList);
4267             }
4268         }
4269         return childList;
4270     }
4271 
4272 
4273     public void buildSearchParams(SearchParams searchParams) {
4274         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "id"));
4275         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemBarcode_display"));
4276         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "bibIdentifier"));
4277         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Title_display"));
4278         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Author_display"));
4279         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "LocalId_display"));
4280         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "holdingsIdentifier"));
4281         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ClaimsReturnedFlag_display"));
4282         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedFlagCreateDate"));
4283         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedNote"));
4284         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumber_display"));
4285         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "TemporaryItemTypeFullValue_search"));
4286         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemTypeFullValue_display"));
4287         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Enumeration_display"));
4288         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Chronology_display"));
4289         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemStatus_display"));
4290         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemDamagedStatus_display"));
4291         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "DamagedItemNote_search"));
4292         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceFlagNote_search"));
4293         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Location_display"));
4294         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCopyNumber_search"));
4295         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCallNumber_search"));
4296         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsLocation_search"));
4297         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceCount_search"));
4298         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfPieces_search"));
4299         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumberPrefix_display"));
4300         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CopyNumber_search"));
4301         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "proxyBorrower"));
4302         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "VolumeNumberLabel_display"));
4303         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "dueDateTime"));
4304         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfRenew_display"));
4305         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "checkOutDateTime"));
4306         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ClaimsReturnedFlag_search"));
4307         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "itemStatusEffectiveDate"));
4308     }
4309 
4310 
4311     public void saveOLEDeliverNoticeHistory(OleLoanDocument oleLoanDocument) {
4312         for (OLEDeliverNotice oleDeliverNotice : oleLoanDocument.getDeliverNotices()) {
4313             OLEDeliverNoticeHistory oleDeliverNoticeHistory = new OLEDeliverNoticeHistory();
4314             oleDeliverNoticeHistory.setLoanId(oleLoanDocument.getLoanId());
4315             oleDeliverNoticeHistory.setNoticeType(oleDeliverNotice.getNoticeType());
4316             oleDeliverNoticeHistory.setNoticeSentDate(new Timestamp(new Date().getTime()));
4317             oleDeliverNoticeHistory.setPatronId(oleLoanDocument.getPatronId());
4318             oleDeliverNoticeHistory.setNoticeSendType(oleDeliverNotice.getNoticeSendType());
4319             getBusinessObjectService().save(oleDeliverNoticeHistory);
4320         }
4321     }
4322 
4323 
4324     private void itemStatusBulkUpdate(List<String> itemUUIDs) {
4325         List<org.kuali.ole.docstore.common.document.Item> items = null;
4326         DocstoreLocalClient docstoreLocalClient = new DocstoreLocalClient();
4327         try {
4328             items = docstoreLocalClient.retrieveItems(itemUUIDs);
4329             //items = docstoreLocalClient.retrieveItems(itemUUIDs);
4330         } catch (Exception e) {
4331             StringBuffer itemUUIDsBuffer = new StringBuffer();
4332             for (String itemUUID : itemUUIDs) {
4333                 itemUUIDsBuffer.append(itemUUID + ",");
4334             }
4335             LOG.info("Exception occured while retrieving the item for updating the item status to the following itemIds : " + itemUUIDsBuffer.toString());
4336             LOG.error(e, e);
4337         }
4338 
4339         BibTrees bibTrees = new BibTrees();
4340         for (org.kuali.ole.docstore.common.document.Item item : items) {
4341             Item oleItem = (Item) item.getContentObject();
4342             String itemXml = null;
4343             try {
4344                 itemXml = getLoanProcessor().buildItemContentWithItemStatus(oleItem, OLEConstants.ITEM_STATUS_LOST);
4345             } catch (Exception e) {
4346                 LOG.info("Exception occured while updating the item status for the item id : " + item.getId() + "and barcode : " + item.getBarcode());
4347                 LOG.error(e, e);
4348             }
4349             if (itemXml != null) {
4350                 item.setContent(itemXml);
4351                 item.setOperation(DocstoreDocument.OperationType.UPDATE);
4352                 BibTree bibTree = new BibTree();
4353                 bibTree.setBib(item.getHolding().getBib());
4354                 HoldingsTree holdingsTree = new HoldingsTree();
4355                 holdingsTree.setHoldings(item.getHolding());
4356                 holdingsTree.getItems().add(item);
4357                 bibTree.getHoldingsTrees().add(holdingsTree);
4358                 bibTrees.getBibTrees().add(bibTree);
4359             }
4360         }
4361         try {
4362             docstoreLocalClient.processBibTrees(bibTrees);
4363         } catch (Exception e) {
4364             LOG.error(e, e);
4365             StringBuffer itemUUIDsBuffer = new StringBuffer();
4366             for (String itemUUID : itemUUIDs) {
4367                 itemUUIDsBuffer.append(itemUUID + ",");
4368             }
4369             LOG.info("Exception occured while updating item status to the following itemIds : " + itemUUIDsBuffer.toString());
4370         }
4371 
4372     }
4373 
4374     public Map<String, List<String>> getItemStatusBasedOnRequestTypeMap() {
4375         String recallDeliveryRequestStatus = getLoanProcessor().getParameter(OLEConstants.RECALL_DELIVERY_ITEM_STATUS);
4376         String recallHoldRequestStatus = getLoanProcessor().getParameter(OLEConstants.RECALL_HOLD_ITEM_STATUS);
4377         String holdDeliveryRequestStatus = getLoanProcessor().getParameter(OLEConstants.HOLD_DELIVERY_ITEM_STATUS);
4378         String holdHoldRequestStatus = getLoanProcessor().getParameter(OLEConstants.HOLD_HOLD_ITEM_STATUS);
4379         String pageDeliveryRequestStatus = getLoanProcessor().getParameter(OLEConstants.PAGE_DELIVERY_ITEM_STATUS);
4380         String pageHoldRequestStatus = getLoanProcessor().getParameter(OLEConstants.PAGE_HOLD_ITEM_STATUS);
4381         String copyRequestStatus = getLoanProcessor().getParameter(OLEConstants.COPY_REQUEST_ITEM_STATUS);
4382 
4383 
4384         Set<String> recallSet = new HashSet<>();
4385         recallSet.addAll(convertArrayToList(recallDeliveryRequestStatus.split(";")));
4386         recallSet.addAll(convertArrayToList(recallHoldRequestStatus.split(";")));
4387 
4388         Set<String> holdSet = new HashSet<>();
4389         holdSet.addAll(convertArrayToList(holdDeliveryRequestStatus.split(";")));
4390         holdSet.addAll(convertArrayToList(holdHoldRequestStatus.split(";")));
4391 
4392         Set<String> pageSet = new HashSet<>();
4393         pageSet.addAll(convertArrayToList(pageDeliveryRequestStatus.split(";")));
4394         pageSet.addAll(convertArrayToList(pageHoldRequestStatus.split(";")));
4395 
4396         Map<String, List<String>> itemStatusByRequestTypeMap = new HashMap<String, List<String>>();
4397         itemStatusByRequestTypeMap.put("recall", new ArrayList<>(recallSet));
4398         itemStatusByRequestTypeMap.put("hold", new ArrayList<>(holdSet));
4399         itemStatusByRequestTypeMap.put("page", new ArrayList<>(pageSet));
4400         itemStatusByRequestTypeMap.put("copy", convertArrayToList(copyRequestStatus.split(";")));
4401 
4402         return itemStatusByRequestTypeMap;
4403     }
4404 
4405 
4406     public boolean deliverAddressExist(String patronId) throws Exception {
4407         boolean found = false;
4408         Map<String, String> criteria = new HashMap<String, String>();
4409         Map<String, String> addressCriteria = new HashMap<String, String>();
4410         criteria.put("olePatronId", patronId);
4411         List<OlePatronDocument> olePatronDocument = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePatronDocument.class, criteria);
4412         if (olePatronDocument != null && olePatronDocument.size() > 0) {
4413             List<OleAddressBo> oleAddressBos = olePatronDocument.get(0).getOleAddresses();
4414             if (oleAddressBos != null && oleAddressBos.size() > 0) {
4415                 for (int address = 0; address < oleAddressBos.size(); address++) {
4416                     if (oleAddressBos != null && oleAddressBos.size() > 0 && oleAddressBos.get(address).isDeliverAddress()) {
4417                         found = true;
4418                     }
4419                 }
4420             }
4421 
4422         }
4423         return found;
4424     }
4425 
4426 
4427     public List getPatronDocumentByPatronBarcode(String patronBarcode) throws Exception {
4428         Map barMap = new HashMap();
4429         barMap.put(OLEConstants.OlePatron.BARCODE, patronBarcode);
4430         List<OlePatronDocument> matching = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
4431         return matching;
4432     }
4433 
4434     // public void processRequestInformation
4435 
4436     public String getParameter(String name) {
4437         ParameterKey parameterKey = ParameterKey.create(OLEConstants.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, name);
4438         Parameter parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
4439         if (parameter == null) {
4440             parameterKey = ParameterKey.create(OLEConstants.APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, name);
4441             parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
4442         }
4443         return parameter != null ? parameter.getValue() : null;
4444     }
4445 
4446     private DataCarrierService dataCarrierService;
4447 
4448     public DataCarrierService getDataCarrierService() {
4449         if (dataCarrierService == null) {
4450             dataCarrierService = (DataCarrierService)SpringContext.getService("dataCarrierService");
4451         }
4452         return dataCarrierService;
4453     }
4454 
4455     public OlePatronDocument validateGeneralChecks(OlePatronDocument olePatronDocument) throws Exception {
4456 
4457         boolean isAddressVerified = false;
4458         try {
4459             isAddressVerified = (boolean) getOleCirculationPolicyService().isAddressVerified(olePatronDocument, olePatronDocument.getOlePatronId());
4460 
4461         } catch (Exception e) {
4462             // LOG.error("Exception while checking address verified & blocks", e);
4463             throw e;
4464         }
4465         String agendaName = OLEConstants.CHECK_OUT_GEN_AGENDA_NM;
4466         String digitRoutine = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE);
4467         String pattern = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE_PATTERN);
4468 
4469         HashMap<String, Object> termValues = new HashMap<String, Object>();
4470         termValues.put(OLEConstants.GENERAL_BLOCK, olePatronDocument.isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
4471         termValues.put(OLEConstants.EXPIR_DATE, olePatronDocument.getExpirationDate());
4472         termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
4473         termValues.put(OLEConstants.PATRON_BAR, olePatronDocument.getBarcode());
4474         termValues.put(OLEConstants.IS_ACTIVE_PATRON, olePatronDocument.isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
4475         termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, olePatronDocument.getActivationDate());
4476 
4477         termValues.put(OLEConstants.ACTIVATION_DATE_STRING, olePatronDocument.getActivationDate() != null ? olePatronDocument.getActivationDate().toString() : "null");
4478         termValues.put(OLEConstants.EXPIRATION_DATE_STRING, olePatronDocument.getExpirationDate() != null ? olePatronDocument.getExpirationDate().toString() : "null");
4479         termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
4480         termValues.put(OLEConstants.PATTERN, pattern);
4481 
4482         EngineResults engineResults = getEngineResults(agendaName, termValues);
4483         HashMap<String, String> errorsAndPermission = new HashMap<>();
4484         errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
4485         StringBuffer failures = new StringBuffer();
4486         olePatronDocument.getErrorsAndPermission().clear();
4487         int i = 1;
4488         if (errorsAndPermission != null) {
4489             Set<String> errorMessage = errorsAndPermission.keySet();
4490             if (errorMessage != null && errorMessage.size() > 0) {
4491                 //TODO KRMS Code Cleanup
4492                 for (String errMsg : errorMessage) {
4493                     if (StringUtils.isNotEmpty(errMsg)) {
4494                         olePatronDocument.getErrorsAndPermission().putAll(errorsAndPermission);
4495                         if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
4496                             failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
4497                             olePatronDocument.setBlockPatron(true);
4498                         } else {
4499                             if (olePatronDocument.isGeneralBlock()) {
4500                                 if (errMsg.equalsIgnoreCase(OLEConstants.GENERAL_BLOCK_MESSAGE)) {
4501                                     failures.append(i++ + ". " + errMsg + " " + OLEConstants.SEMI_COLON + " " + olePatronDocument.getGeneralBlockNotes() + OLEConstants.BREAK);
4502                                 } else {
4503                                     failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
4504                                 }
4505                             } else {
4506                                 failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
4507                             }
4508 
4509                         }
4510                     }
4511                 }
4512             }
4513             errorsAndPermission.clear();
4514         }
4515         List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
4516         if (errorMessage != null && errorMessage.size() > 0) {
4517             for (String errMsg : errorMessage) {
4518                 if (StringUtils.isNotEmpty(errMsg)) {
4519                     if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
4520                         failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
4521                         olePatronDocument.setBlockPatron(true);
4522                     } else {
4523                         failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
4524                     }
4525                 }
4526             }
4527         }
4528         if (!failures.toString().isEmpty()) {
4529             olePatronDocument.setErrorMessage(failures.toString());
4530         }
4531         getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
4532         getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
4533         return olePatronDocument;
4534     }
4535 
4536     public EngineResults getEngineResults(String agendaName, HashMap<String, Object> termValues) throws Exception {
4537         LOG.debug("Inside the getEngineResults method");
4538         EngineResults engineResult = null;
4539         try {
4540             Engine engine = KrmsApiServiceLocator.getEngine();
4541             ContextDefinition contextDefinition = KrmsRepositoryServiceLocator.getContextBoService().getContextByNameAndNamespace("OLE-CONTEXT", "OLE");
4542             AgendaDefinition agendaDefinition = KrmsRepositoryServiceLocator.getAgendaBoService().getAgendaByNameAndContextId(agendaName, contextDefinition.getId());
4543             HashMap<String, String> map = new HashMap<String, String>();
4544             map.put(OLEConstants.AGENDA_NAME, agendaDefinition.getName());
4545             List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
4546 
4547             SelectionCriteria selectionCriteria =
4548                     SelectionCriteria.createCriteria(null, getSelectionContext(contextDefinition.getName()), getAgendaContext(agendaName));
4549             ExecutionOptions executionOptions = new ExecutionOptions();
4550             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
4551 
4552             Facts.Builder factBuilder = Facts.Builder.create();
4553 
4554             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
4555                 MatchBo matchBo = matchBoIterator.next();
4556                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
4557             }
4558             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
4559         } catch (Exception krmsException) {
4560             LOG.error("-----------KRMS EXCEPTION------------------", krmsException);
4561 
4562             throw new RuntimeException(krmsException);
4563         }
4564         return engineResult;
4565     }
4566 
4567 
4568     public List<OleDeliverRequestBo> getRequestByItem(String itemBarcode) {
4569         List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
4570         Map<String, String> requestMap = new HashMap<String, String>();
4571         requestMap.put("itemId", itemBarcode);
4572         oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
4573         return oleDeliverRequestBoList;
4574     }
4575 
4576     public List<String> convertArrayToList(String[] array) {
4577         List<String> returnArrayList = new ArrayList<>();
4578         if (array != null && array.length > 0) {
4579             for (String value : array) {
4580                 if (StringUtils.isNotBlank(value))
4581                     returnArrayList.add(value.trim());
4582             }
4583         }
4584         return returnArrayList;
4585     }
4586 
4587 }
4588 
4589 
4590 
4591 
4592 
4593