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