View Javadoc
1   package org.kuali.ole.deliver.service;
2   
3   
4   import bitronix.tm.utils.CollectionUtils;
5   import com.lowagie.text.Document;
6   import org.apache.log4j.Logger;
7   import org.kuali.asr.ASRConstants;
8   import org.kuali.asr.service.ASRHelperServiceImpl;
9   import org.kuali.ole.DataCarrierService;
10  import org.kuali.ole.LoanUtil;
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.Bib;
25  import org.kuali.ole.docstore.common.document.Holdings;
26  import org.kuali.ole.docstore.common.document.ItemOleml;
27  import org.kuali.ole.docstore.common.document.content.enums.DocType;
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.common.document.content.instance.Item;
33  import org.kuali.ole.docstore.common.document.content.instance.LocationLevel;
34  import org.kuali.ole.ingest.pojo.MatchBo;
35  import org.kuali.ole.ncip.bo.OLENCIPConstants;
36  import org.kuali.ole.ncip.bo.OLEPlaceRequest;
37  import org.kuali.ole.ncip.converter.OLEPlaceRequestConverter;
38  import org.kuali.ole.sys.context.SpringContext;
39  import org.kuali.ole.util.DocstoreUtil;
40  import org.kuali.rice.core.api.config.property.ConfigContext;
41  import org.kuali.rice.core.api.mail.EmailBody;
42  import org.kuali.rice.core.api.mail.EmailFrom;
43  import org.kuali.rice.core.api.mail.EmailSubject;
44  import org.kuali.rice.core.api.mail.EmailTo;
45  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
46  import org.kuali.rice.coreservice.impl.parameter.ParameterBo;
47  import org.kuali.rice.kim.api.permission.PermissionService;
48  import org.kuali.rice.kim.api.role.RoleService;
49  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
50  import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
51  import org.kuali.rice.krad.service.BusinessObjectService;
52  import org.kuali.rice.krad.service.KRADServiceLocator;
53  import org.kuali.rice.krad.util.GlobalVariables;
54  import org.kuali.rice.krad.util.KRADConstants;
55  import org.kuali.rice.krad.util.ObjectUtils;
56  import org.kuali.rice.krms.api.KrmsApiServiceLocator;
57  import org.kuali.rice.krms.api.engine.*;
58  import org.kuali.rice.krms.impl.repository.AgendaBo;
59  
60  import java.io.OutputStream;
61  import java.math.BigDecimal;
62  import java.sql.*;
63  import java.text.DateFormat;
64  import java.text.SimpleDateFormat;
65  import java.util.*;
66  import java.util.Date;
67  
68  import org.apache.ojb.broker.PersistenceBroker;
69  import org.apache.ojb.broker.PersistenceBrokerException;
70  
71  /**
72   * Created with IntelliJ IDEA.
73   * User: ?
74   * Date: 10/24/12
75   * Time: 10:27 AM
76   * To change this template use File | Settings | File Templates.
77   */
78  public class OleDeliverRequestDocumentHelperServiceImpl {
79      private static final Logger LOG = Logger.getLogger(OleDeliverRequestDocumentHelperServiceImpl.class);
80      private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
81      private static final String NAME_SELECTOR = "name";
82      private final static String RULE_EVALUATED = "Rule Evaluated";
83      private final static String ROUTED_EXTERNAL = "Routed External";
84      private BusinessObjectService businessObjectService;
85      private int queuePosition = 0;
86      private LoanProcessor loanProcessor;
87      private DocstoreUtil docstoreUtil;
88      private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
89      private OLEDeliverNoticeHelperService oleDeliverNoticeHelperService ;
90  
91      private PermissionService getPermissionService() {
92          PermissionService service = KimApiServiceLocator.getPermissionService();
93          return service;
94      }
95  
96      private DocstoreClientLocator docstoreClientLocator;
97  
98      public DocstoreClientLocator getDocstoreClientLocator() {
99  
100         if (docstoreClientLocator == null) {
101             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
102 
103         }
104         return docstoreClientLocator;
105     }
106 
107     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
108         this.businessObjectService = businessObjectService;
109     }
110 
111 
112     public void setLoanProcessor(LoanProcessor loanProcessor) {
113         this.loanProcessor = loanProcessor;
114     }
115 
116     public void setDocstoreUtil(DocstoreUtil docstoreUtil) {
117         this.docstoreUtil = docstoreUtil;
118     }
119 
120     public void setDocstoreClientLocator(DocstoreClientLocator docstoreClientLocator) {
121         this.docstoreClientLocator = docstoreClientLocator;
122     }
123 
124     public DocstoreUtil getDocstoreUtil() {
125         if(docstoreUtil == null){
126             docstoreUtil = SpringContext.getBean(DocstoreUtil.class);
127         }
128         return docstoreUtil;
129     }
130 
131 
132     /**
133      * Gets the businessObjectService attribute.
134      *
135      * @return Returns the businessObjectService
136      */
137     private BusinessObjectService getBusinessObjectService() {
138         if (null == businessObjectService) {
139             businessObjectService = KRADServiceLocator.getBusinessObjectService();
140         }
141         return businessObjectService;
142     }
143 
144     public LoanProcessor getLoanProcessor() {
145         if(loanProcessor == null){
146             loanProcessor = SpringContext.getBean(LoanProcessor.class);
147         }
148         return loanProcessor;
149     }
150 
151     public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
152         if(itemOlemlRecordProcessor == null){
153             itemOlemlRecordProcessor = SpringContext.getBean(ItemOlemlRecordProcessor.class);
154         }
155         return itemOlemlRecordProcessor;
156     }
157     public OLEDeliverNoticeHelperService getOleDeliverNoticeHelperService() {
158         if(oleDeliverNoticeHelperService ==null){
159             oleDeliverNoticeHelperService = SpringContext.getBean(OLEDeliverNoticeHelperServiceImpl.class);
160         }
161         return oleDeliverNoticeHelperService;
162     }
163 
164     public void setOleDeliverNoticeHelperService(OLEDeliverNoticeHelperService oleDeliverNoticeHelperService) {
165         this.oleDeliverNoticeHelperService = oleDeliverNoticeHelperService;
166     }
167 
168     /**
169      * This method is used to change the request type based on selection of  pick up  location
170      *
171      * @param oleDeliverRequestBo
172      * @return oleDeliverRequestBo
173      */
174     public OleDeliverRequestBo processRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
175         if (LOG.isDebugEnabled()) {
176             LOG.debug("Inside processRequestType for the Request id :" + oleDeliverRequestBo.getRequestId());
177         }
178         oleDeliverRequestBo = processPatron(oleDeliverRequestBo);
179         oleDeliverRequestBo = processItem(oleDeliverRequestBo);
180         oleDeliverRequestBo = processRequestTypeByPickUpLocation(oleDeliverRequestBo);
181         return oleDeliverRequestBo;
182     }
183 
184     private OleDeliverRequestBo processRequestTypeByPickUpLocation(OleDeliverRequestBo oleDeliverRequestBo){
185         if (oleDeliverRequestBo.getRequestTypeId() != null) {
186             if (oleDeliverRequestBo.getRequestTypeId().equals("3") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
187                 oleDeliverRequestBo.setRequestTypeId("4");
188             } else if (oleDeliverRequestBo.getRequestTypeId().equals("5") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
189                 oleDeliverRequestBo.setRequestTypeId("6");
190             } else if (oleDeliverRequestBo.getRequestTypeId().equals("1") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
191                 oleDeliverRequestBo.setRequestTypeId("2");
192             }
193         }
194         return oleDeliverRequestBo;
195     }
196 
197 
198     /**
199      * This is to create a new patron object if the user enters the operator Id manually
200      *
201      * @param oleDeliverRequestBo
202      * @return deliver
203      */
204     public OleDeliverRequestBo processPatron(OleDeliverRequestBo oleDeliverRequestBo) {
205         LOG.debug("Inside processPatron");
206         OleDeliverRequestBo deliver = oleDeliverRequestBo;
207 
208         if (oleDeliverRequestBo.getBorrowerBarcode() != null || oleDeliverRequestBo.getProxyBorrowerBarcode() != null) {
209             Map<String, String> patronMap = new HashMap<String, String>();
210             patronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getBorrowerBarcode());
211             List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
212             if (olePatronDocumentList != null && olePatronDocumentList.size() > 0) {
213                 deliver.setOlePatron(olePatronDocumentList.get(0));
214                 deliver.setBorrowerName(olePatronDocumentList.get(0).getPatronName());
215                 deliver.setBorrowerId(olePatronDocumentList.get(0).getOlePatronId());
216             } else if (olePatronDocumentList != null && olePatronDocumentList.size() == 0) {
217                 deliver.setBorrowerId(null);
218                 deliver.setFirstName(null);
219                 deliver.setLastName(null);
220                 deliver.setOlePatron(null);
221                 deliver.setBorrowerName(null);
222                 deliver.setBorrowerBarcode(null);
223             }
224             if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
225                 Map<String, String> proxyPatronMap = new HashMap<String, String>();
226                 proxyPatronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getProxyBorrowerBarcode());
227                 List<OlePatronDocument> oleProxyPatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, proxyPatronMap);
228                 if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() > 0) {
229                     deliver.setOleProxyPatron(oleProxyPatronDocumentList.get(0));
230                     deliver.setProxyBorrowerName(oleProxyPatronDocumentList.get(0).getPatronName());
231                     deliver.setProxyBorrowerId(oleProxyPatronDocumentList.get(0).getOlePatronId());
232                 } else if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() == 0) {
233                     deliver.setProxyBorrowerId(null);
234                     deliver.setProxyBorrowerName(null);
235                     deliver.setOleProxyPatron(null);
236                 }
237             }
238 
239         }
240 
241         return deliver;
242     }
243 
244     public boolean processOperator(String principalId) {
245         /*if (getPermissionService().hasPermission(oleDeliverRequestBo.getOperatorCreateId(), OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN)) {
246             return true;
247         }*/
248         // Modified as per comments in Jira OLE-4901
249         boolean isOperator = true;
250         Collection<String> roles = getRoleService().getRoleMemberPrincipalIds(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR, null);
251         if (roles != null) {
252             isOperator = roles.contains(principalId);
253         }
254         return isOperator;
255     }
256 
257     /**
258      * This is to check whether the pick up location is selected for the hold type of Request
259      *
260      * @param oleDeliverRequestBo
261      * @return validRequest
262      */
263     public boolean validateRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
264         LOG.debug("Inside validateRequestType");
265         boolean validRequest = true;
266         if ((oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) && (oleDeliverRequestBo.getPickUpLocationId() == null) || (oleDeliverRequestBo.getPickUpLocationId() != null && oleDeliverRequestBo.getPickUpLocationId().isEmpty())) {
267             validRequest = false;
268         }
269         return validRequest;
270     }
271 
272 
273     /**
274      * This is to check whether the patron is having delivery privilege or not
275      *
276      * @param oleDeliverRequestBo
277      * @return hasDeliveryPrivilege
278      */
279     public boolean validateDeliveryPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
280         LOG.debug("Inside validateDeliveryPrivilege");
281         boolean hasDeliveryPrivilege = true;
282         if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("3") || oleDeliverRequestBo.getRequestTypeId().equals("5")) {
283             if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege()) {
284                 hasDeliveryPrivilege = false;
285             }
286         } else if (oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
287             if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege() && oleDeliverRequestBo.getPickUpLocationId() == null) {
288                 hasDeliveryPrivilege = false;
289             }
290         }
291         return hasDeliveryPrivilege;
292     }
293 
294 
295     /**
296      * This is to check whether the patron is having paging privilege or not
297      *
298      * @param oleDeliverRequestBo
299      * @return hasPagePrivilege
300      */
301     public boolean validatePagingPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
302         LOG.debug("Inside validatePagingPrivilege");
303         boolean hasPagePrivilege = true;
304         if (oleDeliverRequestBo.getRequestTypeId().equals("5") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
305             if (!oleDeliverRequestBo.getOlePatron().isPagingPrivilege()) {
306                 hasPagePrivilege = false;
307             }
308         }
309         return hasPagePrivilege;
310     }
311 
312 
313     /**
314      * This for setting the null values for the unselected requester
315      *
316      * @param oleDeliverRequestBo
317      * @return oleDeliverRequestBo
318      */
319     public OleDeliverRequestBo processRequester(OleDeliverRequestBo oleDeliverRequestBo) {
320         LOG.debug("Inside processRequester");
321         if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PATRON)) {
322             oleDeliverRequestBo.setProxyBorrowerId(null);
323             oleDeliverRequestBo.setOleProxyPatron(null);
324             oleDeliverRequestBo.setOperatorCreateId(null);
325             oleDeliverRequestBo.setOperatorCreator(null);
326         } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
327             oleDeliverRequestBo.setOperatorCreateId(null);
328             oleDeliverRequestBo.setOperatorCreator(null);
329         } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR)) {
330             oleDeliverRequestBo.setProxyBorrowerId(null);
331             oleDeliverRequestBo.setOleProxyPatron(null);
332         }
333         return oleDeliverRequestBo;
334     }
335 
336 
337     /**
338      * This is to check whether the login patron is the proxy patron for the real patron
339      *
340      * @param oleDeliverRequestBo
341      * @return validProxy
342      */
343     public boolean isValidProxyPatron(OleDeliverRequestBo oleDeliverRequestBo) {
344         LOG.debug("Inside isValidProxyPatron");
345         boolean validProxy = true;
346         Map<String, String> proxyMap = new HashMap<String, String>();
347         proxyMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
348         proxyMap.put(OLEConstants.OleDeliverRequest.PROXY_PATRON_ID, oleDeliverRequestBo.getProxyBorrowerId());
349         if (oleDeliverRequestBo.getProxyBorrowerId() != null && !oleDeliverRequestBo.getProxyBorrowerId().isEmpty()) {
350             List<OleProxyPatronDocument> proxyPatronDocuments = (List<OleProxyPatronDocument>) getBusinessObjectService().findMatching(OleProxyPatronDocument.class, proxyMap);
351             if (proxyPatronDocuments.size() == 0) {
352                 validProxy = false;
353             }
354         }
355         return validProxy;
356     }
357 
358 
359     /**
360      * This is to check whether the request is already raised by the patron for this item
361      *
362      * @param oleDeliverRequestBo
363      * @return alreadyExist
364      */
365     public boolean isRequestAlreadyRaisedByPatron(OleDeliverRequestBo oleDeliverRequestBo) {
366         LOG.debug("Inside isRequestAlreadyRaised");
367         boolean alreadyExist = false;
368         Map<String, String> requestMap = new HashMap<String, String>();
369         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, oleDeliverRequestBo.getBorrowerId());
370         requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
371         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
372         if (deliverRequestBos != null && deliverRequestBos.size() > 0) {
373             alreadyExist = true;
374         }
375         return alreadyExist;
376     }
377 
378 
379     /**
380      * This is to check whether the requested item is currently in loan to the requesting patron
381      *
382      * @param oleDeliverRequestBo
383      * @return alreadyLoaned
384      */
385     public boolean isAlreadyLoaned(OleDeliverRequestBo oleDeliverRequestBo) {
386         LOG.debug("Inside isAlreadyLoaned");
387         boolean alreadyLoaned = false;
388         Map<String, String> loanMap = new HashMap<String, String>();
389         loanMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, oleDeliverRequestBo.getBorrowerId());
390         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
391         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
392         if (loanDocuments != null && loanDocuments.size() > 0) {
393             alreadyLoaned = true;
394         }
395         return alreadyLoaned;
396     }
397 
398 
399     /**
400      * This is to check whether the item is available in the desk or not
401      *
402      * @param oleDeliverRequestBo
403      * @return itemAvailable
404      */
405     public boolean isItemAvailable(OleDeliverRequestBo oleDeliverRequestBo) {
406         LOG.debug("Inside isItemAvailable");
407         boolean itemAvailable = true;
408 
409         String itemStatuslist = null;
410         String requestTypeCode = oleDeliverRequestBo.getRequestTypeCode();
411         if (requestTypeCode.equals("Recall/Delivery Request")) {
412             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.RECALL_DELIVERY_ITEM_STATUS);
413         } else if (requestTypeCode.equals("Recall/Hold Request")) {
414             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.RECALL_HOLD_ITEM_STATUS);
415         } else if (requestTypeCode.equals("Hold/Delivery Request")) {
416             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.HOLD_DELIVERY_ITEM_STATUS);
417         } else if (requestTypeCode.equals("Hold/Hold Request")) {
418             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.HOLD_HOLD_ITEM_STATUS);
419         } else if (requestTypeCode.equals("Page/Delivery Request")) {
420             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.PAGE_DELIVERY_ITEM_STATUS);
421         } else if (requestTypeCode.equals("Page/Hold Request")) {
422             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.PAGE_HOLD_ITEM_STATUS);
423         } else if (requestTypeCode.equals("Copy Request")) {
424             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.COPY_REQUEST_ITEM_STATUS);
425         } else if (requestTypeCode.equals("ASR Request")) {
426             itemStatuslist = getLoanProcessor().getParameter(OLEConstants.ASR_REQUEST_ITEM_STATUS);
427         }else {
428             GlobalVariables.getMessageMap().putError(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, OLEConstants.OleDeliverRequest.REQUEST_ID_INVALID);
429         }
430         String[] str = itemStatuslist.split(";");
431         for (String itemStatus : str) {
432             if ((itemStatus != null) && (!itemStatus.isEmpty()) && (itemStatus.equals(oleDeliverRequestBo.getItemStatus()))) {
433                 itemAvailable = false;
434             }
435         }
436         return itemAvailable;
437     }
438 
439 
440     /**
441      * This is to check whether the item is available in the desk or not
442      *
443      * @param oleDeliverRequestBo
444      * @return itemAvailable
445      */
446     public boolean isItemAvailableForLoan(OleDeliverRequestBo oleDeliverRequestBo) {
447         LOG.debug("Inside isItemAvailable");
448         boolean itemAvailable = false;
449         Map<String, String> loanItemMap = new HashMap<String, String>();
450         loanItemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
451         List<OleLoanDocument> loanItemDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanItemMap);
452         if (loanItemDocuments.size() == 0) {
453             itemAvailable = true;
454         }
455         return itemAvailable;
456     }
457 
458 
459     /**
460      * This is to check whether the item is eligible to loan
461      *
462      * @param oleDeliverRequestBo
463      * @return itemEligible
464      */
465     public boolean isItemEligible(OleDeliverRequestBo oleDeliverRequestBo) {
466         LOG.debug("Inside isItemEligible");
467         boolean itemEligible = true;
468         Map<String, String> statusMap = new HashMap<String, String>();
469         statusMap.put(OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT, OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT);
470         statusMap.put(OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE, OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE);
471         statusMap.put(OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN, OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN);
472 
473         if (statusMap.containsKey(oleDeliverRequestBo.getItemStatus())) {
474             itemEligible = false;
475         }
476         return itemEligible;
477     }
478 
479     /**
480      * This is to check whether the patron record is alive or expired
481      *
482      * @param oleDeliverRequestBo
483      * @return expired
484      */
485     public String patronRecordExpired(OleDeliverRequestBo oleDeliverRequestBo) {
486         LOG.debug("Inside patronRecordExpired");
487         String expired = null;
488         Map<String, String> patronMap = new HashMap<String, String>();
489         patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
490         List<OlePatronDocument> olePatronDocuments = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
491         if (olePatronDocuments != null && olePatronDocuments.size() > 0) {
492             SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
493             Date expirationDate = olePatronDocuments.get(0).getExpirationDate();
494             Date activationDate = olePatronDocuments.get(0).getActivationDate();
495             if ((fmt.format(activationDate)).compareTo(fmt.format(new Date(System.currentTimeMillis()))) <= 0) {
496                 if (expirationDate != null) {
497                     if ((fmt.format(expirationDate)).compareTo(fmt.format(new Date(System.currentTimeMillis()))) < 0) {
498                         expired = OLEConstants.OleDeliverRequest.PATRON_RECORD_EXPIRE;
499                     }
500                 }
501             } else {
502                 expired = OLEConstants.OleDeliverRequest.PATRON_RECORD_FUTURE;
503             }
504         }
505         return expired;
506     }
507 
508 
509     /**
510      * This is for retrieving the request raised by  the patron
511      *
512      * @param olePatronId
513      * @return deliverRequestBos
514      */
515     public List<OleDeliverRequestBo> getRequestedItems(String olePatronId) {
516         LOG.debug("Inside getRequestedItems");
517         Map<String, String> requestMap = new HashMap<String, String>();
518         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, olePatronId);
519         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
520         for (int i = 0; i < deliverRequestBos.size(); i++) {
521             processItem(deliverRequestBos.get(i));
522         }
523         return deliverRequestBos;
524 
525     }
526 
527 
528     /**
529      * This is to check the  duplicate in the queue Position while re -ordering
530      *
531      * @param itemList
532      * @return exist
533      */
534     public String validateQueuePosition(List<OleDeliverRequestBo> itemList) {
535         LOG.debug("Inside validateQueuePosition");
536         String message = OLEConstants.OleDeliverRequest.REORDER_SUCCESS;
537         List<Integer> queuePositionList = new ArrayList<Integer>();
538         if (itemList.get(0).getBorrowerQueuePosition() < 1) {
539             return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
540         }
541         queuePositionList.add(itemList.get(0).getBorrowerQueuePosition());
542 
543         for (int i = 1; i < itemList.size(); i++) {
544             for (int j = 0; j < queuePositionList.size(); j++) {
545                 if (itemList.get(i).getBorrowerQueuePosition() != null) {
546                     if ((itemList.get(i).getBorrowerQueuePosition() >= 1) && (itemList.get(i).getBorrowerQueuePosition() == queuePositionList.get(j))) {
547                         return OLEConstants.OleDeliverRequest.QUEUE_DUPLICATE;
548                     } else if ((itemList.get(i).getBorrowerQueuePosition() <= 0)) {
549                         return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
550                     }
551                 }
552             }
553             queuePositionList.add(itemList.get(i).getBorrowerQueuePosition());
554         }
555         return message;
556     }
557 
558     //
559 
560     /**
561      * This is to check whether any request raised for the item
562      *
563      * @param oleDeliverRequestBo
564      * @return exist
565      */
566     public boolean isRequestRaised(OleDeliverRequestBo oleDeliverRequestBo) {
567         LOG.debug("Inside isRequestRaised");
568         boolean exist = false;
569         Map<String, String> requestMap = new HashMap<String, String>();
570         requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
571         List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
572         if (deliverRequestBos.size() > 0) {
573             exist = true;
574         }
575         return exist;
576     }
577 
578 
579     /**
580      * This method is used to cancel the request document using ASR/NCIP.
581      *
582      * @param oleDeliverRequestBo
583      */
584     public void cancelDocument(OleDeliverRequestBo oleDeliverRequestBo){
585         try{
586         List<OleNoticeBo> oleNoticeBos = cancelRequestForItem(oleDeliverRequestBo.getItemUuid(), oleDeliverRequestBo.getBorrowerId());
587         ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
588         LOG.debug("Inside cancelDocument");
589         Map<String, String> itemMap = new HashMap<String, String>();
590         itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
591         Map<String, String> requestMap = new HashMap<String, String>();
592         requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, oleDeliverRequestBo.getRequestId());
593         getBusinessObjectService().deleteMatching(OleDeliverRequestBo.class, requestMap);
594         List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
595         getBusinessObjectService().delete(oleDeliverRequestDocumentsList);
596         int queuePosition = 1;
597         for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
598             oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
599             queuePosition = queuePosition + 1;
600         }
601         getBusinessObjectService().save(oleDeliverRequestDocumentsList);
602         asrHelperService.deleteASRTypeRequest(oleDeliverRequestBo.getRequestId());
603         sendCancelNotice(oleNoticeBos);
604         }catch (Exception e){
605             LOG.error("Cancellation of Request"+e.getMessage());
606         }
607     }
608 
609     /**
610      * Build the cancellation notice template.
611      * @param itemUuid
612      * @param patronId
613      * @return
614      * @throws Exception
615      */
616     public List<OleNoticeBo> cancelRequestForItem(String itemUuid,String patronId) throws Exception{
617         Map<String, String> requestMap = new HashMap<String, String>();
618         requestMap.put(OLEConstants.ITEM_UUID,itemUuid);
619         requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID,patronId);
620         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
621         List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
622         if(org.apache.commons.collections.CollectionUtils.isNotEmpty(oleDeliverRequestBoList)){
623             OleDeliverRequestBo oleDeliverRequestBo = oleDeliverRequestBoList.get(0);
624             //cancelDocument(oleDeliverRequestBo);
625             OleItemSearch itemSearch = getDocstoreUtil().getOleItemSearchList(itemUuid);
626             EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
627 
628             OleNoticeBo oleNoticeBo = new OleNoticeBo();
629             oleNoticeBo.setNoticeName(OLEConstants.CANCELLATION_NOTICE);
630             oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
631             oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
632             oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
633             oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
634             oleNoticeBo.setAuthor(itemSearch.getAuthor() != null ? itemSearch.getAuthor() : "");
635             oleNoticeBo.setItemCallNumber(itemSearch.getCallNumber() != null ? itemSearch.getCallNumber() : "");
636             if(itemSearch.getShelvingLocation()!=null && itemSearch.getShelvingLocation().toString().contains("/")){
637                 String [] location=itemSearch.getShelvingLocation().split("/");
638                 if(location!=null && location.length>0)
639                     oleNoticeBo.setItemShelvingLocation(location[1]!=null ? location[1] : "");
640             } else {
641                 oleNoticeBo.setItemShelvingLocation("");
642             }
643             oleNoticeBo.setItemId(itemSearch.getItemBarCode() != null ? itemSearch.getItemBarCode() : "");
644             oleNoticeBo.setTitle(itemSearch.getTitle() != null ? itemSearch.getTitle() : "");
645             oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
646             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
647                oleNoticeBos.add(oleNoticeBo);
648             }
649         }
650        return oleNoticeBos;
651     }
652 
653 
654     /**
655      * send the email to respective patron.
656      * @param oleNoticeBos
657      * @throws Exception
658      */
659     public void sendCancelNotice(List<OleNoticeBo> oleNoticeBos)throws Exception{
660         String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
661         if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
662             fromAddress = OLEConstants.KUALI_MAIL;
663         }
664         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
665         for(OleNoticeBo oleNoticeBo : oleNoticeBos){
666                 List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
667                 String content = list.toString();
668                 content = content.replace('[', ' ');
669                 content = content.replace(']', ' ');
670                 if (!content.trim().equals("")) {
671                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
672                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.CANCELLATION_NOTICE), new EmailBody(content), true);
673                 }
674         }
675     }
676 
677 
678 
679 
680     public void cancelPendingRequestForClaimsReturnedItem(String itemUuid) throws Exception {
681         Map<String, String> requestMap = new HashMap<String, String>();
682         requestMap.put(OLEConstants.ITEM_UUID, itemUuid);
683         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
684         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
685         for (OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBoList) {
686             cancelDocument(oleDeliverRequestBo);
687             /*OleItemSearch itemSearch = getDocstoreUtil().getOleItemSearchList(itemUuid);
688             EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
689             List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
690             OleNoticeBo oleNoticeBo = new OleNoticeBo();
691             oleNoticeBo.setNoticeName(OLEConstants.CANCELLATION_NOTICE);
692             oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
693             oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
694             oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
695             oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
696             oleNoticeBo.setAuthor(itemSearch.getAuthor() != null ? itemSearch.getAuthor() : "");
697             oleNoticeBo.setItemCallNumber(itemSearch.getCallNumber() != null ? itemSearch.getCallNumber() : "");
698             if(itemSearch.getShelvingLocation()!=null && itemSearch.getShelvingLocation().toString().contains("/")){
699                 String [] location=itemSearch.getShelvingLocation().split("/");
700                 if(location!=null && location.length>0)
701                     oleNoticeBo.setItemShelvingLocation(location[1]!=null ? location[1] : "");
702             } else {
703                 oleNoticeBo.setItemShelvingLocation("");
704             }
705             oleNoticeBo.setItemId(itemSearch.getItemBarCode() != null ? itemSearch.getItemBarCode() : "");
706             oleNoticeBo.setTitle(itemSearch.getTitle() != null ? itemSearch.getTitle() : "");
707             oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
708             String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
709             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
710                 fromAddress = OLEConstants.KUALI_MAIL;
711             }
712             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
713                 oleNoticeBos.add(oleNoticeBo);
714                 List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
715                 String content = list.toString();
716                 content = content.replace('[', ' ');
717                 content = content.replace(']', ' ');
718                 if (!content.trim().equals("")) {
719                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
720                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.CANCELLATION_NOTICE), new EmailBody(content), true);
721                 }
722             }*/
723         }
724     }
725 
726     /**
727      * This method is to set the item values from docstore
728      *
729      * @param oleDeliverRequestBo
730      * @return oleDeliverRequestBo
731      */
732     public OleDeliverRequestBo processItem(OleDeliverRequestBo oleDeliverRequestBo) {
733         LOG.debug("Inside processItem");
734         OleItemSearch oleItemSearch = null;
735         if (oleDeliverRequestBo.getItemType() == null) {
736             // Map<String, String> itemMap = new HashMap<String, String>();
737             //itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
738             OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(oleDeliverRequestBo.getItemUuid());
739             try {
740                 //org.kuali.ole.docstore.common.document.Item item=getDocstoreClientLocator().getDocstoreClient().retrieveItem( oleDeliverRequestBo.getItemUuid());
741 
742 
743                 if (itemSearchList != null) {
744                     oleItemSearch = itemSearchList;
745                     oleDeliverRequestBo.setTitle(itemSearchList.getTitle());
746                     oleDeliverRequestBo.setAuthor(itemSearchList.getAuthor());
747                     oleDeliverRequestBo.setCallNumber(itemSearchList.getCallNumber());
748                     oleDeliverRequestBo.setItemType(itemSearchList.getItemType());
749                     oleDeliverRequestBo.setItemLocation(itemSearchList.getShelvingLocation());
750                     oleDeliverRequestBo.setShelvingLocation(itemSearchList.getShelvingLocation());
751                     oleDeliverRequestBo.setCopyNumber(itemSearchList.getCopyNumber());
752                     oleDeliverRequestBo.setItemStatus(itemSearchList.getItemStatus());
753                 }
754             } catch (Exception ex) {
755                 ex.printStackTrace();
756             }
757             try {
758                 String itemXml = getLoanProcessor().getItemXML(oleDeliverRequestBo.getItemUuid());
759                 Item oleItem = getLoanProcessor().getItemPojo(itemXml);
760                 if (oleItemSearch == null) {
761                     oleItemSearch = new OleItemSearch();
762                     oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
763                     if (oleItem.getItemStatus() != null) {
764                         oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
765                     }
766                     oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
767                     oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
768 
769                     if (oleItem.getItemStatus() != null) {
770                         oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
771                     }
772                     oleDeliverRequestBo.setShelvingLocation(oleItemSearch.getShelvingLocation());
773                 }
774                 // Map docStoreDetails = loanProcessor.getItemDetails(oleDeliverRequestBo.getItemId());
775                 if (oleDeliverRequestBo.getRequestTypeId().equals("8")) {
776                     oleDeliverRequestBo.setInTransitCheckInNote(oleItem.getCheckinNote());
777                 }
778             } catch (Exception e) {
779                 LOG.error(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC), e);  //To change body of catch statement use File | Settings | File Templates.
780             }
781         }
782         oleDeliverRequestBo.setOleItemSearch(oleItemSearch);
783         oleDeliverRequestBo = processItemType(oleDeliverRequestBo);
784         return oleDeliverRequestBo;
785     }
786 
787     /**
788      * This method is to set the item type name  based on the item type code
789      *
790      * @param oleDeliverRequestBo
791      * @return
792      */
793     public OleDeliverRequestBo processItemType(OleDeliverRequestBo oleDeliverRequestBo) {
794         LOG.debug("Inside process Item Type");
795         Map<String, String> itemMap = new HashMap<String, String>();
796         itemMap = new HashMap<String, String>();
797         itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, oleDeliverRequestBo.getItemType());
798         List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) getBusinessObjectService().findMatching(OleInstanceItemType.class, itemMap);
799         if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
800             OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
801             oleDeliverRequestBo.setItemTypeName(oleInstanceItemType.getInstanceItemTypeName());
802         }
803 
804         return oleDeliverRequestBo;
805     }
806 
807     /**
808      * This method is to retrieve the shelving location from item
809      *
810      * @param oleLocation
811      * @return locationLevelName
812      */
813     private String getShelvingLocation(Location oleLocation) {
814 
815         LOG.debug("Inside getShelvingLocation");
816         String locationLevelName = "";
817         if (oleLocation != null) {
818             LocationLevel locationLevel =
819                     oleLocation.getLocationLevel();
820             if (locationLevel != null) {
821                 while (locationLevel.getLocationLevel() != null && !locationLevel.getLevel().equalsIgnoreCase(OLEConstants.OleDeliverRequest.SHELVING)) {
822                     locationLevel = locationLevel.getLocationLevel();
823                 }
824                 locationLevelName = locationLevel.getName();
825             }
826         }
827         return locationLevelName;
828     }
829 
830 
831     /**
832      * This method is to check whether the selected  request can be raised for the item
833      *
834      * @param oleDeliverRequestBo
835      * @return canRaiseRequest
836      */
837     public boolean canRaiseRequest(OleDeliverRequestBo oleDeliverRequestBo) {
838         LOG.debug("Inside canRaiseRequest");
839         boolean canRaiseRequest = true;
840 
841         if (isItemAvailable(oleDeliverRequestBo)) {
842             canRaiseRequest = false;
843 
844 
845         }
846         return canRaiseRequest;
847     }
848 
849 
850     /**
851      * racle
852      * This method is to update the request id in the loan document
853      *
854      * @param oleDeliverRequestBo
855      */
856     public OleDeliverRequestBo updateLoanDocument(OleDeliverRequestBo oleDeliverRequestBo) {
857         LOG.debug("Inside updateLoanDocument");
858         Map<String, String> loanMap = new HashMap<String, String>();
859         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
860         List<OleLoanDocument> oleLoanDocumentList = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
861         if (oleLoanDocumentList != null && oleLoanDocumentList.size() > 0 && oleLoanDocumentList.get(0) != null && oleLoanDocumentList.get(0).getOleRequestId() == null) {
862             if (oleLoanDocumentList.get(0).getLoanId() != null) {
863                 oleLoanDocumentList.get(0).setOleRequestId(oleDeliverRequestBo.getRequestId());
864                 oleDeliverRequestBo.setLoanTransactionRecordNumber(oleLoanDocumentList.get(0).getLoanId());
865             }
866            businessObjectService.save(oleLoanDocumentList.get(0));
867 
868         }
869         return oleDeliverRequestBo;
870     }
871 
872     /**
873      * @param requestId
874      * @param itemUUID
875      * @param operatorId
876      * @param loanTransactionNumber
877      */
878     public void deleteRequest(String requestId, String itemUUID, String operatorId, String loanTransactionNumber) {
879         LOG.debug("Inside deleteRequest");
880         Map<String, String> requestMap = new HashMap<String, String>();
881         requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
882         createRequestHistoryRecord(requestId, operatorId, loanTransactionNumber);
883         Map<String, String> itemMap = new HashMap<String, String>();
884         itemMap.put(OLEConstants.ITEM_UUID, itemUUID);
885         List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
886         getBusinessObjectService().delete(oleDeliverRequestDocumentsList);
887         int queuePosition = 1;
888         for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
889             oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
890             queuePosition = queuePosition + 1;
891         }
892         getBusinessObjectService().save(oleDeliverRequestDocumentsList);
893 
894     }
895 
896     /**
897      * This for retrieving the item Details from docstore
898      *
899      * @param itemUUID
900      * @return oleItemSearch
901      */
902     public OleItemSearch getItemDetails(String itemUUID) {
903         LOG.debug("Inside getItemDetails");
904         OleItemSearch oleItemSearch = getItemDetailsForPatron(itemUUID);
905         try {
906             // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
907             String itemXml = getLoanProcessor().getItemXML(itemUUID);
908             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
909             if (oleItem != null && oleItem.getItemType() != null) {
910                 oleItemSearch.setItemType(processItemType(oleItem.getItemType().getCodeValue()));
911             }
912             oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
913             if (oleItem.getItemStatus() != null) {
914                 oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
915             }
916             oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
917             oleItemSearch.setVolumeNumber(oleItem.getVolumeNumber());
918         } catch (Exception e) {
919             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.
920         }
921         return oleItemSearch;
922     }
923 
924     /**
925      * This method is for retrieving the item details for displaying in the patron screen
926      *
927      * @param itemUUID
928      * @return OleItemSearch
929      */
930     public OleItemSearch getItemDetailsForPatron(String itemUUID) {
931         LOG.debug("Inside getItemDetailsForPatron");
932         OleItemSearch oleItemSearch;
933         try {
934 
935             Map<String, String> itemMap = new HashMap<String, String>();
936             // itemMap.put(OLEConstants.OleDeliverRequest.ITEM_UUID, itemUUID);
937             OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(itemUUID);
938             if (itemSearchList != null) {
939                 return oleItemSearch = itemSearchList;
940             }
941         } catch (NullPointerException e) {
942             LOG.error("No item details available for the Item Barcode : " + itemUUID, e);
943         }
944 
945         return new OleItemSearch();
946 
947     }
948 
949     /**
950      * This method is to re-order the queuePosition based on the priority while creating the request
951      *
952      * @param oleDeliverRequestBo
953      * @return OleDeliverRequestBo
954      */
955     public OleDeliverRequestBo reOrderQueuePosition(OleDeliverRequestBo oleDeliverRequestBo) {
956         LOG.debug("Inside reOrderQueuePosition");
957         List<OleDeliverRequestBo> existingRequest = new ArrayList<OleDeliverRequestBo>();
958         String queue = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.REQUEST_QUEUE);
959         List<String> orderQueue = new ArrayList<String>();
960         String[] queueArray = queue.split(";");
961         for (int i = 0; i < queueArray.length; i++) {
962             orderQueue.add(queueArray[i]);
963         }
964         List<OleDeliverRequestBo> finalList = new ArrayList<OleDeliverRequestBo>();
965         Map<String, String> recallRequestMap = new HashMap<String, String>();
966         recallRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
967         recallRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
968         Map<String, String> recallHoldRequestMap = new HashMap<String, String>();
969         recallHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
970         recallHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
971         Map<String, String> holdRequestMap = new HashMap<String, String>();
972         holdRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
973         holdRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
974         Map<String, String> holdHoldRequestMap = new HashMap<String, String>();
975         holdHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
976         holdHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
977         Map<String, String> pageRequestMap = new HashMap<String, String>();
978         pageRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
979         pageRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
980         Map<String, String> pageHoldRequestMap = new HashMap<String, String>();
981         pageHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
982         pageHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
983         Map<String, String> copyRequestMap = new HashMap<String, String>();
984         copyRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
985         copyRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "7");
986         Map<String, String> inTransitRequestMap = new HashMap<String, String>();
987         inTransitRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
988         inTransitRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "8");
989         Map<String, String> asrRequestMap = new HashMap<String, String>();
990         asrRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
991         asrRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
992         List<OleDeliverRequestBo> recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, recallRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
993         List<OleDeliverRequestBo> recallHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, recallHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
994         List<OleDeliverRequestBo> holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, holdRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
995         List<OleDeliverRequestBo> holdHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, holdHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
996         List<OleDeliverRequestBo> pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, pageRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
997         List<OleDeliverRequestBo> pageHoldList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, pageHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
998         List<OleDeliverRequestBo> copyList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, copyRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
999         List<OleDeliverRequestBo> inTransitList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, inTransitRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1000         List<OleDeliverRequestBo> asrList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatchingOrderBy(OleDeliverRequestBo.class, asrRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
1001         if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_DELIVERY)) {
1002             recallList.add(oleDeliverRequestBo);
1003         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_DELIVERY)) {
1004             holdList.add(oleDeliverRequestBo);
1005         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_DELIVERY)) {
1006             pageList.add(oleDeliverRequestBo);
1007         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.COPY)) {
1008             copyList.add(oleDeliverRequestBo);
1009         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.INTRANSIT)) {
1010             inTransitList.add(oleDeliverRequestBo);
1011         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_HOLD)) {
1012             recallHoldList.add(oleDeliverRequestBo);
1013         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_HOLD)) {
1014             holdHoldList.add(oleDeliverRequestBo);
1015         } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_HOLD)) {
1016             pageHoldList.add(oleDeliverRequestBo);
1017         }else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.ASR_REQUEST)) {
1018             asrList.add(oleDeliverRequestBo);
1019         }
1020         OleDeliverRequestBo oleDeliverRequestBo1;
1021         for (int i = 0; i < orderQueue.size(); i++) {
1022             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallList.size() > 0) {
1023                 for (int x = 0; x < recallList.size(); x++) {
1024                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallList.get(x));
1025                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1026                     this.queuePosition = this.queuePosition + 1;
1027                     finalList.add(oleDeliverRequestBo1);
1028 
1029                 }
1030             }
1031             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdList.size() > 0) {
1032                 for (int x = 0; x < holdList.size(); x++) {
1033                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdList.get(x));
1034                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1035                     this.queuePosition = this.queuePosition + 1;
1036                     finalList.add(oleDeliverRequestBo1);
1037 
1038                 }
1039             }
1040             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageList.size() > 0) {
1041                 for (int x = 0; x < pageList.size(); x++) {
1042                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageList.get(x));
1043                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1044                     this.queuePosition = this.queuePosition + 1;
1045                     finalList.add(oleDeliverRequestBo1);
1046                 }
1047             }
1048             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallHoldList.size() > 0) {
1049                 for (int x = 0; x < recallHoldList.size(); x++) {
1050                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallHoldList.get(x));
1051                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1052                     this.queuePosition = this.queuePosition + 1;
1053                     finalList.add(oleDeliverRequestBo1);
1054 
1055                 }
1056             }
1057             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdHoldList.size() > 0) {
1058                 for (int x = 0; x < holdHoldList.size(); x++) {
1059                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdHoldList.get(x));
1060                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1061                     this.queuePosition = this.queuePosition + 1;
1062                     finalList.add(oleDeliverRequestBo1);
1063 
1064                 }
1065             }
1066             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageHoldList.size() > 0) {
1067                 for (int x = 0; x < pageHoldList.size(); x++) {
1068                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageHoldList.get(x));
1069                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1070                     this.queuePosition = this.queuePosition + 1;
1071                     finalList.add(oleDeliverRequestBo1);
1072                 }
1073             }
1074             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.COPY) && copyList.size() > 0) {
1075                 for (int x = 0; x < copyList.size(); x++) {
1076                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(copyList.get(x));
1077                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1078                     this.queuePosition = this.queuePosition + 1;
1079                     finalList.add(oleDeliverRequestBo1);
1080 
1081                 }
1082             }
1083             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.INTRANSIT) && inTransitList.size() > 0) {
1084                 for (int x = 0; x < inTransitList.size(); x++) {
1085                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(inTransitList.get(x));
1086                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1087                     this.queuePosition = this.queuePosition + 1;
1088                     finalList.add(oleDeliverRequestBo1);
1089 
1090                 }
1091             }
1092             if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.ASR_REQUEST) && asrList.size() > 0) {
1093                 for (int x = 0; x < asrList.size(); x++) {
1094                     oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(asrList.get(x));
1095                     oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
1096                     this.queuePosition = this.queuePosition + 1;
1097                     finalList.add(oleDeliverRequestBo1);
1098 
1099                 }
1100             }
1101         }
1102         for (int i = 0; i < finalList.size(); i++) {
1103             if (finalList.get(i).getRequestId() == null) {
1104                 oleDeliverRequestBo.setBorrowerQueuePosition(finalList.get(i).getBorrowerQueuePosition());
1105                 finalList.remove(finalList.get(i));
1106             }
1107         }
1108         getBusinessObjectService().save(finalList);
1109         this.queuePosition = 0;
1110         oleDeliverRequestBo.setRequestId(KRADServiceLocator.getSequenceAccessorService().getNextAvailableSequenceNumber("OLE_DLVR_RQST_S").toString());
1111         return oleDeliverRequestBo;
1112     }
1113 
1114     /**
1115      * Thsi method is to check whether the item is available in doc store or not
1116      *
1117      * @param oleDeliverRequestBo
1118      * @return boolean
1119      */
1120     public boolean isItemAvailbleInDocstore(OleDeliverRequestBo oleDeliverRequestBo) {
1121         LOG.debug("Inside isItemAvailbleInDocstore");
1122         boolean available = false;
1123         Map<String, String> itemMap = new HashMap<String, String>();
1124         try {
1125             String itemUUID = "";
1126             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1127             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
1128             SearchResponse searchResponse = null;
1129             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()), ""));
1130 
1131 
1132             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
1133             ;
1134 
1135                    /* Map<String,String> map=new HashMap<>();
1136                     map.put(item.BARCODE, itemBarcode);
1137                     item=getDocstoreClientLocator().getDocstoreClient().findItem(map);*/
1138 
1139             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
1140             for (SearchResult searchResult : searchResponse.getSearchResults()) {
1141                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1142                     String fieldName = searchResultField.getFieldName();
1143                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
1144 
1145                     if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("item")) {
1146                         itemUUID = fieldValue;
1147                     }
1148 
1149                 }
1150             }
1151 
1152 
1153             oleDeliverRequestBo.setItemUuid(itemUUID);
1154         } catch (Exception e) {
1155             LOG.error("Exception", e);
1156             //To change body of catch statement use File | Settings | File Templates.
1157         }
1158         // itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1159         OleItemSearch itemSearchList = getDocstoreUtil().getOleItemSearchList(oleDeliverRequestBo.getItemUuid());
1160         if (itemSearchList != null) {
1161             oleDeliverRequestBo.setTitle(itemSearchList.getTitle());
1162             oleDeliverRequestBo.setAuthor(itemSearchList.getAuthor());
1163             oleDeliverRequestBo.setCallNumber(itemSearchList.getCallNumber());
1164             oleDeliverRequestBo.setItemType(itemSearchList.getItemType());
1165         }
1166         try {
1167             // Map docStoreDetails = loanProcessor.getItemDetailsByUUID(oleDeliverRequestBo.getItemId());
1168             String itemXml = getLoanProcessor().getItemXML(oleDeliverRequestBo.getItemUuid());
1169             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
1170 
1171             oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
1172             if (oleItem.getItemStatus() != null) {
1173                 oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
1174             }
1175             oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
1176             available = true;
1177         } catch (Exception e) {
1178             LOG.error(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC), e);  //To change body of catch statement use File | Settings | File Templates.
1179         }
1180         return available;
1181     }
1182 
1183     public OleDeliverRequestBo populateItemDetailsToRequest(OleDeliverRequestBo oleDeliverRequestBo, OleItemSearch oleItemSearch) {
1184         LOG.debug("Inside populateItemDetailsToRequest");
1185         if (oleDeliverRequestBo != null && oleItemSearch != null) {
1186             oleDeliverRequestBo.setAuthor(oleItemSearch.getAuthor());
1187             oleDeliverRequestBo.setTitle(oleItemSearch.getTitle());
1188             oleDeliverRequestBo.setCallNumber(oleItemSearch.getCallNumber());
1189             oleDeliverRequestBo.setCopyNumber(oleItemSearch.getCopyNumber());
1190             oleDeliverRequestBo.setItemType(oleItemSearch.getItemType());
1191             oleDeliverRequestBo.setItemStatus(oleItemSearch.getItemStatus());
1192             oleItemSearch.setShelvingLocation(oleDeliverRequestBo.getShelvingLocation());
1193         }
1194         return oleDeliverRequestBo;
1195     }
1196 
1197 
1198     public OleDeliverRequestBo generateRecallNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
1199         Map<String, String> loanMap = new HashMap<String, String>();
1200         loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1201         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
1202         OleLoanDocument oleLoanDocument = loanDocuments.get(0);
1203         Map<String, String> patronMap = new HashMap<String, String>();
1204         patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleLoanDocument.getPatronId());
1205         List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
1206         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1207         Item item;
1208         if (patronDocumentList.size() > 0) {
1209             OlePatronDocument olePatronDocument = patronDocumentList.get(0);
1210             EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
1211             oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " +olePatronDocument.getEntity().getNames().get(0).getLastName());
1212             oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1213             oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1214             oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1215         }
1216         oleNoticeBo.setAuthor(oleDeliverRequestBo.getAuthor() != null ? oleDeliverRequestBo.getAuthor() : "");
1217         oleNoticeBo.setCirculationDeskAddress("");
1218         oleNoticeBo.setCirculationDeskName("");
1219         oleNoticeBo.setCirculationDeskEmailAddress("");
1220         oleNoticeBo.setCirculationDeskPhoneNumber("");
1221         oleNoticeBo.setItemCallNumber(oleDeliverRequestBo.getCallNumber() != null ? oleDeliverRequestBo.getCallNumber() : "");
1222         oleNoticeBo.setItemShelvingLocation(oleDeliverRequestBo.getShelvingLocation() != null ? oleDeliverRequestBo.getShelvingLocation() : "");
1223         oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
1224         oleNoticeBo.setTitle(oleDeliverRequestBo.getTitle() != null ? oleDeliverRequestBo.getTitle() : "");
1225         oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
1226         oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
1227         oleNoticeBo.setVolumeNumber(oleNoticeBo.getOleItem().getVolumeNumber() != null ? oleNoticeBo.getOleItem().getVolumeNumber() : "");
1228         oleNoticeBo.setOriginalDueDate(oleDeliverRequestBo.getOriginalDueDate());
1229         oleNoticeBo.setNewDueDate(oleDeliverRequestBo.getNewDueDate());
1230         String volumeNumber = oleDeliverRequestBo.getVolumeNumber() != null ? oleDeliverRequestBo.getVolumeNumber() : "";
1231         String copyNumber = oleDeliverRequestBo.getCopyNumber()!=null ? oleDeliverRequestBo.getCopyNumber() : "";
1232         oleNoticeBo.setVolumeIssueCopyNumber("/"+volumeNumber + "/" + copyNumber);
1233         /*if (oleDeliverRequestBo.getRecallDueDate() != null) {
1234             oleNoticeBo.setNewDueDate(oleDeliverRequestBo.getRecallDueDate());
1235         } else {
1236             oleNoticeBo.setNewDueDate(oleLoanDocument.getLoanDueDate());
1237         }*/
1238         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_RECALL);
1239         String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_BODY);
1240         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1241         //  oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo,oleDeliverRequestBo.getOlePatron());
1242         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1243         List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
1244         String noticeType = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_NOTICE_TYPE);
1245         oleNoticeBos.add(oleNoticeBo);
1246         if (noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1247             String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1248             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1249                 fromAddress = OLEConstants.KUALI_MAIL;
1250             }
1251             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
1252                 List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
1253                 String content = list.toString();
1254                 content = content.replace('[', ' ');
1255                 content = content.replace(']', ' ');
1256                 if (!content.trim().equals("")) {
1257                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1258                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1259                 } else {
1260                     for (OleNoticeBo oleNoticeBo1 : oleNoticeBos) {
1261                         if (LOG.isDebugEnabled()) {
1262                             LOG.debug("Notice Type :" + oleNoticeBo1.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo1.getItemId() + " " + "Patron Name :" + oleNoticeBo1.getPatronName());
1263                         }
1264                     }
1265                 }
1266                 if (LOG.isDebugEnabled()) {
1267                     LOG.debug("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1268                 }
1269 /*
1270                 Mailer  mailer = CoreApiServiceLocator.getMailer();
1271                 mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1272           */
1273             }
1274         } else if (noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1275             //oleNoticeBos.add(oleNoticeBo);
1276             Map map = oleDeliverBatchService.getSMSForPatron(oleNoticeBos);
1277             HashMap sms = (HashMap) map.get(OLEConstants.OleDeliverRequest.RECALL);
1278             Iterator it = sms.entrySet().iterator();
1279             while (it.hasNext()) {
1280                 Map.Entry pairs = (Map.Entry) it.next();
1281                 String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1282                 OleSms oleSms = new OleSms();
1283                 oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1284             }
1285 
1286         }
1287         if (noticeType.equalsIgnoreCase(OLEConstants.MAIL) || noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1288             //oleNoticeBos.add(oleNoticeBo);
1289             oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
1290             if (LOG.isDebugEnabled()) {
1291                 LOG.debug("Recall Notice Pdf generated for item Id" + oleNoticeBo.getItemId());
1292             }
1293         }
1294         oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(oleDeliverRequestBo);
1295         oleDeliverRequestBo.setRecallNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1296         return oleDeliverRequestBo;
1297     }
1298 
1299 
1300     public void generateOnHoldNotice() throws Exception {
1301 
1302         List<OleDeliverRequestBo> finalDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1303         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb)SpringContext.getBean("oleLoanDao");
1304 
1305         List<String> requestTypeIds = new ArrayList<>();
1306         requestTypeIds.add("2");
1307         requestTypeIds.add("4");
1308         Collection oleDeliverRequestBoList = oleLoanDocumentDaoOjb.getHoldRequests(requestTypeIds);
1309         OleDeliverRequestBo oleDeliverRequestBo;
1310         List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1311         EntityTypeContactInfoBo entityTypeContactInfoBo;
1312         OleNoticeBo oleNoticeBo;
1313         Item item;
1314         boolean firstTime = true;
1315         String patronId ="";
1316         String noticeTypeParam = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_NOTICE_TYPE);
1317         for (Object obj : oleDeliverRequestBoList) {
1318             OleDeliverRequestBo deliverRequestBo = (OleDeliverRequestBo) obj;
1319             if(firstTime){
1320                 patronId= deliverRequestBo.getBorrowerId();
1321                 firstTime = false;
1322             }
1323             if (getDocstoreUtil().isItemAvailableInDocStore(deliverRequestBo)) {
1324                 item = deliverRequestBo.getOleItem();
1325                 OlePatronDocument olePatronDocument = deliverRequestBo.getOlePatron();
1326                 if (item != null && item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null && item.getItemStatus().getCodeValue().equals(OLEConstants.ITEM_STATUS_ON_HOLD) && deliverRequestBo.getOnHoldNoticeSentDate() == null) {
1327                     entityTypeContactInfoBo = deliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1328                     oleNoticeBo = new OleNoticeBo();
1329                     oleNoticeBo.setAuthor(deliverRequestBo.getAuthor());
1330                     oleNoticeBo.setCirculationDeskAddress("");
1331                     oleNoticeBo.setCirculationDeskName("");
1332                     oleNoticeBo.setCirculationDeskEmailAddress("");
1333                     oleNoticeBo.setCirculationDeskPhoneNumber("");
1334                     oleNoticeBo.setPatronName(deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1335                     oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1336                     oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1337                     oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1338                     oleNoticeBo.setItemCallNumber(deliverRequestBo.getCallNumber() != null ? deliverRequestBo.getCallNumber() : "");
1339                     oleNoticeBo.setItemShelvingLocation(deliverRequestBo.getShelvingLocation() != null ? deliverRequestBo.getShelvingLocation() : "");
1340                     oleNoticeBo.setItemId(deliverRequestBo.getItemId() != null ? deliverRequestBo.getItemId() : "");
1341                     oleNoticeBo.setTitle(deliverRequestBo.getTitle() != null ? deliverRequestBo.getTitle() : "");
1342                     oleNoticeBo.setOleItem(item);
1343                     oleNoticeBo.setOlePatron(deliverRequestBo.getOlePatron());
1344                     oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1345                     oleNoticeBo.setNewDueDate(new Date());
1346                     oleNoticeBo.setOriginalDueDate(new Date());
1347                     oleNoticeBo.setNoticeName(OLEConstants.NOTICE_ONHOLD);
1348                     oleNoticeBo.setCirculationDeskName(deliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName());
1349                     String circulationDeskId = deliverRequestBo.getPickUpLocationId();
1350                     int noDays = 0;
1351                     Map<String, String> mapCirculationDesk = new HashMap<String, String>();
1352                     mapCirculationDesk.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_ID, circulationDeskId);
1353                     List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDesk.class, mapCirculationDesk);
1354                     if (oleCirculationDesks.size() > 0) {
1355                         OleCirculationDesk oleCirculationDesk = oleCirculationDesks.get(0);
1356                         noDays = Integer.parseInt(oleCirculationDesk.getOnHoldDays());
1357                     }
1358                     Calendar calendar = Calendar.getInstance();
1359                     calendar.add(Calendar.DATE, noDays);
1360                     Date date = calendar.getTime();
1361                     oleNoticeBo.setExpiredOnHoldDate(date);
1362                     String maxNumOfDays = deliverRequestBo.getOlePickUpLocation().getOnHoldDays() != null ? deliverRequestBo.getOlePickUpLocation().getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1363                     Integer maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1364                     oleNoticeBo.setOnHoldDueDate(dateAdd(deliverRequestBo.getCreateDate(), maxNumberOfDaysOnHold));
1365                     String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_BODY);
1366                     oleNoticeBo.setNoticeSpecificContent(noticeContent);
1367                     String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1368                     HashMap<String, Object> termValues = new HashMap<String, Object>();
1369                     OleCirculationDesk oleCirculationDesk = deliverRequestBo.getOlePickUpLocation();
1370                     String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1371                     String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1372                     termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1373                     termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1374                     termValues.put(OLEConstants.NOTICE, OLEConstants.NOTICE_ONHOLD);
1375                     if (LOG.isDebugEnabled()) {
1376                         LOG.debug("termValues.toString()" + termValues.toString());
1377                     }
1378                     EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1379                     String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1380                     if (LOG.isDebugEnabled()) {
1381                         LOG.debug("**************" + noticeType);
1382                     }
1383                     noticeType = noticeType != null ? noticeType : noticeTypeParam;
1384                     oleNoticeBo.setNoticeType(noticeType);
1385                     if(!patronId.equalsIgnoreCase(deliverRequestBo.getBorrowerId()) && noticesList.size()>0){
1386                         generateNoticesBasedOnNoticeType(noticesList,OLEConstants.NOTICE_ONHOLD);
1387                         patronId = deliverRequestBo.getBorrowerId();
1388                         noticesList =  new ArrayList<>();
1389                     }
1390                     noticesList.add(oleNoticeBo);
1391                     // To do send Notice
1392                     deliverRequestBo.setOleItem(null);
1393                     oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(deliverRequestBo);
1394                     oleDeliverRequestBo.setOnHoldNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1395                     finalDeliverRequestBoList.add(oleDeliverRequestBo);
1396                 }
1397             }
1398         }
1399         if(noticesList.size()>0){
1400             generateNoticesBasedOnNoticeType(noticesList,OLEConstants.NOTICE_ONHOLD);
1401         }
1402         getBusinessObjectService().save(finalDeliverRequestBoList);
1403     }
1404 
1405     private void generateNoticesBasedOnNoticeType(List<OleNoticeBo> noticesList,String noticeName) throws Exception{
1406         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1407         OleNoticeBo oleNoticeBo = noticesList.get(0);
1408         String noticeType = oleNoticeBo.getNoticeType();
1409         if (noticeType != null && (noticeType.equalsIgnoreCase(OLEConstants.EMAIL) || noticeType.equalsIgnoreCase(OLEConstants.MAIL))) {
1410             if (LOG.isDebugEnabled()) {
1411                 LOG.debug("noticesList.size()" + noticesList.size());
1412             }
1413             oleDeliverBatchService.getPdfNoticeForPatron(noticesList);
1414         }
1415         if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1416             String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1417             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1418                 fromAddress = OLEConstants.KUALI_MAIL;
1419             }
1420             if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
1421                 List list = oleDeliverBatchService.getNoticeForPatron(noticesList);
1422                 String content = list.toString();
1423                 content = content.replace('[', ' ');
1424                 content = content.replace(']', ' ');
1425                 if (!content.trim().equals("")) {
1426                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1427                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
1428                 } else {
1429                     if (LOG.isDebugEnabled()) {
1430                         LOG.debug("Notice Details" + noticesList);
1431                     }
1432                 }
1433                 if (LOG.isDebugEnabled()) {
1434                     LOG.debug("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1435                 }
1436             }
1437         } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1438             Map map = oleDeliverBatchService.getSMSForPatron(noticesList);
1439             HashMap sms = (HashMap) map.get(noticeName);
1440             Iterator it = sms.entrySet().iterator();
1441             while (it.hasNext()) {
1442                 Map.Entry pairs = (Map.Entry) it.next();
1443                 String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1444                 OleSms oleSms = new OleSms();
1445                 oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1446             }
1447         }
1448     }
1449     public void generateRequestExpirationNotice() throws Exception {
1450         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb)SpringContext.getBean("oleLoanDao");
1451         Collection oleDeliverRequestBoList = oleLoanDocumentDaoOjb.getExpiredRequests();
1452         SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1453         EntityTypeContactInfoBo entityTypeContactInfoBo;
1454         List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1455         Item item;
1456         String noticeType = null;
1457         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1458         boolean firstTime = true;
1459         String patronId ="";
1460         String noticeTypeParam = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RQST_EXPR_NOTICE_TYPE);
1461         if (oleDeliverRequestBoList.size() > 0) {
1462             for (Object obj : oleDeliverRequestBoList) {
1463                 OleDeliverRequestBo deliverRequestBo = (OleDeliverRequestBo) obj;
1464                 if(firstTime){
1465                     patronId= deliverRequestBo.getBorrowerId();
1466                     firstTime = false;
1467                 }
1468                 if (getDocstoreUtil().isItemAvailableInDocStore(deliverRequestBo)) {
1469                     //  processItem(deliverRequestBo);
1470                     item = deliverRequestBo.getOleItem();
1471                     if (LOG.isDebugEnabled()) {
1472                         LOG.debug("Expiration Date :" + deliverRequestBo.getRequestExpiryDate());
1473                     }
1474                     if (deliverRequestBo.getOlePatron().isCourtesyNotice()) {
1475                         if (LOG.isDebugEnabled()) {
1476                             LOG.debug("Inside Expiration Date :" + deliverRequestBo.getRequestExpiryDate());
1477                         }
1478                         entityTypeContactInfoBo = deliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1479                         oleNoticeBo = new OleNoticeBo();
1480                         oleNoticeBo.setAuthor(deliverRequestBo.getAuthor());
1481                         oleNoticeBo.setCirculationDeskAddress("");
1482                         oleNoticeBo.setCirculationDeskName("");
1483                         oleNoticeBo.setCirculationDeskEmailAddress("");
1484                         oleNoticeBo.setCirculationDeskPhoneNumber("");
1485                         oleNoticeBo.setPatronName(deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + deliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1486                         oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1487                         oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1488                         oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1489                         oleNoticeBo.setItemCallNumber(deliverRequestBo.getCallNumber() != null ? deliverRequestBo.getCallNumber() : "");
1490                         oleNoticeBo.setItemShelvingLocation(deliverRequestBo.getShelvingLocation() != null ? deliverRequestBo.getShelvingLocation() : "");
1491                         oleNoticeBo.setItemId(deliverRequestBo.getItemId() != null ? deliverRequestBo.getItemId() : "");
1492                         oleNoticeBo.setTitle(deliverRequestBo.getTitle() != null ? deliverRequestBo.getTitle() : "");
1493                         oleNoticeBo.setOleItem(item);
1494                         oleNoticeBo.setOlePatron(deliverRequestBo.getOlePatron());
1495                         oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1496                         oleNoticeBo.setNewDueDate(new Date());
1497                         oleNoticeBo.setOriginalDueDate(new Date());
1498                         oleNoticeBo.setNoticeName(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1499                         String noticeContent = getLoanProcessor().getParameter(OLEParameterConstants.EXPIRED_BODY);
1500                         oleNoticeBo.setNoticeSpecificContent(noticeContent);
1501                       //  noticesList.add(oleNoticeBo);
1502                         String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1503                         HashMap<String, Object> termValues = new HashMap<String, Object>();
1504                         OleCirculationDesk oleCirculationDesk = deliverRequestBo.getOlePickUpLocation();
1505                         OlePatronDocument olePatronDocument = deliverRequestBo.getOlePatron();
1506                         String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1507                         String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1508                         termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1509                         termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1510                         termValues.put(OLEConstants.NOTICE, OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1511                         if (LOG.isDebugEnabled()) {
1512                             LOG.debug("termValues.toString()" + termValues.toString());
1513                         }
1514                         EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
1515                         noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1516                         if (LOG.isDebugEnabled()) {
1517                             LOG.debug("**************" + noticeType);
1518                         }
1519                         noticeType = noticeType != null ? noticeType : noticeTypeParam;
1520                         oleNoticeBo.setNoticeType(noticeType);
1521                         oleNoticeBo.setNoticeType(noticeType);
1522                         if(!patronId.equalsIgnoreCase(deliverRequestBo.getBorrowerId()) && noticesList.size()>0){
1523                             generateNoticesBasedOnNoticeType(noticesList,OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1524                             patronId = deliverRequestBo.getBorrowerId();
1525                             noticesList =  new ArrayList<>();
1526                         }
1527                         noticesList.add(oleNoticeBo);
1528                     }
1529                 }
1530             }
1531             if(noticesList.size()>0){
1532                 generateNoticesBasedOnNoticeType(noticesList,OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1533             }
1534         }
1535     }
1536 
1537     private java.sql.Date dateAdd(java.sql.Date in, int daysToAdd) {
1538         if (in == null) {
1539             return null;
1540         }
1541         GregorianCalendar cal = new GregorianCalendar();
1542         cal.setTime(in);
1543         cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
1544         return new java.sql.Date(cal.getTime().getTime());
1545     }
1546 
1547     public void deletingExpiredRequests() {
1548         LOG.debug("Inside deletingExpiredRequests");
1549         List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1550         List<OleDeliverRequestBo> newOleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1551         try {
1552             oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findAll(OleDeliverRequestBo.class);
1553             getBusinessObjectService().delete(oleDeliverRequestBoList);
1554             SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1555             for (int i = 0; i < oleDeliverRequestBoList.size(); i++) {
1556                 if ((fmt.format(oleDeliverRequestBoList.get(i).getRequestExpiryDate())).compareTo(fmt.format(new Date(System.currentTimeMillis()))) > 0) {
1557                     newOleDeliverRequestBoList.add(oleDeliverRequestBoList.get(i));
1558                 }
1559             }
1560             getBusinessObjectService().save(newOleDeliverRequestBoList);
1561         } catch (Exception e) {
1562             getBusinessObjectService().save(oleDeliverRequestBoList);
1563             LOG.error("Exception while deleting expired requests", e);
1564         }
1565     }
1566 
1567     private Item getItem(String itemUUID) {
1568         LOG.debug("Inside getItem");
1569         try {
1570             // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
1571             String itemXml = getLoanProcessor().getItemXML(itemUUID);
1572             Item oleItem = getLoanProcessor().getItemPojo(itemXml);
1573             return oleItem;
1574         } catch (Exception e) {
1575             LOG.error("Item not available in doc store", e);
1576         }
1577         return null;
1578     }
1579 
1580 
1581     private OleNoticeBo setPatronDetailsForNotice(OleNoticeBo oleNoticeBo, OlePatronDocument olePatronDocument) {
1582         LOG.debug("Inside setPatronDetailsForNotice");
1583         if (oleNoticeBo.getAuthor() != null && olePatronDocument.getOlePatronId() != null) {
1584             oleNoticeBo.setPatronName(olePatronDocument.getName().getFirstName());
1585             if (olePatronDocument.getAddresses().size() > 0) {
1586                 oleNoticeBo.setPatronAddress(olePatronDocument.getAddresses().get(0).getLine1() + "/n" + olePatronDocument.getAddresses().get(0).getLine2() + "/n" + olePatronDocument.getAddresses().get(0).getCity());
1587             }
1588             oleNoticeBo.setPatronEmailAddress(olePatronDocument.getEmailAddress());
1589             oleNoticeBo.setPatronPhoneNumber(olePatronDocument.getPhoneNumber());
1590         }
1591         return oleNoticeBo;
1592     }
1593 
1594 
1595     private void createRequestHistoryRecord(String requestId, String OperatorId, String loanTransactionNumber) {
1596         LOG.debug("Inside createRequestHistoryRecord");
1597         Map<String, String> requestMap = new HashMap<String, String>();
1598         requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
1599         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1600         if (oleDeliverRequestBoList.size() > 0) {
1601             OleDeliverRequestBo oleDeliverRequestBo = oleDeliverRequestBoList.get(0);
1602             OleDeliverRequestHistoryRecord oleDeliverRequestHistoryRecord = new OleDeliverRequestHistoryRecord();
1603             oleDeliverRequestHistoryRecord.setRequestId(oleDeliverRequestBo.getRequestId());
1604             oleDeliverRequestHistoryRecord.setItemId(oleDeliverRequestBo.getItemId());
1605             oleDeliverRequestHistoryRecord.setArchiveDate(new java.sql.Date(System.currentTimeMillis()));
1606             oleDeliverRequestHistoryRecord.setPickUpLocationCode(oleDeliverRequestBo.getPickUpLocationCode());
1607             oleDeliverRequestHistoryRecord.setOperatorId(OperatorId);
1608             oleDeliverRequestHistoryRecord.setDeliverRequestTypeCode(oleDeliverRequestBo.getRequestTypeCode());
1609             oleDeliverRequestHistoryRecord.setPoLineItemNumber("");
1610             oleDeliverRequestHistoryRecord.setLoanTransactionId(loanTransactionNumber);
1611             //oleDeliverRequestHistoryRecord.setMachineId(""); //commented for jira OLE-5675
1612             getBusinessObjectService().save(oleDeliverRequestHistoryRecord);
1613         }
1614         getBusinessObjectService().delete(oleDeliverRequestBoList);
1615     }
1616 
1617     public OleDeliverRequestBo getOleDeliverRequestBo(String itemUUID) {
1618 
1619         LOG.debug("Inside getOleDeliverRequestBo method");
1620         Map<String, String> requestMap = new HashMap<String, String>();
1621         requestMap.put(OLEConstants.ITEM_UUID, itemUUID);
1622         List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1623         if (oleDeliverRequestBoList.size() > 0)
1624             return oleDeliverRequestBoList.get(0);
1625         return null;
1626     }
1627 
1628     public String getPatronPreferredAddress(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1629         LOG.debug("Inside the getPatronPreferredAddress method");
1630         String address = "";
1631         if (entityTypeContactInfoBo.getAddresses() != null) {
1632             for (int i = 0; i < entityTypeContactInfoBo.getAddresses().size(); i++) {
1633                 if (entityTypeContactInfoBo.getAddresses().get(i).isDefaultValue()) {
1634                     if (entityTypeContactInfoBo.getAddresses().get(i).getLine1() != null)
1635                         if (!entityTypeContactInfoBo.getAddresses().get(i).getLine1().isEmpty())
1636                             address += entityTypeContactInfoBo.getAddresses().get(i).getLine1() + ",";
1637 
1638                     if (entityTypeContactInfoBo.getAddresses().get(i).getLine2() != null)
1639                         if (!entityTypeContactInfoBo.getAddresses().get(i).getLine2().isEmpty())
1640                             address += entityTypeContactInfoBo.getAddresses().get(i).getLine2() + ",";
1641 
1642                     if (entityTypeContactInfoBo.getAddresses().get(i).getLine3() != null)
1643                         if (!entityTypeContactInfoBo.getAddresses().get(i).getLine3().isEmpty())
1644                             address += entityTypeContactInfoBo.getAddresses().get(i).getLine3() + ",";
1645 
1646                     if (entityTypeContactInfoBo.getAddresses().get(i).getCity() != null)
1647                         if (!entityTypeContactInfoBo.getAddresses().get(i).getCity().isEmpty())
1648                             address += entityTypeContactInfoBo.getAddresses().get(i).getCity() + ",";
1649 
1650                     if (entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode() != null)
1651                         if (!entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode().isEmpty())
1652                             address += entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode() + ",";
1653 
1654                     if (entityTypeContactInfoBo.getAddresses().get(i).getCountryCode() != null)
1655                         if (!entityTypeContactInfoBo.getAddresses().get(i).getCountryCode().isEmpty())
1656                             address += entityTypeContactInfoBo.getAddresses().get(i).getCountryCode() + ",";
1657 
1658                     if (entityTypeContactInfoBo.getAddresses().get(i).getPostalCode() != null)
1659                         if (!entityTypeContactInfoBo.getAddresses().get(i).getPostalCode().isEmpty())
1660                             address += entityTypeContactInfoBo.getAddresses().get(i).getPostalCode();
1661                 }
1662             }
1663         }
1664 
1665         return address;
1666     }
1667 
1668     public String getPatronHomePhoneNumber(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1669         LOG.debug("Inside the getPatronHomePhoneNumber method");
1670         String phoneNumber = "";
1671         if (entityTypeContactInfoBo.getPhoneNumbers() != null) {
1672             for (int j = 0; j < entityTypeContactInfoBo.getPhoneNumbers().size(); j++) {
1673                 if (entityTypeContactInfoBo.getPhoneNumbers().get(j).getPhoneTypeCode().equalsIgnoreCase("HM")) {
1674                     phoneNumber = (entityTypeContactInfoBo.getPhoneNumbers().get(j).getPhoneNumber());
1675                 }
1676             }
1677         }
1678         return phoneNumber;
1679     }
1680 
1681     public String getPatronHomeEmailId(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1682         LOG.debug("Inside the getPatronHomeEmailId method");
1683         String emailId = "";
1684         if (entityTypeContactInfoBo.getEmailAddresses() != null) {
1685             for (int j = 0; j < entityTypeContactInfoBo.getEmailAddresses().size(); j++) {
1686                 if (entityTypeContactInfoBo.getEmailAddresses().get(j).getDefaultValue()) {
1687                     emailId = (entityTypeContactInfoBo.getEmailAddresses().get(j).getEmailAddress());
1688                     break;
1689                 }
1690             }
1691         }
1692         return emailId;
1693     }
1694 
1695     private static int determineDifferenceInDays(Date currentDate, Date dueDate) {
1696         Calendar calendar1 = Calendar.getInstance();
1697         calendar1.setTime(dueDate);
1698         Calendar calendar2 = Calendar.getInstance();
1699         calendar2.setTime(currentDate);
1700         long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
1701         return (int) (diffInMillis / (24 * 1000 * 60 * 60));
1702     }
1703 
1704 
1705     public void generateNotices() throws Exception {
1706         Long b1 = System.currentTimeMillis();
1707         if (LOG.isDebugEnabled()) {
1708             LOG.debug("************---------START TIME OF GENERATE NOTICE SERVICE------" + System.currentTimeMillis());
1709         }
1710         DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1711         String courtesyInterval = getIntervalForCourtesyNotice();
1712         OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb)SpringContext.getBean("oleLoanDao");
1713         List<OleLoanDocument> courtesyNotice = new ArrayList<>();
1714         List<OleLoanDocument> overdueNotice = new ArrayList<>();
1715         try {
1716             overdueNotice=oleLoanDocumentDaoOjb.getLoanDocumentsForNoticeGeneration(OLEConstants.NOTICE_OVERDUE);
1717             try{
1718             overdueNotice = getLoanDocumentWithItemInfo((List<OleLoanDocument>)overdueNotice);
1719             }catch (Exception e){
1720                 LOG.error(e,e);
1721                 throw new Exception("Exception occured while fetching data from solr");
1722             }
1723             List<OleLoanDocument> documents = new ArrayList<>();
1724             List<String> itemIds = new ArrayList<>();
1725             if (overdueNotice != null && overdueNotice.size()>0) {
1726                 boolean firstTime = true;
1727                 String patronId="";
1728                 for (Object obj : overdueNotice) {
1729                     OleLoanDocument loanDocument = (OleLoanDocument) obj;
1730                     if(firstTime){
1731                        patronId=loanDocument.getPatronId();
1732                     }
1733                     if(patronId!=null && patronId.equals(loanDocument.getPatronId()) ){
1734                         documents.add(loanDocument);
1735                         itemIds.add(loanDocument.getItemUuid());
1736                     } else {
1737                         generateNoticeForOverdueAndCourtesy(patronId,documents,true);
1738                         documents = new ArrayList<>();
1739                         itemIds =  new ArrayList<>();
1740                         documents.add(loanDocument);
1741                         itemIds.add(loanDocument.getItemUuid());
1742                         patronId=loanDocument.getPatronId();
1743                     }
1744                     firstTime=false;
1745                 }
1746                 generateNoticeForOverdueAndCourtesy(patronId,documents,true);
1747             }
1748             courtesyNotice=oleLoanDocumentDaoOjb.getLoanDocumentsForNoticeGeneration(OLEConstants.NOTICE_COURTESY);
1749             try{
1750             courtesyNotice=getLoanDocumentWithItemInfo((List<OleLoanDocument>)courtesyNotice);
1751         }catch (Exception e){
1752             LOG.error(e,e);
1753             throw new Exception("Exception occured while fetching data from solr");
1754         }
1755             documents = new ArrayList<>();
1756             itemIds = new ArrayList<>();
1757             if (courtesyNotice != null && courtesyNotice.size()>0) {
1758                 boolean firstTime = true;
1759                 String patronId="";
1760                 for (Object obj : courtesyNotice) {
1761                     OleLoanDocument loanDocument = (OleLoanDocument) obj;
1762                     if(firstTime){
1763                         patronId=loanDocument.getPatronId();
1764                     }
1765                     if(patronId!=null && patronId.equals(loanDocument.getPatronId()) ){
1766                         documents.add(loanDocument);
1767                         itemIds.add(loanDocument.getItemUuid());
1768                     } else {
1769                         generateNoticeForOverdueAndCourtesy(patronId,documents,false);
1770                         documents = new ArrayList<>();
1771                         itemIds =  new ArrayList<>();
1772                         documents.add(loanDocument);
1773                         itemIds.add(loanDocument.getItemUuid());
1774                         patronId=loanDocument.getPatronId();
1775                     }
1776                     firstTime=false;
1777                 }
1778                 generateNoticeForOverdueAndCourtesy(patronId,documents,false);
1779             }
1780         } catch (Exception e){
1781            LOG.error("Error while preparing Patron Map using PersistenceBroker ----> generateOverDueNotice()"+e.getMessage() +e);
1782         }
1783         Long b2 = System.currentTimeMillis();
1784         Long total = b2 - b1;
1785         LOG.info("The time generating overdue/courtesy notice time:"+total);
1786 
1787     }
1788 
1789     public void generateNoticeForOverdueAndCourtesy(String patronId, List<OleLoanDocument> oleLoanDocuments,boolean overdue){
1790         Map<String, String> patronMap = new HashMap<String, String>();
1791         patronMap.put("olePatronId",patronId);
1792         List<OlePatronDocument> olePatronDocuments=(List<OlePatronDocument>)KRADServiceLocator.getBusinessObjectService().findMatching(OlePatronDocument.class,patronMap);
1793         if(olePatronDocuments!=null && olePatronDocuments.size()>0){
1794             OlePatronDocument olePatronDocument=olePatronDocuments.get(0);
1795             if(oleLoanDocuments!=null && oleLoanDocuments.size()>0){
1796                 getNoticeList(oleLoanDocuments,olePatronDocument,overdue);
1797             }
1798         }
1799     }
1800 
1801     public void generateHoldCourtesyNotice() throws Exception {
1802         List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) KRADServiceLocator.getBusinessObjectService().findAll(OleDeliverRequestBo.class);
1803         for (OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBos) {
1804             List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
1805             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1806             if (getDocstoreUtil().isItemAvailableInDocStore(oleDeliverRequestBo)) {
1807                 Item oleItem = oleDeliverRequestBo.getOleItem();
1808                 OleNoticeBo oleNoticeBo = new OleNoticeBo();
1809                 Date currentDate = new Date();
1810                 DateFormat formatter = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE_NOTICE);
1811                 Date itemStatusEffectiveDate = (Date) formatter.parse(oleItem.getItemStatusEffectiveDate());
1812                 Integer numberOfDaysOnHold = determineDifferenceInDays(currentDate, itemStatusEffectiveDate);
1813                 Integer maxNumberOfDaysOnHold = 0;
1814                 OleCirculationDesk oleCirculationDesk = null;
1815                 if (oleDeliverRequestBo.getPickUpLocationId() != null) {
1816                     oleCirculationDesk = getLoanProcessor().getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId());
1817                     String maxNumOfDays = oleCirculationDesk.getOnHoldDays() != null ? oleCirculationDesk.getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1818                     maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1819                 }
1820                 String itemTypeName = null;
1821                 if (oleItem.getTemporaryItemType() != null && oleItem.getTemporaryItemType().getCodeValue() != "") {
1822                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getTemporaryItemType().getCodeValue());
1823                     itemTypeName = oleInstanceItemType.getInstanceItemTypeCode();
1824                 }
1825                 else if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
1826                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
1827                     itemTypeName = oleInstanceItemType.getInstanceItemTypeCode();
1828                 }
1829                 OlePatronDocument olePatronDocument = oleDeliverRequestBo.getOlePatron();
1830                 String agendaName = OLEConstants.OleDeliverRequest.NOTICE_VALIDATION;
1831                 String patronId = olePatronDocument.getOlePatronId()!=null ?  olePatronDocument.getOlePatronId() : "";
1832                 String itemId = oleDeliverRequestBo.getItemId()!=null ?  oleDeliverRequestBo.getItemId() : "";
1833                 dataCarrierService.removeData(patronId+itemId);
1834                 HashMap<String, Object> termValues = new HashMap<String, Object>();
1835                 Date expirationDate = olePatronDocument!=null ? olePatronDocument.getExpirationDate():null;
1836                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1837                 termValues.put(OLEConstants.ITEM_TYPE, itemTypeName);
1838                 termValues.put(OLEConstants.OVERLAY_ITEM_LOCATION, oleDeliverRequestBo.getShelvingLocation());
1839                 termValues.put(OLEConstants.NO_OF_DAYS_ON_HOLD, numberOfDaysOnHold);
1840                 termValues.put(OLEConstants.MAX_NO_OF_DAYS_ONHOLD, maxNumberOfDaysOnHold);
1841                 termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
1842                 termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
1843                 termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
1844                 termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
1845                 termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
1846                 termValues.put(OLEConstants.REQUEST_TYPE,oleDeliverRequestBo.getRequestTypeCode());
1847                 termValues.put(OLEConstants.EXPIR_DATE,expirationDate);
1848                 termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
1849                 termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
1850                 if (oleItem.getItemStatus() != null)
1851                     termValues.put(OLEConstants.ITEM_STATUS, oleItem.getItemStatus().getCodeValue());
1852                 if (LOG.isDebugEnabled()) {
1853                     LOG.debug("termValues.toString()" + termValues.toString());
1854                 }
1855                 EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
1856                 String notice = (String) engineResults.getAttribute(OLEConstants.NOTICE);
1857                 if (LOG.isDebugEnabled()) {
1858                     LOG.debug("notice" + notice);
1859                 }
1860                 agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1861                 termValues = new HashMap<String, Object>();
1862                 String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1863                 String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1864                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1865                 termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1866                 termValues.put(OLEConstants.NOTICE, notice);
1867                 if (LOG.isDebugEnabled()) {
1868                     LOG.debug("termValues.toString()" + termValues.toString());
1869                 }
1870                 engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
1871                 dataCarrierService.removeData(patronId+itemId);
1872                 String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1873                 if (LOG.isDebugEnabled()) {
1874                     LOG.debug("**************" + noticeType);
1875                 }
1876                 OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1877                 if (notice != null) {
1878                     oleNoticeBo.setNoticeName(notice);
1879                     if (notice.equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
1880                         oleNoticeBo = getExpiredHoldNotice(oleDeliverRequestBo);
1881                         oleNoticeBo.setCirculationDeskName(deskLocationName);
1882                         oleNoticeBos.add(oleNoticeBo);
1883                         noticeType = noticeType == null ? getLoanProcessor().getParameter("HOLDCOURTESY_NOTICE_TYPE") : noticeType;
1884                     }
1885                     if (oleNoticeBos.size() > 0 && noticeType != null && (noticeType.equalsIgnoreCase(OLEConstants.EMAIL) || noticeType.equalsIgnoreCase(OLEConstants.MAIL))) {
1886                         oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
1887                     }
1888 
1889                 }
1890                 olePatronDocument = oleDeliverRequestBo.getOlePatron();
1891                 if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1892                     String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1893                     if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1894                         fromAddress = OLEConstants.KUALI_MAIL;
1895                     }
1896                     if (olePatronDocument.getEmailAddress() != null && !olePatronDocument.getEmailAddress().isEmpty()) {
1897                         List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
1898                         String noticeContent = list.toString();
1899                         noticeContent = noticeContent.replace('[', ' ');
1900                         noticeContent = noticeContent.replace(']', ' ');
1901                         if (!noticeContent.trim().equals("")) {
1902                             OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1903                             oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(noticeContent), true);
1904                         } else {
1905                             for (OleNoticeBo oleNoticeBo1 : oleNoticeBos) {
1906                                 if (LOG.isDebugEnabled()) {
1907                                     LOG.debug("Notice Type :" + oleNoticeBo1.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo1.getItemId() + " " + "Patron Name :" + oleNoticeBo1.getPatronName());
1908                                 }
1909                             }
1910                         }
1911 
1912                         if (LOG.isDebugEnabled()) {
1913                             LOG.debug("olePatronDocument.getEmailAddress()" + olePatronDocument.getEmailAddress());
1914                         }
1915                     }
1916                 } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1917                     //TODO : sms in progress.
1918                 }
1919             }
1920         }
1921     }
1922 
1923     public void deleteTemporaryHistoryRecord() throws Exception {
1924         List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePatronDocument.class);
1925         for (OlePatronDocument olePatronDocument : patronDocumentList) {
1926             Map<String, String> requestMap = new HashMap<String, String>();
1927             requestMap.put(OLEConstants.OlePatron.PATRON_ID, olePatronDocument.getOlePatronId());
1928             List<OleTemporaryCirculationHistory> oleTemporaryCirculationHistoryList = (List<OleTemporaryCirculationHistory>) KRADServiceLocator.getBusinessObjectService().findMatching(OleTemporaryCirculationHistory.class, requestMap);
1929             List<OleTemporaryCirculationHistory> deleteRecords = new ArrayList<OleTemporaryCirculationHistory>();
1930             for (OleTemporaryCirculationHistory oleTemporaryCirculationHistory : oleTemporaryCirculationHistoryList) {
1931                 String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1932                 HashMap<String, Object> termValues = new HashMap<String, Object>();
1933                 termValues.put(OLEConstants.OleDeliverRequest.IS_TEMPORARY_HISTORY_RECORD, String.valueOf(Boolean.TRUE));
1934                 DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1935                 dataCarrierService.addData(OLEConstants.DATE_CHECK_IN, oleTemporaryCirculationHistory.getCheckInDate());
1936                 EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
1937                 Boolean deleteRecord = (Boolean) engineResults.getAttribute(OLEConstants.OVERLAY_OPTION_DELETE);
1938                 if (deleteRecord != null && deleteRecord) {
1939                     deleteRecords.add(oleTemporaryCirculationHistory);
1940                 }
1941             }
1942             getBusinessObjectService().delete(deleteRecords);
1943         }
1944     }
1945 
1946     private OleNoticeBo getExpiredHoldNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
1947         LOG.debug("Expired Hold Notice");
1948         Item oleItem = oleDeliverRequestBo.getOleItem();
1949         EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1950         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1951         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleDeliverRequestBo.getItemUuid());
1952         String shelvingLocation = oleDeliverRequestBo.getShelvingLocation();
1953         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId());
1954         if (oleCirculationDesk != null)
1955             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
1956         else
1957             oleNoticeBo.setCirculationDeskName("");
1958         oleNoticeBo.setCirculationDeskAddress("");
1959         oleNoticeBo.setCirculationDeskEmailAddress("");
1960         oleNoticeBo.setCirculationDeskPhoneNumber("");
1961         oleNoticeBo.setCirculationDeskPhoneNumber("");
1962         oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1963         oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1964         oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1965         oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1966         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_HOLD_COURTESY);
1967         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.EXP_HOLD_NOTICE_CONTENT));
1968         oleNoticeBo.setTitle(item.getHolding().getBib().getTitle());
1969         oleNoticeBo.setAuthor(item.getHolding().getBib().getAuthor());
1970         /*oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
1971         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
1972         oleNoticeBo.setVolumeNumber(item.getVolumeNumber());
1973         oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
1974         //oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
1975         oleNoticeBo.setItemCallNumber((String) oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("") ? oleItem.getCallNumber().getNumber() : "");
1976         oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
1977         oleNoticeBo.setOleItem(oleItem);
1978         oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
1979       //  oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo, oleDeliverRequestBo.getOlePatron());
1980         oleDeliverRequestBo.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
1981         return oleNoticeBo;
1982     }
1983 
1984     private OleNoticeBo getCourtesyNotice(OleLoanDocument oleLoanDocument) throws Exception {
1985         LOG.debug("Courtesy Notice");
1986         oleLoanDocument.setCourtesyNoticeFlag(true);
1987         Map<String, String> map = new HashMap<String, String>();
1988         map.put(OLEConstants.LOAN_ID, oleLoanDocument.getLoanId());
1989         KRADServiceLocator.getBusinessObjectService().save(oleLoanDocument);
1990         EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1991         OleNoticeBo oleNoticeBo = new OleNoticeBo();
1992         //String itemId  = oleLoanDocument.getItemId();
1993         Item oleItem = oleLoanDocument.getOleItem();
1994         String shelvingLocation = oleLoanDocument.getItemLocation();
1995         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
1996         if (oleCirculationDesk != null)
1997             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
1998         else
1999             oleNoticeBo.setCirculationDeskName("");
2000         oleNoticeBo.setCirculationDeskAddress("");
2001         oleNoticeBo.setCirculationDeskEmailAddress("");
2002         oleNoticeBo.setCirculationDeskPhoneNumber("");
2003         oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
2004         oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2005         oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2006         oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2007         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_COURTESY);
2008         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.COURTESY_NOTICE_CONTENT));
2009        /* oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
2010         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
2011         oleNoticeBo.setTitle(oleLoanDocument.getTitle());
2012         oleNoticeBo.setAuthor(oleLoanDocument.getAuthor());
2013         oleNoticeBo.setVolumeNumber(oleLoanDocument.getItemVolumeNumber());
2014         oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
2015         // oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
2016         oleNoticeBo.setItemCallNumber(oleLoanDocument.getItemCallNumber());
2017         oleNoticeBo.setItemId(oleLoanDocument.getItemId());
2018         oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
2019         if (LOG.isDebugEnabled()) {
2020             LOG.debug("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
2021         }
2022         return oleNoticeBo;
2023     }
2024 
2025     private OleNoticeBo getOverdueNotice(OleLoanDocument oleLoanDocument) throws Exception {
2026         LOG.debug("Overdue Notice");
2027         EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
2028         OleNoticeBo oleNoticeBo = new OleNoticeBo();
2029         //   String itemId  = oleLoanDocument.getItemId();
2030         Item oleItem = oleLoanDocument.getOleItem();
2031         //  String itemUuid = oleItem.getItemIdentifier();
2032         //String shelvingLocation = oleLoanDocument.getItemLocation();
2033         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2034         if (oleCirculationDesk != null)
2035             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
2036         else
2037             oleNoticeBo.setCirculationDeskName("");
2038         oleNoticeBo.setCirculationDeskAddress("");
2039         oleNoticeBo.setCirculationDeskEmailAddress("");
2040         oleNoticeBo.setCirculationDeskPhoneNumber("");
2041         oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
2042         oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2043         oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2044         oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2045         oleNoticeBo.setNoticeName(OLEConstants.NOTICE_OVERDUE);
2046         oleNoticeBo.setNoticeSpecificContent(getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.OVERDUE_NOTICE_CONTENT));
2047         oleNoticeBo.setTitle(oleLoanDocument.getTitle());
2048         oleNoticeBo.setAuthor(oleLoanDocument.getAuthor());
2049         /*oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
2050         oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");*/
2051 
2052         //oleNoticeBo.setVolumeNumber((String) docStoreDetails.get(OLEConstants.VOL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.VOL_NUM) : "");
2053         String volume = (String) oleItem.getEnumeration() != null && !oleItem.getEnumeration().equals("") ? oleItem.getEnumeration() : "";
2054         String issue = new String(" ");
2055         String copyNumber = (String) oleItem.getCopyNumber() != null && !oleItem.getCopyNumber().equals("") ? oleItem.getCopyNumber() : "";
2056         oleNoticeBo.setVolumeIssueCopyNumber(volume + "/" + issue + "/" + copyNumber);
2057         oleNoticeBo.setItemShelvingLocation(oleLoanDocument.getItemLocation());
2058         if (oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("")) {
2059             oleNoticeBo.setItemCallNumber((String) oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().equals("") ? oleItem.getCallNumber().getNumber() : "");
2060         } else {
2061             oleNoticeBo.setItemCallNumber(getLoanProcessor().getItemCallNumber(oleItem, oleLoanDocument.getInstanceUuid()));
2062         }
2063         //oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
2064         oleNoticeBo.setItemId(oleLoanDocument.getItemId());
2065         //oleNoticeBo.setDueDate(oleLoanDocument.getLoanDueDate()!=null ? oleLoanDocument.getLoanDueDate().toString().substring(0, 10):null);
2066         oleNoticeBo.setDueDate(oleLoanDocument.getLoanDueDate()!=null ? oleLoanDocument.getLoanDueDate():null);
2067 
2068         oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
2069         if (LOG.isDebugEnabled()) {
2070             LOG.debug("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
2071         }
2072         int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
2073         noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
2074         if (LOG.isDebugEnabled()) {
2075             LOG.debug("Updated Loan Record : " + oleLoanDocument);
2076         }
2077         oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
2078         oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
2079         getBusinessObjectService().save(oleLoanDocument);
2080         return oleNoticeBo;
2081     }
2082 
2083     public void updateItem(Item oleItem, String itemUuid) throws Exception {
2084         ItemStatus itemStatus = new ItemStatus();
2085         itemStatus.setCodeValue(OLEConstants.OleDeliverRequest.MISSING);
2086         itemStatus.setFullValue(OLEConstants.OleDeliverRequest.MISSING);
2087         oleItem.setItemStatus(itemStatus);
2088         oleItem.setStaffOnlyFlag(true);
2089         String itemContent = new ItemOlemlRecordProcessor().toXML(oleItem);
2090         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2091         item.setId(itemUuid);
2092         item.setContent(itemContent);
2093         item.setCategory(OLEConstants.WORK_CATEGORY);
2094         item.setType(DocType.ITEM.getCode());
2095         item.setFormat(OLEConstants.OLEML_FORMAT);
2096         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2097     }
2098 
2099     public String getShelvingLocation(LocationLevel oleLocationLevel) {
2100         String location = null;
2101         if (oleLocationLevel != null) {
2102             if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
2103                 location = oleLocationLevel.getName();
2104             else
2105                 location = getShelvingLocation(oleLocationLevel.getLocationLevel());
2106         }
2107         if ("".equals(location) || location == null)
2108             return null;
2109         return location;
2110     }
2111 
2112 
2113     public String getIntervalForCourtesyNotice() {
2114         BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2115         Map<String, String> criteriaMap = new HashMap<String, String>();
2116         criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
2117         criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
2118         criteriaMap.put(OLEConstants.NAME, OLEParameterConstants.COURTESY_NOTICE_INTER);
2119         List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
2120         return parametersList.get(0).getValue();
2121     }
2122 
2123     public String getIntervalForOverdueNotice() {
2124         BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2125         Map<String, String> criteriaMap = new HashMap<String, String>();
2126         criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
2127         criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
2128         criteriaMap.put(OLEConstants.NAME, OLEConstants.OVERDUE_NOTICE_INTER);
2129         List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
2130         return parametersList.get(0).getValue();
2131     }
2132 
2133 
2134     private PatronBillPayment getPatronBillPayment(String patronId) {
2135         LOG.debug("Inside the getPatronBillPayment method");
2136         Map billMap = new HashMap();
2137         billMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, patronId);
2138         List<PatronBillPayment> patronBillPaymentList = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, billMap);
2139         return patronBillPaymentList != null && patronBillPaymentList.size() > 0 ? patronBillPaymentList.get(0) : null;
2140     }
2141 
2142     private OlePaymentStatus getPaymentStatus() {
2143         LOG.debug("Inside the getPaymentStatus method");
2144         Map statusMap = new HashMap();
2145         statusMap.put(OLEConstants.OleDeliverRequest.PAYMENT_STATUS_NAME, OLEConstants.PAYMENT_STATUS_OUTSTANDING);
2146         List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
2147         return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
2148     }
2149 
2150     private String getFeeTypeId(String feeTypeName) {
2151         LOG.debug("Inside the getOverdueFeeTypeId method");
2152         Map feeMap = new HashMap();
2153         feeMap.put(OLEConstants.FEE_TYPE_NAME, feeTypeName);
2154         List<OleFeeType> oleFeeTypes = (List<OleFeeType>) getBusinessObjectService().findMatching(OleFeeType.class, feeMap);
2155         return oleFeeTypes != null && oleFeeTypes.size() > 0 ? oleFeeTypes.get(0).getFeeTypeId() : null;
2156     }
2157 
2158     public String processItemType(String itemType) {
2159 
2160         LOG.debug("Inside process Item Type");
2161         Map<String, String> itemMap = new HashMap<String, String>();
2162         itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, itemType);
2163         List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) businessObjectService.findMatching(OleInstanceItemType.class, itemMap);
2164         if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
2165             OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
2166             return oleInstanceItemType.getInstanceItemTypeName();
2167         }
2168         return null;
2169     }
2170 
2171     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) {
2172         OLEPlaceRequest olePlaceRequest = new OLEPlaceRequest();
2173         OLEPlaceRequestConverter olePlaceRequestConverter = new OLEPlaceRequestConverter();
2174         ASRHelperServiceImpl asrHelperService = new ASRHelperServiceImpl();
2175         OleDeliverRequestBo oleDeliverRequestBo = new OleDeliverRequestBo();
2176         oleDeliverRequestBo.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
2177         OlePatronDocument olePatronDocument = null;
2178         Map<String, String> patronMap = new HashMap<String, String>();
2179         patronMap.put(OLEConstants.BARCODE, patronBarcode);
2180         OleNoticeBo oleNoticeBo = new OleNoticeBo();
2181         List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, patronMap);
2182         if (olePatronDocumentList.size() > 0) {
2183             olePatronDocument = olePatronDocumentList.get(0);
2184             oleDeliverRequestBo.setBorrowerId(olePatronDocument.getOlePatronId());
2185             oleDeliverRequestBo.setBorrowerBarcode(olePatronDocument.getBarcode());
2186             oleDeliverRequestBo.setOlePatron(olePatronDocument);
2187             EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
2188             try {
2189                 oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
2190                 oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
2191                 oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
2192                 oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
2193             } catch (Exception e) {
2194                 LOG.error("Exception", e);
2195                 if (LOG.isDebugEnabled()) {
2196                     LOG.debug("Exception Occured while setting the patron information for the patron . Patron Barcode : " + oleDeliverRequestBo.getBorrowerBarcode());
2197                 }
2198             }
2199         } else {
2200             olePlaceRequest.setCode("002");
2201             olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.NO_PATRON_INFO));
2202              return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2203         }
2204         if (requestType != null) {
2205             Map<String, String> requestTypeMap = new HashMap<String, String>();
2206             requestTypeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_CD, requestType);
2207             List<OleDeliverRequestType> oleDeliverRequestTypeList = (List<OleDeliverRequestType>) getBusinessObjectService().findMatching(OleDeliverRequestType.class, requestTypeMap);
2208             if (oleDeliverRequestTypeList != null && (oleDeliverRequestTypeList.size() > 0)) {
2209                 oleDeliverRequestBo.setRequestTypeId(oleDeliverRequestTypeList.get(0).getRequestTypeId());
2210                 oleDeliverRequestBo.setOleDeliverRequestType(oleDeliverRequestTypeList.get(0));
2211             } else{
2212                 olePlaceRequest.setCode("012");
2213                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_RQST_TYP));
2214                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2215             }
2216         }
2217         if (pickUpLocation != null) {
2218             Map<String, String> circulationDeskMap = new HashMap<String, String>();
2219             circulationDeskMap.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_CD, pickUpLocation);
2220             List<OleCirculationDesk> oleCirculationDeskList = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, circulationDeskMap);
2221             if (oleCirculationDeskList != null && oleCirculationDeskList.size() > 0) {
2222                 oleDeliverRequestBo.setPickUpLocationId(oleCirculationDeskList.get(0).getCirculationDeskId());
2223                 oleDeliverRequestBo.setPickUpLocationCode(oleCirculationDeskList.get(0).getCirculationDeskCode());
2224                 oleDeliverRequestBo.setOlePickUpLocation(oleCirculationDeskList.get(0));
2225             } else {
2226                 olePlaceRequest.setCode("013");
2227                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_PK_UP_LOCN));
2228                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2229             }
2230 
2231         }
2232         try {
2233             if (itemBarcode == null || (itemBarcode != null && itemBarcode.isEmpty())) {
2234                 olePlaceRequest.setCode("014");
2235                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2236                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2237 
2238             }
2239             oleDeliverRequestBo.setItemId(itemBarcode);
2240             oleDeliverRequestBo.setItemUuid(itemIdentifier);
2241             oleDeliverRequestBo.setItemStatus(OLEConstants.AVAILABLE);
2242             oleDeliverRequestBo.setItemType(itemType);
2243             oleDeliverRequestBo.setItemLocation(itemLocation);
2244             if(itemIdentifier == null || itemLocation == null || itemType == null){
2245                 Thread.sleep(500);
2246                 String itemUUID=null;
2247                 String holdingsId =null;
2248                 if(itemIdentifier==null){
2249                     try {
2250                         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2251                         org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
2252                         SearchResponse searchResponse = null;
2253                         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()), ""));
2254                         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
2255                         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode(), "id"));
2256                         searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
2257                         for (SearchResult searchResult : searchResponse.getSearchResults()) {
2258                             for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
2259                                 String fieldName = searchResultField.getFieldName();
2260                                 String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
2261                                 if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("holdings")) {
2262                                     holdingsId = fieldValue;
2263                                 } else {
2264                                     oleDeliverRequestBo.setItemUuid(fieldValue);
2265                                     itemUUID = fieldValue;
2266                                 }
2267                             }
2268                         }
2269                     } catch (Exception ex) {
2270                         GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_EXIST));
2271                         LOG.error(OLEConstants.ITEM_EXIST + ex);
2272                     }
2273                 }
2274                 if(itemUUID==null){
2275                     olePlaceRequest.setCode("014");
2276                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2277                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2278                 }
2279                 if(itemType==null || itemLocation ==null){
2280                     Map<String,Object> detailMap =retrieveBIbItemHoldingData(itemUUID);
2281                     Bib bib = (Bib)detailMap.get(OLEConstants.BIB);
2282                     Item item = (Item)detailMap.get(OLEConstants.ITEM);
2283                     OleHoldings oleHoldings = (OleHoldings)detailMap.get(OLEConstants.HOLDING);
2284                     org.kuali.ole.docstore.common.document.Item item1 = (org.kuali.ole.docstore.common.document.Item)detailMap.get("documentItem");
2285                     if(item != null){
2286                         oleDeliverRequestBo.setOleItem(item);
2287                         if(item.getCallNumber()!=null && item.getCallNumber().getNumber()!= null){
2288                             oleDeliverRequestBo.setCallNumber(item.getCallNumber().getNumber());
2289                         }
2290                         if(item.getCopyNumber()!=null){
2291                             oleDeliverRequestBo.setCopyNumber(item.getCopyNumber());
2292                         }
2293                         oleDeliverRequestBo.setVolumeNumber(item.getEnumeration()!=null ? item.getEnumeration() : "");
2294                     }
2295                     if(oleHoldings!=null ){
2296                         if( oleDeliverRequestBo.getCallNumber() == null && oleHoldings.getCallNumber()!=null  && oleHoldings.getCallNumber().getNumber()!=null){
2297                         oleDeliverRequestBo.setCallNumber(oleHoldings.getCallNumber().getNumber());
2298                         }
2299                         if( oleDeliverRequestBo.getCopyNumber() == null && oleHoldings.getCopyNumber()!=null){
2300                             oleDeliverRequestBo.setCopyNumber(oleHoldings.getCopyNumber());
2301                         }
2302                     }
2303                     if(itemLocation == null){
2304                         if(item1.getLocation()== null || (item1.getLocation()!=null && item1.getLocation().trim().isEmpty())){
2305                             itemLocation =getDocstoreUtil().getLocation(oleHoldings.getLocation(),new StringBuffer(""));
2306                         }else{
2307                             itemLocation = item1.getLocation();
2308                         }
2309                         oleDeliverRequestBo.setItemLocation(itemLocation);
2310                     }
2311                     if(item.getItemType()!=null){
2312                         oleDeliverRequestBo.setItemType(item.getItemType().getCodeValue());
2313                     }
2314                     if (item.getItemStatus() != null) {
2315                         oleDeliverRequestBo.setItemStatus(item.getItemStatus().getCodeValue());
2316                     }
2317 
2318                     if(bib!=null){
2319                         oleDeliverRequestBo.setTitle(bib.getTitle());
2320                         oleDeliverRequestBo.setAuthor(bib.getAuthor());
2321                     }
2322                 }
2323             }
2324 
2325             if(itemLocation!=null){
2326                 if (asrHelperService.isAnASRItem(itemLocation) && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && !oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))){
2327                     olePlaceRequest.setCode("700");
2328                     olePlaceRequest.setMessage("Cannot create "+oleDeliverRequestBo.getRequestTypeCode()+" for this item");
2329                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2330                 }else if(asrHelperService.isAnASRItem(itemLocation) && !oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS)) && oleDeliverRequestBo.getRequestTypeCode().equals(getLoanProcessor().getParameter(ASRConstants.ASR_TYP_RQST))){
2331                     olePlaceRequest.setCode("701");
2332                     olePlaceRequest.setMessage("Cannot create "+oleDeliverRequestBo.getRequestTypeCode()+" for this item");
2333                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2334                 }
2335                 Map<String,String> locationMap = getLocationMap(itemLocation);
2336                 oleDeliverRequestBo.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
2337                 oleDeliverRequestBo.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
2338                 oleDeliverRequestBo.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
2339                 oleDeliverRequestBo.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
2340                 oleDeliverRequestBo.setShelvingLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
2341             }
2342             oleDeliverRequestBo.setRequestCreator(OLENCIPConstants.OPERATOR);
2343             oleDeliverRequestBo.setOperatorCreateId(operatorId);
2344             oleDeliverRequestBo.setItemId(itemBarcode);
2345             if (!processOperator(operatorId)) {
2346                 olePlaceRequest.setCode("001");
2347                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVALID_OPRTR_ID));
2348                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2349             }
2350             processRequestTypeByPickUpLocation(oleDeliverRequestBo);
2351             String message = this.patronRecordExpired(oleDeliverRequestBo);
2352             if (message != null) {
2353                 olePlaceRequest.setCode("015");
2354                 olePlaceRequest.setMessage(message);
2355                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2356             }
2357             boolean requestRaised = this.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo);
2358             if (requestRaised){
2359                 {
2360                     olePlaceRequest.setCode("016");
2361                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_ALRDY_RAISD));
2362                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2363                 }
2364             }
2365             boolean itemEligible = this.isItemEligible(oleDeliverRequestBo);
2366             if (!itemEligible){
2367                 {
2368                     olePlaceRequest.setCode("017");
2369                     olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITM_NOT_LOAN));
2370                     return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2371                 }
2372             }
2373             boolean alreadyLoaned = this.isAlreadyLoaned(oleDeliverRequestBo);
2374             if (alreadyLoaned){
2375                 olePlaceRequest.setCode("018");
2376                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITM_LOAN_BY_PTRN));
2377                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2378             }
2379             boolean valid = false;
2380             EngineResults engineResult = this.executeEngineResults(oleDeliverRequestBo);
2381             if (engineResult != null) {
2382                 List<ResultEvent> allResults = engineResult.getAllResults();
2383                 if (allResults.size() > 0) {
2384                     for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
2385                         ResultEvent resultEvent = resultEventIterator.next();
2386                         if (resultEvent.getType().equals(RULE_EVALUATED))
2387                             valid |= resultEvent.getResult();
2388                     }
2389                     if ((oleDeliverRequestBo.getMessage() != null && !oleDeliverRequestBo.getMessage().isEmpty())) {
2390                         olePlaceRequest.setCode("500");
2391                         olePlaceRequest.setMessage(oleDeliverRequestBo.getMessage().replaceAll("<br/>",""));
2392                         return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2393                     }
2394 
2395                 }
2396             }
2397             OleDeliverRequestBo oleDeliverRequestBo1 = oleDeliverRequestBo;
2398             if (isItemAvailable(oleDeliverRequestBo1)) {
2399                 olePlaceRequest.setCode("019");
2400                 olePlaceRequest.setMessage(oleDeliverRequestBo1.getRequestTypeCode()+ OLEConstants.RQST_CONDITION +oleDeliverRequestBo1.getItemStatus());
2401                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2402             }
2403             oleDeliverRequestBo.setOleItem(null);
2404             this.reOrderQueuePosition(oleDeliverRequestBo1);
2405             boolean asrItem = asrHelperService.isAnASRItem(oleDeliverRequestBo.getItemLocation());
2406             if(asrItem && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS))) {
2407                 oleDeliverRequestBo.setAsrFlag(true);
2408                 oleDeliverRequestBo.setRequestStatus("1");
2409             }
2410             getBusinessObjectService().save(oleDeliverRequestBo1);
2411             List<OleDeliverRequestBo> oleDeliverRequestBoList=null;
2412             String requestId = "";
2413             try {
2414             Map<String, String> requestMap = new HashMap<String, String>();
2415             requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, olePatronDocument.getOlePatronId());
2416             requestMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemBarcode);
2417             oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2418             if (oleDeliverRequestBoList.size() > 0) {
2419                 requestId = ":"+OLEConstants.OleDeliverRequest.REQUEST_ID+":" + oleDeliverRequestBoList.get(0).getRequestId();
2420             }
2421                 if (!oleDeliverRequestBo.getRequestTypeId().equals("8")) {
2422                     oleDeliverRequestBo = updateLoanDocument(oleDeliverRequestBo);
2423                     oleDeliverRequestBo.setOlePatron(null);
2424                     oleDeliverRequestBo.setOleProxyPatron(null);
2425                 }
2426             if (LOG.isDebugEnabled()) {
2427                 LOG.debug("Request Raised Succesfully" + requestId);
2428             }
2429                 if (oleDeliverRequestBo.getOperatorModifiedId() == null) {
2430 
2431                     if(oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2") ) {
2432                         try {
2433                             oleDeliverRequestBo = generateRecallNotice(oleDeliverRequestBo);
2434                             oleDeliverRequestBo.setRecallNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
2435                         } catch (Exception e) {
2436                             LOG.error("Error occured while generating the notices " + e, e);  //To change body of catch statement use File | Settings | File Templates.
2437                         }
2438                     }
2439 
2440                 }
2441             if(asrItem && oleDeliverRequestBo.getItemStatus().equals(getLoanProcessor().getParameter(ASRConstants.ASR_REQUEST_ITEM_STATUS))){
2442 
2443                 ASRTypeRequest asrTypeRequest = new ASRTypeRequest();
2444                 asrTypeRequest.setRequestId(oleDeliverRequestBoList.get(0).getRequestId());
2445                 asrTypeRequest.setRequestStatus("1");
2446                 asrTypeRequest.setPickUpLocation(oleDeliverRequestBo.getPickUpLocationCode());
2447                 asrTypeRequest.setItemId(oleDeliverRequestBo.getItemId());
2448                 asrTypeRequest.setPatronId(oleDeliverRequestBo.getBorrowerId());
2449                 getBusinessObjectService().save(asrTypeRequest);
2450             } else if(externalItem){
2451                 String noticeSendParameter = getLoanProcessor().getParameter(OLEParameterConstants.NCIP_ACCEPT_ITEM_NOTICE_INDICATOR);
2452                 if(noticeSendParameter!=null && (noticeSendParameter.trim().isEmpty() || noticeSendParameter.equalsIgnoreCase("Y"))){
2453             String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
2454             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
2455                 fromAddress = OLEConstants.KUALI_MAIL;
2456             }
2457             oleNoticeBo.setNoticeName(OLEConstants.PICKUP_NOTICE);
2458             Date pickupDate = new java.sql.Date(System.currentTimeMillis());
2459             if(oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays()!=null){
2460                 pickupDate = addDate(new java.sql.Date(System.currentTimeMillis()), new Integer(oleDeliverRequestBo.getOlePickUpLocation().getOnHoldDays()));
2461             }
2462             oleNoticeBo.setNoticeSpecificContent(OLEConstants.PICKUP_NOTICE_START_CONTENT + oleDeliverRequestBo.getOlePickUpLocation().getCirculationDeskPublicName() + OLEConstants.PICKUP_NOTICE_MIDDLE_CONTENT + pickupDate + OLEConstants.PICKUP_NOTICE_FINAL_CONTENT);
2463             oleNoticeBo.setAuthor(author);
2464             oleNoticeBo.setItemCallNumber(callNumber);
2465             oleNoticeBo.setItemId(itemBarcode);
2466             oleNoticeBo.setTitle(title);
2467             OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
2468             String content = oleDeliverBatchService.getEmailPickUpNotice(oleNoticeBo);
2469                  try  {
2470                 if (!content.trim().equals("")) {
2471                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
2472                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(content), true);
2473                     if (LOG.isDebugEnabled()) {
2474                         LOG.debug("Mail send Successfully to " + oleNoticeBo.getPatronEmailAddress());
2475                     }
2476                     oleDeliverBatchService.getPdfPickUpNotice(oleNoticeBo);
2477                 } else {
2478                     if (LOG.isDebugEnabled()) {
2479                         LOG.debug("Notice Type :" + oleNoticeBo.getNoticeName() + "  " + "Item Barcode : " + oleNoticeBo.getItemId() + " " + "Patron Name :" + oleNoticeBo.getPatronName());
2480                     }
2481                 }
2482                  }catch(Exception e){
2483                      LOG.error("Exception", e);
2484                      olePlaceRequest.setCode("020");
2485                      olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2486                      olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.NTCE_PRBLM);
2487                      olePlaceRequest.setRequestId(oleDeliverRequestBoList.get(0).getRequestId());
2488                      olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2489                      return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2490                  }
2491             }}
2492 
2493             }
2494             catch (Exception e) {
2495                 LOG.error("Exception", e);
2496                 olePlaceRequest.setCode("020");
2497                 olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2498                 olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId + OLEConstants.RQST_PRBLM);
2499                 olePlaceRequest.setRequestId(oleDeliverRequestBoList.get(0).getRequestId());
2500                 olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2501                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2502 
2503             }
2504             olePlaceRequest.setCode("021");
2505             olePlaceRequest.setRequestId(oleDeliverRequestBoList.get(0).getRequestId());
2506             olePlaceRequest.setAvailableDate(getAvailableDate(itemBarcode));
2507             olePlaceRequest.setQueuePosition(String.valueOf(oleDeliverRequestBo.getBorrowerQueuePosition()));
2508             olePlaceRequest.setMessage(OLEConstants.RQST_SUCCESS + requestId);
2509             return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2510         } catch (Exception e) {
2511             LOG.error("Exception", e);
2512             if (e.getMessage()!=null && e.getMessage().equalsIgnoreCase("Item barcode does not exist.")) {
2513                 olePlaceRequest.setCode("014");
2514                 olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
2515                 return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2516             }
2517             olePlaceRequest.setCode("023");
2518             olePlaceRequest.setMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.RQST_FAIL));
2519             return olePlaceRequestConverter.generatePlaceRequestXml(olePlaceRequest);
2520         }
2521     }
2522 
2523     public String getAvailableDate(String itemBarcode) {
2524         Map<String, String> loanMap = new HashMap<>();
2525         SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
2526         simpleDateFormat.applyPattern(OLEConstants.GREGORIAN_PATTERN);
2527         loanMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemBarcode);
2528         String date = null;
2529         List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, loanMap);
2530         if (loanDocuments.size() > 0) {
2531             if (loanDocuments.get(0).getLoanDueDate() != null) {
2532                 date = loanDocuments.get(0).getLoanDueDate().toString();
2533             } else {
2534                 date = simpleDateFormat.format(new Timestamp(2025, 1, 1, 1, 1, 1, 1));
2535             }
2536         } else {
2537             date = simpleDateFormat.format(new Timestamp(new java.sql.Date(System.currentTimeMillis()).getTime()));
2538         }
2539         return date;
2540     }
2541 
2542 
2543     public java.sql.Date addDate(java.sql.Date in, int daysToAdd) {
2544         if (in == null) {
2545             return null;
2546         }
2547         GregorianCalendar cal = new GregorianCalendar();
2548         cal.setTime(in);
2549         cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
2550         return new java.sql.Date(cal.getTime().getTime());
2551     }
2552 
2553     public EngineResults executeEngineResults(OleDeliverRequestBo oleDeliverRequestBo) {
2554         List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
2555         List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
2556         List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
2557         List<OleDeliverRequestBo> asrList = new ArrayList<OleDeliverRequestBo>();
2558         List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
2559         Engine engine = KrmsApiServiceLocator.getEngine();
2560         EngineResults engineResult = null;
2561         HashMap<String, Object> agendaValue = new HashMap<String, Object>();
2562         agendaValue.put(OLEConstants.NAME_NM, OLEConstants.REQUEST_AGENDA_NM);
2563         List<AgendaBo> agendaBos = (List<AgendaBo>) KRADServiceLocator.getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
2564         if (agendaBos != null && agendaBos.size() > 0) {
2565             AgendaBo agendaBo = agendaBos.get(0);
2566             HashMap<String, String> map = new HashMap<String, String>();
2567             map.put(OLEConstants.AGENDA_NAME, agendaBo.getName());
2568             List<MatchBo> matchBos = (List<MatchBo>) KRADServiceLocator.getBusinessObjectService().findMatching(MatchBo.class, map);
2569 
2570             SelectionCriteria selectionCriteria =
2571                     SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()),
2572                             getAgendaContext(OLEConstants.REQUEST_AGENDA_NM));
2573 
2574             ExecutionOptions executionOptions = new ExecutionOptions();
2575             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
2576 
2577             Facts.Builder factBuilder = Facts.Builder.create();
2578 
2579             String borrowerType = "";
2580             if (oleDeliverRequestBo.getOlePatron() != null && oleDeliverRequestBo.getOlePatron().getOleBorrowerType() != null) {
2581                 borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeCode();
2582             }
2583             String itemType = oleDeliverRequestBo.getItemType();
2584 
2585             String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
2586 
2587             String requestType = oleDeliverRequestBo.getRequestTypeCode();
2588 
2589             String location = oleDeliverRequestBo.getShelvingLocation();
2590             OleLoanDocument oleLoanDocument = getLoanProcessor().getOleLoanDocumentUsingItemUUID(oleDeliverRequestBo.getItemUuid());
2591             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
2592             dataCarrierService.addData(OLEConstants.LOANED_DATE, oleLoanDocument != null ? oleLoanDocument.getCreateDate() : null);
2593             dataCarrierService.addData(OLEConstants.DUE_DATE,oleLoanDocument!=null?oleLoanDocument.getLoanDueDate():null);
2594             String patronId = oleDeliverRequestBo.getBorrowerId()!=null ?  oleDeliverRequestBo.getBorrowerId() : "";
2595             String itemId = oleDeliverRequestBo.getItemId()!=null ?  oleDeliverRequestBo.getItemId() : "";
2596             dataCarrierService.removeData(patronId+itemId);
2597             String borrowerId = oleDeliverRequestBo.getBorrowerId();
2598             Map<String, String> requestMap = new HashMap<String, String>();
2599             requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
2600             if (requestTypeId != null && (requestTypeId.equals("1") || requestTypeId.equals("2"))) {
2601                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
2602                 recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2603                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
2604                 recallList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
2605             } else if (requestTypeId != null && (requestTypeId.equals("3") || requestTypeId.equals("4"))) {
2606                 //  holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
2607                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
2608                 holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2609                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
2610                 holdList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
2611             } else if (requestTypeId != null && (requestTypeId.equals("5") || requestTypeId.equals("6"))) {
2612                 // pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
2613                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
2614                 pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2615                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
2616                 pageList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
2617             }else if (requestTypeId != null && (requestTypeId.equals("9"))) {
2618                 requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "9");
2619                 asrList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
2620             }
2621             Map<String, String> requestByBorrower = new HashMap<String, String>();
2622             requestByBorrower.put(OLEConstants.OleDeliverRequest.BORROWER_ID, borrowerId);
2623             requestsByBorrower = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestByBorrower);
2624             HashMap<String, Object> termValues = new HashMap<String, Object>();
2625             termValues.put(OLEConstants.BORROWER_TYPE, borrowerType);
2626             termValues.put(OLEConstants.ITEM_TYPE, itemType);
2627             termValues.put(OLEConstants.LOCATION, location);
2628             termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
2629             termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
2630             termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
2631             termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
2632             termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
2633             termValues.put(OLEConstants.MAX_NO_OF_RECALL_REQUEST, new Integer(recallList.size()) + 1);
2634             termValues.put(OLEConstants.MAX_NO_OF_HOLD_REQUEST, new Integer(holdList.size()) + 1);
2635             termValues.put(OLEConstants.MAX_NO_OF_PAGE_REQUEST, new Integer(pageList.size()) + 1);
2636             termValues.put(OLEConstants.MAX_NO_OF_ASR_REQUEST, new Integer(asrList.size()) + 1);
2637             // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
2638             termValues.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, requestTypeId);
2639             termValues.put(OLEConstants.REQUEST_TYPE, requestType);
2640             termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
2641             termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
2642 
2643             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
2644                 MatchBo matchBo = matchBoIterator.next();
2645                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
2646             }
2647             if (LOG.isDebugEnabled()) {
2648                 LOG.debug("termValues.toString()" + termValues.toString());
2649             }
2650             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
2651             dataCarrierService.removeData(patronId+itemId);
2652             List<String> errorMessage = (List<String>) engineResult.getAttribute(OLEConstants.ERROR_ACTION);
2653             java.sql.Date d = (java.sql.Date) engineResult.getAttribute(OLEConstants.REQ_EXPIRATION_DATE);
2654             Timestamp recallDueDate = (Timestamp) engineResult.getAttribute(OLEConstants.RECALL_DUE_DATE);
2655             String notice = (String) engineResult.getAttribute(OLEConstants.NOTICE);
2656             oleDeliverRequestBo.setNoticeType(notice);
2657 
2658             oleDeliverRequestBo.setRequestExpiryDate(d);
2659             StringBuffer failures = new StringBuffer();
2660             if (errorMessage != null && errorMessage.size() > 0) {
2661                 int i = 1;
2662                 for (String errMsg : errorMessage) {
2663                     failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
2664                 }
2665             }
2666             if (!failures.toString().isEmpty()) {
2667                 oleDeliverRequestBo.setMessage(failures.toString());
2668             }else if(failures.toString().trim().isEmpty()){
2669 
2670             if(oleLoanDocument!=null && (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2"))){
2671             Timestamp itemDueDate = null;
2672             if(ObjectUtils.isNotNull(oleLoanDocument)){
2673               itemDueDate = oleLoanDocument.getLoanDueDate();
2674             }
2675             Item oleItem = oleDeliverRequestBo.getOleItem();
2676             if(itemDueDate == null && recallDueDate!=null){
2677                // oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
2678                 oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
2679                 oleLoanDocument.setLoanDueDate(recallDueDate);
2680                 oleDeliverRequestBo.setRecallDueDate(recallDueDate);
2681                 oleItem.setDueDateTime(recallDueDate.toString());
2682                 getBusinessObjectService().save(oleLoanDocument);
2683                 OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
2684                         getLoanProcessor().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
2685                 oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
2686                 OLEDeliverNoticeHelperService oleDeliverNoticeHelperService =getOleDeliverNoticeHelperService();
2687                 oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
2688                 try{
2689                 oleDeliverNoticeHelperService.generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
2690                         oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
2691                         oleLoanDocument.getBorrowerTypeCode(),itemType, oleDeliverRequestBo.getItemStatus(),
2692                         oleLoanDocument.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
2693                         oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
2694                         oleDeliverRequestBo.getShelvingLocation(), oleDeliverRequestBo.getItemCollection(), oleDeliverRequestBo.getItemLibrary(),
2695                         oleDeliverRequestBo.getItemCampus(), oleDeliverRequestBo.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
2696                 }catch(Exception e){
2697                     LOG.info("Exception occured while updating the date in notice table");
2698                     LOG.error(e,e);
2699                 }
2700                     oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate,"MM/dd/yyyy HH:mm:ss"));
2701                 try{
2702                    updateItem(oleItem);
2703                 }catch(Exception e){
2704                     if(LOG.isInfoEnabled()){
2705                         LOG.info("Exception occured while updating the item . " +e.getMessage() );
2706                     }
2707                     LOG.error(e,e);
2708                 }
2709             }
2710             if (recallDueDate != null && itemDueDate!=null ) {
2711                 if(itemDueDate.compareTo(recallDueDate) > 0){
2712                 oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(itemDueDate.getTime())));
2713                 oleDeliverRequestBo.setNewDueDate(new java.sql.Date(recallDueDate.getTime()));
2714                 oleLoanDocument.setLoanDueDate(recallDueDate);
2715                 oleDeliverRequestBo.setRecallDueDate(recallDueDate);
2716                 getBusinessObjectService().save(oleLoanDocument);
2717                     OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ?
2718                             getLoanProcessor().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
2719                     oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
2720                     OLEDeliverNoticeHelperService oleDeliverNoticeHelperService =getOleDeliverNoticeHelperService();
2721                     oleDeliverNoticeHelperService.deleteDeliverNotices(oleLoanDocument.getLoanId());
2722                     try{
2723                     oleDeliverNoticeHelperService.generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
2724                             oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
2725                             oleLoanDocument.getBorrowerTypeCode(),itemType, oleDeliverRequestBo.getItemStatus(),
2726                             oleLoanDocument.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
2727                             oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
2728                             oleDeliverRequestBo.getShelvingLocation(), oleDeliverRequestBo.getItemCollection(), oleDeliverRequestBo.getItemLibrary(),
2729                             oleDeliverRequestBo.getItemCampus(), oleDeliverRequestBo.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
2730                     }catch(Exception e){
2731                         LOG.info("Exception occured while updating the date in notice table");
2732                         LOG.error(e,e);
2733                     }
2734                         oleItem.setDueDateTime(getLoanProcessor().convertDateToString(recallDueDate,"MM/dd/yyyy HH:mm:ss"));
2735                     try{
2736                         updateItem(oleItem);
2737                     }catch(Exception e){
2738                         if(LOG.isInfoEnabled()){
2739                             LOG.info("Exception occured while updating the item . " +e.getMessage() );
2740                         }
2741                         LOG.error(e,e);
2742                     }
2743                 }else{
2744                     oleDeliverRequestBo.setNewDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
2745                     oleDeliverRequestBo.setOriginalDueDate((new java.sql.Date(oleLoanDocument.getLoanDueDate().getTime())));
2746                 }
2747             }
2748           }
2749             }
2750             dataCarrierService.addData(OLEConstants.ERROR_ACTION, null);
2751         }
2752         return engineResult;
2753     }
2754 
2755     /**
2756      * This method returns SelectionContext using contextName.
2757      *
2758      * @param contextName
2759      * @return Map
2760      */
2761     protected Map<String, String> getSelectionContext(String contextName) {
2762         Map<String, String> selector = new HashMap<String, String>();
2763         selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
2764         selector.put(NAME_SELECTOR, contextName);
2765         return selector;
2766     }
2767 
2768     /**
2769      * This method returns AgendaContext using agendaName..
2770      *
2771      * @param agendaName
2772      * @return Map
2773      */
2774     protected Map<String, String> getAgendaContext(String agendaName) {
2775         Map<String, String> selector = new HashMap<String, String>();
2776         selector.put(NAME_SELECTOR, agendaName);
2777         return selector;
2778     }
2779 
2780     public OleCirculationDesk getOleCirculationDesk(String circulationDeskId) {
2781         Map<String, String> circulationDeskMap = new HashMap<String, String>();
2782         circulationDeskMap.put(OLEConstants.CIRCULATION_DESK_ID, circulationDeskId);
2783         List<OleCirculationDesk> oleCirculationDeskList = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, circulationDeskMap);
2784         if (oleCirculationDeskList != null && oleCirculationDeskList.size() > 0) {
2785             return oleCirculationDeskList.get(0);
2786         } else
2787             return null;
2788     }
2789 
2790     private RoleService getRoleService() {
2791         RoleService service = KimApiServiceLocator.getRoleService();
2792         return service;
2793     }
2794     public boolean checkForOverdueNotice(Date expDate){
2795         Date curDat = new Date();
2796         if(expDate!=null && curDat.compareTo(expDate)<=0){
2797             return  false;
2798         }
2799         return true;
2800     }
2801 
2802 
2803     public Map<String,String> getLocationMap(String itemLocation){
2804         Map<String,String> locationMap = new HashMap<String,String>();
2805         String[] locationArray =  itemLocation.split("['/']");
2806         List<String> locationList = Arrays.asList(locationArray);
2807         for(String value : locationList){
2808             Map<String,String> requestMap =  new HashMap<>();
2809             requestMap.put(OLEConstants.LOCATION_CODE,value);
2810             List<OleLocation> oleLocations = (List<OleLocation>)getBusinessObjectService().findMatching(OleLocation.class,requestMap);
2811             if(oleLocations!=null && oleLocations.size()>0){
2812                 String locationLevelId = oleLocations.get(0).getLevelId();
2813                 requestMap.clear();
2814                 requestMap.put(OLEConstants.LEVEL_ID,locationLevelId);
2815                 List<OleLocationLevel> oleLocationLevels = (List<OleLocationLevel>)getBusinessObjectService().findMatching(OleLocationLevel.class,requestMap);
2816                 if(oleLocationLevels!=null && oleLocationLevels.size()>0){
2817                     OleLocationLevel oleLocationLevel = new OleLocationLevel();
2818                     oleLocationLevel = oleLocationLevels.get(0);
2819                     if(oleLocationLevel.getLevelCode().equals(OLEConstants.OLEBatchProcess.LOCATION_LEVEL_CAMPUS)){
2820                         locationMap.put(OLEConstants.ITEM_CAMPUS, value);
2821                     }else if(oleLocationLevel.getLevelCode().equals(OLEConstants.OLEBatchProcess.LOCATION_LEVEL_INSTITUTION)){
2822                         locationMap.put(OLEConstants.ITEM_INSTITUTION,value);
2823                     }else if(oleLocationLevel.getLevelCode().equals(OLEConstants.OLEBatchProcess.LOCATION_LEVEL_COLLECTION)){
2824                         locationMap.put(OLEConstants.ITEM_COLLECTION,value);
2825                     }else if(oleLocationLevel.getLevelCode().equals(OLEConstants.OLEBatchProcess.LOCATION_LEVEL_LIBRARY)){
2826                         locationMap.put(OLEConstants.ITEM_LIBRARY,value);
2827                     }else if(oleLocationLevel.getLevelCode().equals(OLEConstants.OLEBatchProcess.LOCATION_LEVEL_SHELVING)){
2828                         locationMap.put(OLEConstants.ITEM_SHELVING,value);
2829                     }
2830                 }
2831             }
2832         }
2833         return locationMap;
2834     }
2835 
2836 
2837 
2838     public  org.kuali.ole.docstore.common.document.Item retrieveItemWithBibAndHoldingData(String itemUUID){
2839         org.kuali.ole.docstore.common.document.Item item = null;
2840         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
2841         HoldingOlemlRecordProcessor holdingsOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
2842         try{
2843             //retrieve the item information from docstore
2844             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
2845             //retrieve item content
2846             Item item1 = itemOlemlRecordProcessor.fromXML(item.getContent());
2847             item = populateInfoFromInstanceItemToDocItem(item1,item);
2848             OleHoldings oleHoldings = holdingsOlemlRecordProcessor.fromXML(item.getHolding().getContent());
2849             Holdings holdings = populateInfoFromInstanceHoldingToDocHoldings(oleHoldings,item.getHolding());
2850             item.setHolding(holdings);
2851         }catch (Exception e){
2852             LOG.error(e);
2853         }
2854         return item;
2855     }
2856 
2857 
2858 
2859     public org.kuali.ole.docstore.common.document.Item populateInfoFromInstanceItemToDocItem(Item instanceItem,org.kuali.ole.docstore.common.document.Item  documentItem){
2860 
2861         documentItem.setBarcode(instanceItem.getAccessInformation().getBarcode());
2862         documentItem.setAnalytic(Boolean.valueOf(instanceItem.getAnalytic()));
2863         if(instanceItem.getCallNumber()!=null){
2864             documentItem.setCallNumber(instanceItem.getCallNumber().getNumber());
2865             documentItem.setCallNumberType(instanceItem.getCallNumber().getType());
2866             documentItem.setCallNumberPrefix(instanceItem.getCallNumber().getPrefix());
2867         }
2868         documentItem.setChronology(instanceItem.getChronology());
2869         documentItem.setCopyNumber(instanceItem.getCopyNumber());
2870         if(instanceItem.getItemStatus()!=null){
2871             documentItem.setItemStatus(instanceItem.getItemStatus().getCodeValue());
2872         }
2873         if(instanceItem.getItemType()!=null){
2874             documentItem.setItemType(instanceItem.getItemType().getCodeValue());
2875         }
2876         documentItem.setEnumeration(instanceItem.getEnumeration());
2877         documentItem.setVolumeNumber(instanceItem.getVolumeNumber());
2878 
2879         return documentItem;
2880     }
2881 
2882     public org.kuali.ole.docstore.common.document.Holdings populateInfoFromInstanceHoldingToDocHoldings(OleHoldings oleHoldings ,Holdings holdings) {
2883         if(oleHoldings.getCallNumber()!=null) {
2884             holdings.setCallNumber(oleHoldings.getCallNumber().getNumber());
2885             holdings.setCallNumberPrefix(oleHoldings.getCallNumber().getPrefix());
2886             holdings.setCallNumberType(oleHoldings.getCallNumber().getType());
2887         }
2888         holdings.setCopyNumber(oleHoldings.getCopyNumber());
2889         holdings.setHoldingsType(oleHoldings.getHoldingsType());
2890       //  holdings.setLocationName(getLocation(oleHoldings.getLocation()));
2891         return holdings;
2892     }
2893 
2894 
2895 
2896     public Map retrieveBIbItemHoldingData(String itemUUID){
2897         Map<String,Object> bibMap  = new HashMap<String,Object>();
2898         org.kuali.ole.docstore.common.document.Item item = null;
2899         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
2900         HoldingOlemlRecordProcessor holdingsOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
2901         try{
2902             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
2903             bibMap.put(OLEConstants.DOCUMENT_ITEM,item);
2904             bibMap.put(OLEConstants.BIB,item.getHolding().getBib());
2905             Item item1 = itemOlemlRecordProcessor.fromXML(item.getContent());
2906             bibMap.put(OLEConstants.ITEM,item1);
2907             OleHoldings oleHoldings = holdingsOlemlRecordProcessor.fromXML(item.getHolding().getContent());
2908             bibMap.put(OLEConstants.HOLDING,oleHoldings);
2909         }catch (Exception e){
2910             LOG.error(e);
2911         }
2912         return bibMap;
2913 
2914     }
2915 
2916     private void getNoticeList(List<OleLoanDocument> oleLoanDocuments, OlePatronDocument olePatronDocument, boolean overdue) {
2917         Long b1 = System.currentTimeMillis();
2918         List<OleLoanDocument> oleOverDueNoticeBoList = new ArrayList<>();
2919         List<OleLoanDocument> oleCourtesyNoticeList = new ArrayList<>();
2920         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
2921         StringBuffer mailContent = new StringBuffer();
2922         Document document=null;
2923         OutputStream outputStream = null;
2924         try {
2925             String overdueNoticeType = getLoanProcessor().getParameter(OLEParameterConstants.OVERDUE_NOTICE_TYPE);
2926             String courtesyNoticeType = getLoanProcessor().getParameter(OLEParameterConstants.COURTESY_NOTICE_TYPE);
2927             DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
2928 
2929      //          HashMap<String, org.kuali.ole.docstore.common.document.Item> itemMap = getDocstoreClientLocator().getDocstoreClient().retrieveItemMap(itemIds);
2930 
2931             mailContent.append(oleDeliverBatchService.getHeaderAndPatronContent(olePatronDocument, overdue));
2932             oleDeliverBatchService.getHeaderAndPatronPDFContent(olePatronDocument,overdue);
2933             document=oleDeliverBatchService.getOverdueDocument();
2934             outputStream=oleDeliverBatchService.getOverdueOutPutStream();
2935             for (OleLoanDocument oleLoanDocument : oleLoanDocuments) {
2936 /*                org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2937                 item = itemMap.get(oleLoanDocument.getItemUuid());
2938                 oleLoanDocument.setInstanceUuid(item.getHolding().getId());
2939                 String itemXml = item.getContent();
2940                 oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
2941                 oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
2942                 oleLoanDocument.setItemVolumeNumber(item.getVolumeNumber());*/
2943 /*                Item oleItem = getLoanProcessor().getItemPojo(itemXml);
2944                 if (oleItem != null && oleItem.getCallNumber() != null) {
2945                     oleLoanDocument.setItemCallNumber(oleItem.getCallNumber().getNumber());
2946                 }
2947                 oleLoanDocument.setOleItem(oleItem);*/
2948                 oleLoanDocument.setOlePatron(olePatronDocument);
2949                 Date dueDate = oleLoanDocument.getLoanDueDate();
2950                 Date currentDate = new Date();
2951                 Integer dueDateDiffInterval = determineDifferenceInDays(dueDate, currentDate);
2952                 DateFormat formatter = new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE_NOTICE);
2953                 if (LOG.isInfoEnabled()) {
2954                     LOG.info("oleLoanDocument---->ItemID--"+oleLoanDocument.getItemId()+": Patron Barcode--"+oleLoanDocument.getPatronBarcode());
2955                     LOG.info("oleItem.getItemStatusEffectiveDate()" + oleLoanDocument.getItemStatusEffectiveDate());
2956                 }
2957                 Date itemStatusEffectiveDate = (Date) formatter.parse(oleLoanDocument.getItemStatusEffectiveDate());
2958                 Integer numberOfDaysOnHold = determineDifferenceInDays(itemStatusEffectiveDate, currentDate);
2959                 Integer dueDateSumInterval = determineDifferenceInDays(currentDate, dueDate);
2960                 Integer overdueNoticeInterval = Integer.parseInt(getIntervalForOverdueNotice());
2961                 Integer intervalWithNoticeCount = 0;
2962                 Integer loanNoOfOverdueNoticeSent = oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent()) : 0;
2963                 if (oleLoanDocument.getNumberOfOverdueNoticesSent() != null) {
2964                     intervalWithNoticeCount = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent()) + 1;
2965                 } else {
2966                     intervalWithNoticeCount = intervalWithNoticeCount + 1;
2967                 }
2968                 dueDateSumInterval = dueDateSumInterval / intervalWithNoticeCount;
2969                 if (dueDateSumInterval < 0) {
2970                     dueDateSumInterval = 0;
2971                 }
2972                 if (dueDateDiffInterval < 0) {
2973                     dueDateDiffInterval = 0;
2974                 }
2975                 Integer maxNumberOfDaysOnHold = 0;
2976                 OleCirculationDesk oleCirculationDesk = null;
2977                 if (oleLoanDocument.getCirculationLocationId() != null) {
2978                     oleCirculationDesk = getLoanProcessor().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2979                     String maxNumOfDays = oleCirculationDesk.getOnHoldDays() != null ? oleCirculationDesk.getOnHoldDays() : getLoanProcessor().getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
2980                     maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
2981                 }
2982                 if(oleLoanDocument.getItemTypeName()!=null){
2983                     oleLoanDocument.setItemType(getItemTypeCodeByName(oleLoanDocument.getItemTypeName()));
2984                 }
2985 
2986 /*                if (oleItem.getTemporaryItemType() != null && oleItem.getTemporaryItemType().getCodeValue() != "") {
2987                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getTemporaryItemType().getCodeValue());
2988                     oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2989                 } else if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
2990                     OleInstanceItemType oleInstanceItemType = getLoanProcessor().getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
2991                     oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2992                 }*/
2993                 OleDeliverRequestBo oleDeliverRequestBo = getLoanProcessor().getPrioritizedRequest(oleLoanDocument.getItemUuid());
2994      /*           getLoanProcessor().getLocation(oleItem, oleLoanDocument);*/
2995 
2996 /*                String agendaName = OLEConstants.NOTICE_AGENDA_NM;
2997                 String patronId = oleLoanDocument.getPatronId()!=null ?  oleLoanDocument.getPatronId() : "";
2998                 String itemId = oleLoanDocument.getItemId()!=null ?  oleLoanDocument.getItemId() : "";
2999                 dataCarrierService.removeData(patronId+itemId);
3000                 HashMap<String, Object> termValues = new HashMap<String, Object>();
3001                 Date expirationDate = olePatronDocument != null ? olePatronDocument.getExpirationDate() : null;
3002                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
3003                 termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemType());
3004                 termValues.put(OLEConstants.OVERLAY_ITEM_LOCATION, oleLoanDocument.getItemLocation());
3005                 termValues.put(OLEConstants.DUE_DATE_DIFF_INTERVAL, dueDateDiffInterval);
3006                 if (oleLoanDocument.getItemStatus() != null)
3007                     termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemStatus());
3008                 termValues.put(OLEConstants.NO_OF_DAYS_ON_HOLD, numberOfDaysOnHold);
3009                 termValues.put(OLEConstants.MAX_NO_OF_DAYS_ONHOLD, maxNumberOfDaysOnHold);
3010                 termValues.put(OLEConstants.OleDeliverRequest.CLAIM_RETURNED, oleLoanDocument.isClaimsReturnedIndicator() ? "true" : "false");
3011                 termValues.put(OLEConstants.OleDeliverRequest.REPLACEMENT_FEE_PATRON_BILL, oleLoanDocument.getRepaymentFeePatronBillId() != null ? "true" : "false");
3012                 termValues.put(OLEConstants.OleDeliverRequest.NUBER_OF_OVER_DUE_SENT, loanNoOfOverdueNoticeSent);
3013                 termValues.put(OLEConstants.OleDeliverRequest.DUE_DATE_SUM_INTERVAL, dueDateSumInterval);
3014                 termValues.put(OLEConstants.OleDeliverRequest.CONFIGURABLE_INTERVAL, Integer.parseInt(courtesyInterval));
3015                 termValues.put(OLEConstants.OleDeliverRequest.INTERVAL_WITH_NOTICE_COUNT, intervalWithNoticeCount);
3016                 termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
3017                 termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
3018                 termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
3019                 termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
3020                 termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
3021                 termValues.put(OLEConstants.REQUEST_TYPE, oleDeliverRequestBo != null ? oleDeliverRequestBo.getRequestTypeCode() : null);
3022                 termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
3023                 termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
3024                 termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
3025                 if (LOG.isDebugEnabled()) {
3026                     LOG.debug("termValues.toString()" + termValues.toString());
3027                 }
3028                 EngineResults engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
3029                 dataCarrierService.removeData(patronId+itemId);
3030                 String notice = (String) engineResults.getAttribute(OLEConstants.NOTICE);
3031                 String itemStatus = (String) engineResults.getAttribute(OLEConstants.ITEM_STATUS);
3032                 BigDecimal replacementBill = (BigDecimal) engineResults.getAttribute(OLEConstants.REPLACEMENT_BILL);
3033                 List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
3034                 if (errorMessage != null && LOG.isDebugEnabled()) {
3035                     LOG.debug("errorMessage" + errorMessage.toString());
3036                 }
3037                 if (LOG.isDebugEnabled()) {
3038                     LOG.debug("notice" + notice);
3039                 }
3040                 agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
3041                 termValues = new HashMap<String, Object>();
3042                 String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
3043                 String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
3044                 termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
3045                 termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
3046                 termValues.put(OLEConstants.NOTICE, notice);
3047                 engineResults = getLoanProcessor().getEngineResults(agendaName, termValues);
3048                 String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
3049                 errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
3050                 if (errorMessage != null && LOG.isDebugEnabled()) {
3051                     LOG.debug("errorMessage" + errorMessage);
3052                 }
3053                 if (LOG.isDebugEnabled()) {
3054                     LOG.debug("noticeType" + noticeType);
3055                 }*/
3056                 String noticeType = oleLoanDocument.getNoticeType();
3057                 if (oleLoanDocument.getReplacementBill()!=null  && oleLoanDocument.getReplacementBill().intValue() > 0 && noticeType.equalsIgnoreCase(OLEConstants.NOTICE_LOST)) {
3058                     int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
3059                     noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
3060                     oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
3061                     oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
3062                     String billNumber = getLoanProcessor().generatePatronBillPayment(oleLoanDocument, OLEConstants.REPLACEMENT_FEE, oleLoanDocument.getReplacementBill());
3063                     oleLoanDocument.setRepaymentFeePatronBillId(billNumber);
3064                     getBusinessObjectService().save(oleLoanDocument);
3065                     List<String> itemUUIDs = new ArrayList<>();
3066                     itemUUIDs.add(oleLoanDocument.getItemUuid());
3067                     HashMap<String, org.kuali.ole.docstore.common.document.Item> itemMaps = getDocstoreClientLocator().getDocstoreClient().retrieveItemMap(itemUUIDs);
3068                    org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
3069                     item = itemMaps.get(oleLoanDocument.getItemUuid());
3070                     String itemXml = item.getContent();
3071                      Item oleItem = getLoanProcessor().getItemPojo(itemXml);
3072                      getLoanProcessor().updateItemStatus(oleItem, OLEConstants.ITEM_STATUS_LOST);
3073                     getBusinessObjectService().delete(oleLoanDocument.getOleDeliverNotice());
3074                     saveOLEDeliverNoticeHistory(oleLoanDocument);
3075                 }
3076 
3077                     if (noticeType.equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
3078                         oleOverDueNoticeBoList.add(oleLoanDocument);
3079                         mailContent.append(oleDeliverBatchService.getOverdueNoticeHTMLContent(oleLoanDocument));
3080                         noticeType = noticeType == null ? overdueNoticeType : noticeType;
3081                         oleDeliverBatchService.getOverdueNoticePDFContent(oleLoanDocument,overdue,document);
3082                         int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
3083                         noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
3084                         if (LOG.isDebugEnabled()) {
3085                             LOG.debug("Updated Loan Record : " + oleLoanDocument);
3086                         }
3087                         oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
3088                         oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
3089                         getBusinessObjectService().save(oleLoanDocument);
3090                         getBusinessObjectService().delete(oleLoanDocument.getOleDeliverNotice());
3091                         saveOLEDeliverNoticeHistory(oleLoanDocument);
3092                     } else if (noticeType.equalsIgnoreCase(OLEConstants.NOTICE_COURTESY) && olePatronDocument.isCourtesyNotice() && !oleLoanDocument.isCourtesyNoticeFlag()) {
3093                         oleCourtesyNoticeList.add(oleLoanDocument);
3094                         mailContent.append(oleDeliverBatchService.getOverdueNoticeHTMLContent(oleLoanDocument));
3095                         oleDeliverBatchService.getOverdueNoticePDFContent(oleLoanDocument,overdue,document);
3096                         noticeType = noticeType == null ? courtesyNoticeType : noticeType;
3097                         oleLoanDocument.setCourtesyNoticeFlag(!overdue);
3098                         getBusinessObjectService().save(oleLoanDocument);
3099                         getBusinessObjectService().delete(oleLoanDocument.getOleDeliverNotice());
3100                         saveOLEDeliverNoticeHistory(oleLoanDocument);
3101                     }
3102 
3103                 olePatronDocument = oleLoanDocument.getOlePatron();
3104                 if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
3105                     //TODO : sms in progress.
3106                 }
3107             }
3108 
3109         } catch (Exception e) {
3110             LOG.error("Exception in generateNotices()" + e.getMessage(), e);
3111         }
3112         Long b2 = System.currentTimeMillis();
3113         Long b3 = b2 - b1;
3114         LOG.info("Time taken to send the notices " + b3);
3115         boolean isFileNeedToDelete=true;
3116         if (overdue) {
3117             if (oleOverDueNoticeBoList != null && oleOverDueNoticeBoList.size() > 0) {
3118                 sendMailsToPatron(olePatronDocument, mailContent.toString());
3119                 try {
3120                     if (document != null && outputStream!=null) {
3121                         oleDeliverBatchService.getPdfFooter(document,outputStream);
3122                         isFileNeedToDelete=false;
3123                     }
3124                 } catch (Exception e){
3125                     LOG.error("PDF overdue notice error");
3126                 }
3127 
3128             }
3129         } else {
3130             if (oleCourtesyNoticeList != null && oleCourtesyNoticeList.size() > 0) {
3131                 sendMailsToPatron(olePatronDocument, mailContent.toString());
3132                 try {
3133                     if (document != null && outputStream!=null) {
3134                         oleDeliverBatchService.getPdfFooter(document,outputStream);
3135                         isFileNeedToDelete=false;
3136                     }
3137                 } catch (Exception e){
3138                     LOG.error("PDF overdue notice error");
3139                 }
3140             }
3141         }
3142         if(isFileNeedToDelete){
3143             oleDeliverBatchService.cleanZeroByteFiles();
3144         }
3145 
3146     }
3147 
3148     public void sendMailsToPatron(OlePatronDocument olePatronDocument, String noticeContent) {
3149 
3150         Long b1 = System.currentTimeMillis();
3151         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
3152         String emailAddress = "";
3153         try {
3154             EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
3155             emailAddress = getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "";
3156         } catch (Exception e) {
3157             LOG.error("Unable to get Patron Email Address --sendMailsToPatron--" + e.getMessage(), e);
3158         }
3159         try {
3160             String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
3161             if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
3162                 fromAddress = OLEConstants.KUALI_MAIL;
3163             }
3164             //   oleDeliverBatchService.generatePdfForOverdueCourtesyNotice(oleLoanDocuments,true,olePatronDocument);
3165             if (emailAddress != null && !emailAddress.isEmpty()) {
3166                 noticeContent = noticeContent.replace('[', ' ');
3167                 noticeContent = noticeContent.replace(']', ' ');
3168                 if (!noticeContent.trim().equals("")) {
3169                     OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
3170                     oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(emailAddress), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(noticeContent), true);
3171                 }
3172             } else {
3173                 LOG.error("Patron Email Address --sendMailsToPatron-- is Empty or Null");
3174             }
3175         } catch (Exception e) {
3176             LOG.error("Exception in generateNotices()" + e.getMessage(), e);
3177         }
3178         Long b2 = System.currentTimeMillis();
3179         Long total = b2 - b1;
3180         LOG.info("The time taken sending mail :" + total);
3181     }
3182 
3183     /**
3184      * This method is used to set the item information in the loan documents
3185      * @param oleLoanDocuments
3186      * @return
3187      */
3188     public List<OleLoanDocument> getLoanDocumentWithItemInfo(List<OleLoanDocument> oleLoanDocuments)throws Exception{
3189        Long startTime = System.currentTimeMillis();
3190         List<OleLoanDocument> loanDocumentsWithItemInfo = new ArrayList<OleLoanDocument>();
3191         if(oleLoanDocuments!=null && oleLoanDocuments.size()>0){
3192             Map<String,OleLoanDocument> loanDocumentMap = new HashMap<String,OleLoanDocument>();
3193             SearchParams searchParams = new SearchParams();
3194             List<SearchCondition> searchConditions = new ArrayList<>();
3195             SearchResponse searchResponse = new SearchResponse();
3196             String numberOfRecords = getLoanProcessor().getParameter(OLEConstants.NUMBER_OF_ITEM_INFO);
3197             List<List<OleLoanDocument>> slicedList = (List<List<OleLoanDocument>>)splitListToSubList(oleLoanDocuments,Integer.valueOf(numberOfRecords).intValue());
3198             for(List<OleLoanDocument> oleLoanDocumentList : slicedList  ){
3199                 try{
3200                 searchConditions = new ArrayList<>();
3201                 searchResponse = new SearchResponse();
3202                 searchParams = new SearchParams();
3203                 for(OleLoanDocument oleLoanDocument : oleLoanDocumentList){
3204                     loanDocumentMap.put(oleLoanDocument.getItemUuid(),oleLoanDocument);
3205                     searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField("item", "id", oleLoanDocument.getItemUuid()), "OR"));
3206                 }
3207                 searchParams.setPageSize(Integer.parseInt(OLEConstants.MAX_PAGE_SIZE_FOR_LOAN));
3208                 buildSearchParams(searchParams);
3209                 searchParams.getSearchConditions().addAll(searchConditions);
3210                 try{
3211                     searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
3212                 }catch(Exception e){
3213                     LOG.error(e,e);
3214                     throw new  Exception("Exception occured while fetching data from solr");
3215                 }try{
3216                     List<OleLoanDocument> processedLoanDocuments = buildSearchResultsFields(searchResponse,loanDocumentMap);
3217                     loanDocumentsWithItemInfo.addAll(processedLoanDocuments);
3218                 }catch(Exception e){
3219                     LOG.error(e,e);
3220                         throw new Exception("Exception occured while setting the item information to loan documents");
3221                 }
3222             }catch(Exception e){
3223                 LOG.info("Exception occured while setting the item information to the loan documents");
3224                 LOG.error(e,e);
3225                 }
3226             }
3227         }
3228         Long endTime =System.currentTimeMillis();
3229         Long timeDifference = endTime-startTime;
3230         LOG.info("Time Taken to set the item information in the loan records in milliseconds : " + timeDifference);
3231         return loanDocumentsWithItemInfo;
3232     }
3233 
3234     /**
3235      * This method is used to set the values from the docstore response
3236      * @param searchResponse
3237      * @param loanDocumentMap
3238      * @return
3239      * @throws Exception
3240      */
3241     public List<OleLoanDocument> buildSearchResultsFields(SearchResponse searchResponse,Map<String,OleLoanDocument> loanDocumentMap)throws Exception{
3242         int count = 0;
3243         Map<String,String> itemTypeNameMap = new HashMap<String,String>();
3244         List<OleInstanceItemType> instanceItemTypeList = (List<OleInstanceItemType>)getBusinessObjectService().findAll(OleInstanceItemType.class);
3245         if(instanceItemTypeList != null && instanceItemTypeList.size()>0){
3246             for(OleInstanceItemType oleInstanceItemType : instanceItemTypeList){
3247                 itemTypeNameMap.put(oleInstanceItemType.getInstanceItemTypeName(),oleInstanceItemType.getInstanceItemTypeCode());
3248             }
3249         }
3250         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
3251         List<OleLoanDocument> oleLoanDocuments = new ArrayList<>();
3252         if(searchResponse!=null){
3253             for (SearchResult searchResult : searchResponse.getSearchResults()) {
3254                 try{
3255                 OleLoanDocument oleLoanDocument = null;
3256                 boolean found = false;
3257                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
3258                     if(searchResultField.getFieldValue()!=null){
3259                         if(searchResultField.getFieldName().equalsIgnoreCase("id")) {
3260                            found = loanDocumentMap.containsKey(searchResultField.getFieldValue());
3261                         }
3262                         if(found){
3263                          if(searchResultField.getFieldName().equalsIgnoreCase("id")) {
3264                             oleLoanDocument = loanDocumentMap.get(searchResultField.getFieldValue());
3265                             oleLoanDocument.setItemUuid(searchResultField.getFieldValue());
3266                         } else if (searchResultField.getFieldName().equalsIgnoreCase("ItemBarcode_display")) {
3267                             oleLoanDocument.setItemId(searchResultField.getFieldValue());
3268                         }
3269                         else if (searchResultField.getFieldName().equalsIgnoreCase("bibIdentifier")) {
3270                             oleLoanDocument.setBibUuid(searchResultField.getFieldValue());
3271                         }
3272                         else if (searchResultField.getFieldName().equalsIgnoreCase("Title_display")) {
3273                             oleLoanDocument.setTitle(searchResultField.getFieldValue());
3274                         }
3275                         else if (searchResultField.getFieldName().equalsIgnoreCase("Author_display")) {
3276                             oleLoanDocument.setAuthor(searchResultField.getFieldValue());
3277                         }
3278                         else if (searchResultField.getFieldName().equalsIgnoreCase("holdingsIdentifier")) {
3279                             oleLoanDocument.setInstanceUuid(searchResultField.getFieldValue());
3280                         }
3281                         else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedNote")) {
3282                             oleLoanDocument.setClaimsReturnNote(searchResultField.getFieldValue());
3283                             //  count++;
3284                         }
3285 
3286                         else if (searchResultField.getFieldName().equalsIgnoreCase("ClaimsReturnedFlag_display") && searchResultField.getFieldValue().equalsIgnoreCase("true")) {
3287                             oleLoanDocument.setClaimsReturnedIndicator(true);
3288                             count++;
3289                         }
3290                         else  if (searchResultField.getFieldName().equalsIgnoreCase("Location_display")) {
3291                             getLoanProcessor().getLocationBySolr(searchResultField, oleLoanDocument);
3292                              oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
3293                              Map<String, String> locationMap = getLocationMap(oleLoanDocument.getItemFullLocation());
3294                              oleLoanDocument.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
3295                              oleLoanDocument.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
3296                              oleLoanDocument.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
3297                              oleLoanDocument.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
3298                              oleLoanDocument.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
3299 
3300                         }
3301                         else  if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsLocation_search") &&
3302                                 (oleLoanDocument.getItemLocation()==null || oleLoanDocument.getItemLocation().isEmpty())) {
3303                             getLoanProcessor().getLocationBySolr(searchResultField,oleLoanDocument);
3304                              oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
3305                              Map<String, String> locationMap = getLocationMap(oleLoanDocument.getItemFullLocation());
3306                              oleLoanDocument.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
3307                              oleLoanDocument.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
3308                              oleLoanDocument.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
3309                              oleLoanDocument.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
3310                              oleLoanDocument.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
3311 
3312                         }
3313                         else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedFlagCreateDate")) {
3314                             String[] formatStrings = new String[]{"MM/dd/yyyy hh:mm:ss","MM/dd/yyyy","yyyy-MM-dd hh:mm:ss"};
3315                             Date date =getLoanProcessor().tryParse(formatStrings,searchResultField.getFieldValue());
3316                             oleLoanDocument.setClaimsReturnedDate(new Timestamp(date.getTime()));
3317 
3318                         }
3319                         else if (searchResultField.getFieldName().equalsIgnoreCase("CallNumber_display")) {
3320                             oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
3321                         }
3322                         else if (searchResultField.getFieldName().equalsIgnoreCase("TemporaryItemTypeFullValue_search")) {
3323                             oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
3324                             oleLoanDocument.setItemType(itemTypeNameMap.get(oleLoanDocument.getItemTypeName()));
3325                         }
3326                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemTypeFullValue_display") &&
3327                                 (oleLoanDocument.getItemTypeName()==null || oleLoanDocument.getItemTypeName().isEmpty())) {
3328                             oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
3329                              oleLoanDocument.setItemType(itemTypeNameMap.get(oleLoanDocument.getItemTypeName()));
3330                          }
3331                         else if (searchResultField.getFieldName().equalsIgnoreCase("Enumeration_display")) {
3332                             oleLoanDocument.setEnumeration(searchResultField.getFieldValue());
3333                         }
3334                         else if (searchResultField.getFieldName().equalsIgnoreCase("Chronology_display")) {
3335                             oleLoanDocument.setChronology(searchResultField.getFieldValue());
3336                         }
3337                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemStatus_display")) {
3338                             oleLoanDocument.setItemStatus(searchResultField.getFieldValue());
3339                         }
3340                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemDamagedStatus_display")) {
3341                             oleLoanDocument.setItemDamagedStatus(searchResultField.getFieldValue().equalsIgnoreCase("true"));
3342                         }
3343                         else if (searchResultField.getFieldName().equalsIgnoreCase("DamagedItemNote_search")) {
3344                             oleLoanDocument.setItemDamagedNote(searchResultField.getFieldValue());
3345                         }
3346                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlagNote_search")) {
3347                             oleLoanDocument.setMissingPieceNote(searchResultField.getFieldValue());
3348                         }
3349                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlag_display")) {
3350                             oleLoanDocument.setMissingPieceFlag(searchResultField.getFieldValue().equalsIgnoreCase("true"));
3351                         }
3352                         else if (searchResultField.getFieldName().equalsIgnoreCase("CopyNumber_search")) {
3353                             oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
3354                         }
3355                         else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCopyNumber_search") &&
3356                                 (oleLoanDocument.getItemCopyNumber()==null || oleLoanDocument.getItemCopyNumber().isEmpty())) {
3357                             oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
3358                         }
3359                         else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCallNumber_search") &&
3360                                 (oleLoanDocument.getItemCallNumber()==null || oleLoanDocument.getItemCallNumber().isEmpty())) {
3361                             oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
3362                         }
3363                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceCount_search")) {
3364                             oleLoanDocument.setMissingPiecesCount(searchResultField.getFieldValue());
3365                         }
3366                         else if (searchResultField.getFieldName().equalsIgnoreCase("NumberOfPieces_search")) {
3367                             oleLoanDocument.setItemNumberOfPieces(Integer.parseInt(searchResultField.getFieldValue()));
3368                             oleLoanDocument.setBackUpNoOfPieces(searchResultField.getFieldValue());
3369                         }
3370                         else if(searchResultField.getFieldName().equalsIgnoreCase("ClaimsReturnedFlag_search")) {
3371                              oleLoanDocument.setClaimsReturnedIndicator(Boolean.valueOf(searchResultField.getFieldValue()));
3372                          }else if(searchResultField.getFieldName().equalsIgnoreCase("itemStatusEffectiveDate")) {
3373                              oleLoanDocument.setItemStatusEffectiveDate(searchResultField.getFieldValue());
3374                             // LOG.info("Item status Effective date from solr : " + searchResultField.getFieldValue() );
3375                          }
3376                     }
3377                   }
3378 
3379                 }
3380                 found =false;
3381                 if(oleLoanDocument.getOlePatron()!=null){
3382                     oleLoanDocument.getOlePatron().setNumberOfClaimsReturned(count);
3383                 }
3384                 oleLoanDocuments.add(oleLoanDocument);
3385             }catch(Exception e){
3386                     LOG.info("Exception occured while setting the item info for the loan ");
3387                 }
3388             }
3389         }
3390         return oleLoanDocuments;
3391     }
3392 
3393 
3394     public String getItemTypeCodeByName(String itemTypeName){
3395        String itemTypeCode = "";
3396         List<OleInstanceItemType> instanceItemTypeList = null;
3397         Map<String,String> instanceItemTypeMap = new HashMap<String,String>();
3398         instanceItemTypeMap.put("instanceItemTypeName",itemTypeName);
3399         instanceItemTypeList = (List<OleInstanceItemType>)getBusinessObjectService().findMatching(OleInstanceItemType.class,instanceItemTypeMap);
3400         if(instanceItemTypeList != null && instanceItemTypeList.size()>0){
3401            itemTypeCode = instanceItemTypeList.get(0).getInstanceItemTypeCode();
3402         }
3403         return itemTypeCode;
3404     }
3405 
3406     /**
3407      * This method is to update the item
3408      * @param oleItem
3409      * @throws Exception
3410      */
3411     public void updateItem(Item oleItem)throws Exception{
3412         String itemUuid = oleItem.getItemIdentifier();
3413         String itemXmlContent = getItemOlemlRecordProcessor().toXML(oleItem);
3414          try{
3415         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
3416         item.setId(itemUuid);
3417         item.setContent(itemXmlContent);
3418         item.setCategory(OLEConstants.WORK_CATEGORY);
3419         item.setType(DocType.ITEM.getCode());
3420         item.setFormat(OLEConstants.OLEML_FORMAT);
3421         getDocstoreClientLocator().getDocstoreClient().updateItem(item);
3422     } catch (Exception e) {
3423         LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
3424         throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
3425     }
3426 
3427     }
3428 
3429 
3430     public List splitListToSubList(List<OleLoanDocument> parentList, int childListSize) {
3431         List<List<OleLoanDocument>> childList = new ArrayList<List<OleLoanDocument>>();
3432         List<OleLoanDocument> tempList = new ArrayList<OleLoanDocument>();
3433         int count = 0;
3434         if (parentList != null) {
3435             for (OleLoanDocument obj : parentList) {
3436                 if (count < childListSize) {
3437                     count = count + 1;
3438                     tempList.add(obj);
3439                 } else {
3440                     childList.add(tempList);
3441                     tempList = new ArrayList<OleLoanDocument>();
3442                     tempList.add(obj);
3443                     count = 1;
3444                 }
3445             }
3446             if (tempList.size() <= childListSize) {
3447                 childList.add(tempList);
3448             }
3449         }
3450         return childList;
3451     }
3452 
3453 
3454     public void buildSearchParams(SearchParams searchParams){
3455         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "id"));
3456         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemBarcode_display"));
3457         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "bibIdentifier"));
3458         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Title_display"));
3459         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Author_display"));
3460         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "LocalId_display"));
3461         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "holdingsIdentifier"));
3462         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ClaimsReturnedFlag_display"));
3463         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedFlagCreateDate"));
3464         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedNote"));
3465         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumber_display"));
3466         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "TemporaryItemTypeFullValue_search"));
3467         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemTypeFullValue_display"));
3468         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Enumeration_display"));
3469         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Chronology_display"));
3470         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemStatus_display"));
3471         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemDamagedStatus_display"));
3472         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "DamagedItemNote_search"));
3473         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceFlagNote_search"));
3474         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Location_display"));
3475         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCopyNumber_search"));
3476         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCallNumber_search"));
3477         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsLocation_search"));
3478         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceCount_search"));
3479         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfPieces_search"));
3480         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumberPrefix_display"));
3481         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CopyNumber_search"));
3482         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "proxyBorrower"));
3483         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "VolumeNumberLabel_display"));
3484         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "dueDateTime"));
3485         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfRenew_display"));
3486         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item" , "checkOutDateTime"));
3487         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item","ClaimsReturnedFlag_search"));
3488         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item","itemStatusEffectiveDate"));
3489     }
3490 
3491 
3492     public void saveOLEDeliverNoticeHistory(OleLoanDocument oleLoanDocument){
3493         OLEDeliverNoticeHistory oleDeliverNoticeHistory = new OLEDeliverNoticeHistory();
3494         oleDeliverNoticeHistory.setLoanId(oleLoanDocument.getLoanId());
3495         oleDeliverNoticeHistory.setNoticeType(oleLoanDocument.getNoticeType());
3496         oleDeliverNoticeHistory.setNoticeSentDate(new Timestamp(new Date().getTime()));
3497         oleDeliverNoticeHistory.setPatronId(oleLoanDocument.getPatronId());
3498         oleDeliverNoticeHistory.setNoticeSendType(oleLoanDocument.getNoticeSendType());
3499         getBusinessObjectService().save(oleDeliverNoticeHistory);
3500     }
3501 
3502 }
3503 
3504 
3505 
3506 
3507 
3508