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