View Javadoc
1   package org.kuali.ole.deliver.processor;
2   
3   import org.apache.commons.collections.CollectionUtils;
4   import org.apache.commons.lang.StringUtils;
5   import org.apache.log4j.Logger;
6   import org.kuali.ole.DataCarrierService;
7   import org.kuali.ole.OLEConstants;
8   import org.kuali.ole.OLEParameterConstants;
9   import org.kuali.ole.deliver.batch.OleDeliverBatchServiceImpl;
10  import org.kuali.ole.deliver.batch.OleMailer;
11  import org.kuali.ole.deliver.batch.OleNoticeBo;
12  import org.kuali.ole.deliver.bo.*;
13  import org.kuali.ole.deliver.calendar.bo.OleCalendar;
14  import org.kuali.ole.deliver.calendar.service.OleCalendarService;
15  import org.kuali.ole.deliver.calendar.service.impl.OleCalendarServiceImpl;
16  import org.kuali.ole.deliver.form.OleLoanForm;
17  import org.kuali.ole.deliver.service.OLEDeliverNoticeHelperService;
18  import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
19  import org.kuali.ole.deliver.service.OleLoanDocumentDaoOjb;
20  import org.kuali.ole.describe.bo.OleInstanceItemType;
21  import org.kuali.ole.describe.bo.OleItemAvailableStatus;
22  import org.kuali.ole.describe.bo.OleLocation;
23  import org.kuali.ole.describe.bo.OleLocationLevel;
24  import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
25  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
26  import org.kuali.ole.docstore.common.document.*;
27  import org.kuali.ole.docstore.common.document.Item;
28  import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecord;
29  import org.kuali.ole.docstore.common.document.content.enums.DocType;
30  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
31  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
32  import org.kuali.ole.docstore.common.search.*;
33  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.DataField;
34  import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.SubField;
35  import org.kuali.ole.docstore.common.document.content.instance.AccessInformation;
36  import org.kuali.ole.docstore.common.document.content.instance.CallNumber;
37  import org.kuali.ole.docstore.common.document.content.instance.CheckInLocation;
38  import org.kuali.ole.docstore.common.document.content.instance.ItemStatus;
39  import org.kuali.ole.docstore.common.document.content.instance.ItemType;
40  import org.kuali.ole.docstore.common.document.content.instance.Location;
41  import org.kuali.ole.docstore.common.document.content.instance.LocationLevel;
42  import org.kuali.ole.docstore.common.document.content.instance.Note;
43  import org.kuali.ole.docstore.common.document.content.instance.NumberOfCirculations;
44  import org.kuali.ole.docstore.common.document.content.instance.OleHoldings;
45  import org.kuali.ole.docstore.common.document.content.instance.ShelvingScheme;
46  import org.kuali.ole.ingest.pojo.MatchBo;
47  import org.kuali.ole.pojo.bib.BibliographicRecord;
48  import org.kuali.ole.service.OleCirculationPolicyService;
49  import org.kuali.ole.service.OleCirculationPolicyServiceImpl;
50  import org.kuali.ole.sys.context.SpringContext;
51  import org.kuali.ole.util.DocstoreUtil;
52  import org.kuali.rice.core.api.config.property.ConfigContext;
53  import org.kuali.rice.core.api.mail.EmailBody;
54  import org.kuali.rice.core.api.mail.EmailFrom;
55  import org.kuali.rice.core.api.mail.EmailSubject;
56  import org.kuali.rice.core.api.mail.EmailTo;
57  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
58  import org.kuali.rice.core.api.util.type.KualiDecimal;
59  import org.kuali.rice.coreservice.api.CoreServiceApiServiceLocator;
60  import org.kuali.rice.coreservice.api.parameter.Parameter;
61  import org.kuali.rice.coreservice.api.parameter.ParameterKey;
62  import org.kuali.rice.kim.api.identity.principal.Principal;
63  import org.kuali.rice.kim.api.permission.PermissionService;
64  import org.kuali.rice.kim.api.role.Role;
65  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
66  import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
67  import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
68  import org.kuali.rice.kim.impl.identity.entity.EntityBo;
69  import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
70  import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
71  import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
72  import org.kuali.rice.kim.impl.role.RoleServiceImpl;
73  import org.kuali.rice.krad.service.BusinessObjectService;
74  import org.kuali.rice.krad.service.KRADServiceLocator;
75  import org.kuali.rice.krad.util.GlobalVariables;
76  import org.kuali.rice.krad.util.KRADConstants;
77  import org.kuali.rice.krms.api.KrmsApiServiceLocator;
78  import org.kuali.rice.krms.api.engine.*;
79  import org.kuali.rice.krms.api.repository.agenda.AgendaDefinition;
80  import org.kuali.rice.krms.api.repository.context.ContextDefinition;
81  import org.kuali.rice.krms.impl.repository.KrmsRepositoryServiceLocator;
82  
83  import javax.xml.datatype.DatatypeConfigurationException;
84  import javax.xml.datatype.DatatypeFactory;
85  import javax.xml.datatype.XMLGregorianCalendar;
86  import java.math.BigDecimal;
87  import java.sql.Timestamp;
88  import java.text.DateFormat;
89  import java.text.ParseException;
90  import java.text.SimpleDateFormat;
91  import java.util.*;
92  import java.util.regex.Matcher;
93  import java.util.regex.Pattern;
94  
95  /**
96   * The Loan Processor  class acts between the controller and the service layers in delegating the appropriate service
97   * to the functions called from the controller.
98   */
99  public class LoanProcessor {
100     private static final Logger LOG = Logger.getLogger(LoanProcessor.class);
101 
102     private BusinessObjectService businessObjectService;
103     private DocstoreUtil docstoreUtil;
104     private OleCirculationPolicyService oleCirculationPolicyService;
105     private OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService;
106     private String circDeskId;
107     private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
108     private static final String NAME_SELECTOR = "name";
109     private String lostDescription;
110     private String lostStatus;
111     private String lostPatronId;
112     private OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb;
113     private OLEDeliverNoticeHelperService oleDeliverNoticeHelperService;
114     private static Map<String, String> locationName = new HashMap<>();
115 
116     private DocstoreClientLocator docstoreClientLocator;
117 
118     private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
119 
120     private  DataCarrierService dataCarrierService;
121 
122     private String itemStatus;
123 
124     public DataCarrierService getDataCarrierService() {
125         if(dataCarrierService == null){
126             dataCarrierService = SpringContext.getBean(DataCarrierService.class);
127         }
128         return dataCarrierService;
129     }
130 
131     public DocstoreUtil getDocstoreUtil() {
132         if(docstoreUtil == null){
133             docstoreUtil = new DocstoreUtil();
134         }
135         return docstoreUtil;
136     }
137 
138     public void setDataCarrierService(DataCarrierService dataCarrierService) {
139         this.dataCarrierService = dataCarrierService;
140     }
141 
142     public DocstoreClientLocator getDocstoreClientLocator() {
143 
144         if (docstoreClientLocator == null) {
145             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
146 
147         }
148         return docstoreClientLocator;
149     }
150 
151 
152     public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
153         if(itemOlemlRecordProcessor == null){
154             itemOlemlRecordProcessor = SpringContext.getBean(ItemOlemlRecordProcessor.class);
155         }
156         return itemOlemlRecordProcessor;
157     }
158 
159     public OleDeliverRequestDocumentHelperServiceImpl getOleDeliverRequestDocumentHelperService() {
160         if (oleDeliverRequestDocumentHelperService == null) {
161             oleDeliverRequestDocumentHelperService = SpringContext.getBean(OleDeliverRequestDocumentHelperServiceImpl.class);
162         }
163         return oleDeliverRequestDocumentHelperService;
164     }
165 
166 
167     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
168         this.businessObjectService = businessObjectService;
169     }
170 
171     public void setOleCirculationPolicyService(OleCirculationPolicyService oleCirculationPolicyService) {
172         this.oleCirculationPolicyService = oleCirculationPolicyService;
173     }
174 
175     public void setOleDeliverRequestDocumentHelperService(OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService) {
176         this.oleDeliverRequestDocumentHelperService = oleDeliverRequestDocumentHelperService;
177     }
178 
179     public void setDocstoreClientLocator(DocstoreClientLocator docstoreClientLocator) {
180         this.docstoreClientLocator = docstoreClientLocator;
181     }
182 
183     public void setItemOlemlRecordProcessor(ItemOlemlRecordProcessor itemOlemlRecordProcessor) {
184         this.itemOlemlRecordProcessor = itemOlemlRecordProcessor;
185     }
186 
187     public String getLostDescription() {
188         return lostDescription;
189     }
190 
191     public void setLostDescription(String lostDescription) {
192         this.lostDescription = lostDescription;
193     }
194 
195     public String getLostStatus() {
196         return lostStatus;
197     }
198 
199     public void setLostStatus(String lostStatus) {
200         this.lostStatus = lostStatus;
201     }
202 
203     public String getLostPatronId() {
204         return lostPatronId;
205     }
206 
207     public void setLostPatronId(String lostPatronId) {
208         this.lostPatronId = lostPatronId;
209     }
210 
211     /**
212      * Gets the businessObjectService attribute.
213      *
214      * @return Returns the businessObjectService
215      */
216     public BusinessObjectService getBusinessObjectService() {
217         if (null == businessObjectService) {
218             businessObjectService = KRADServiceLocator.getBusinessObjectService();
219         }
220         return businessObjectService;
221     }
222 
223     /**
224      * Gets the oleCirculationPolicyService attribute.
225      *
226      * @return Returns the oleCirculationPolicyService
227      */
228     public OleCirculationPolicyService getOleCirculationPolicyService() {
229         if (null == oleCirculationPolicyService) {
230             oleCirculationPolicyService = SpringContext.getBean(OleCirculationPolicyServiceImpl.class);
231         }
232         return oleCirculationPolicyService;
233     }
234 
235 
236     /**
237      * Validates the patron barcode for general blocks and address verified.
238      *
239      * @param oleLoanDocument
240      * @return
241      * @throws Exception
242      */
243     private boolean checkAddressVerifiedAndBlocks(OleLoanDocument oleLoanDocument) throws Exception {
244         boolean isAddressVerified = false;
245         try {
246             isAddressVerified = (boolean) getOleCirculationPolicyService().isAddressVerified(oleLoanDocument.getOlePatron(),oleLoanDocument.getPatronId());
247             if (!isAddressVerified || oleLoanDocument.getOlePatron().isGeneralBlock()) {
248                 oleLoanDocument.setAddressVerified(true);
249             }
250         } catch (Exception e) {
251             LOG.error("Exception while checking address verified & blocks", e);
252             throw e;
253         }
254         return isAddressVerified;
255     }
256 
257     /**
258      * Retrieve information about patron name,borrorwer type and patron loaned items
259      *
260      * @param barcode
261      * @return OleLoanDocument
262      */
263     public OleLoanDocument getLoanDocument(String barcode, String realPtrnBarcode, boolean selfCheckOut,boolean isProxyToRealPatron) throws Exception {
264         LOG.debug("Inside the getLoanDocument method");
265 
266         OleLoanDocument oleLoanDocument = new OleLoanDocument();
267         String patronInactiveMessage=OLEConstants.PATRON_INVALID_BARCODE_MESSAGE;
268         if (barcode != null && checkLostPatronBarcode(barcode)) {
269             //oleLoanDocument.setErrorMessage(OLEConstants.H4 + OLEConstants.BARCODE_LOST_OR_STOLEN + OLEConstants.H4_CLOSE);
270             String url="<a target=\"_blank\" href="+OLEConstants.ASSIGN_EDIT_PATRON_ID + getLostPatronId() + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT+">"+getLostPatronId()+"</a>";
271             String patronUrl=OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + "Patron Details : " + OLEConstants.TEXT_BOLD_TAG_CLOSE +url+OLEConstants.H5_CLOSE + OLEConstants.H5;
272             oleLoanDocument.setErrorMessage(patronInactiveMessage+patronUrl+OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_STATUS_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostStatus()!=null?getLostStatus():"") + OLEConstants.H5_CLOSE + OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_DESCRIPTION_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostDescription()!=null?getLostDescription():"") + OLEConstants.H5_CLOSE);
273             oleLoanDocument.setBlockLoan(true);
274             oleLoanDocument.setLostPatron(true);
275             return oleLoanDocument;
276         } else if (realPtrnBarcode != null && checkLostPatronBarcode(realPtrnBarcode)) {
277             //oleLoanDocument.setErrorMessage(OLEConstants.H4 + OLEConstants.BARCODE_LOST_OR_STOLEN + OLEConstants.H4_CLOSE);
278             String url="<a target=\"_blank\" href="+OLEConstants.ASSIGN_EDIT_PATRON_ID + getLostPatronId() + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT+">"+getLostPatronId()+"</a>";
279             String patronUrl=OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + "Patron Details : " + OLEConstants.TEXT_BOLD_TAG_CLOSE +url+OLEConstants.H5_CLOSE + OLEConstants.H5;
280             oleLoanDocument.setErrorMessage(patronInactiveMessage+patronUrl+OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_STATUS_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostStatus()!=null?getLostStatus():"") + OLEConstants.H5_CLOSE + OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_DESCRIPTION_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostDescription()!=null?getLostDescription():"") + OLEConstants.H5_CLOSE);
281             oleLoanDocument.setBlockLoan(true);
282             oleLoanDocument.setLostPatron(true);
283             return oleLoanDocument;
284         }
285         oleLoanDocument = getPatronBarcodeRecord(barcode);
286         oleLoanDocument.setRealPatronBarcode(realPtrnBarcode);
287         Date expirationDate = oleLoanDocument.getOlePatron().getExpirationDate();
288         List<OlePatronDocument> proxyPatron = null;
289         if (!selfCheckOut && !isProxyToRealPatron) {
290             proxyPatron = (List<OlePatronDocument>) getOleCirculationPolicyService().isProxyPatron(oleLoanDocument.getOlePatron());
291         }
292         String agendaName = OLEConstants.CHECK_OUT_GEN_AGENDA_NM;
293         OleLoanDocument oleLoanDocumentForRealPatron = new OleLoanDocument();
294         String digitRoutine = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE);
295         String pattern = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE_PATTERN);
296         HashMap<String, Object> termValues = new HashMap<String, Object>();
297         // Check for Proxy Patron.
298         if (!isProxyToRealPatron) {
299             if (proxyPatron != null && proxyPatron.size() > 0 && !isProxyToRealPatron) {
300                 // Display real patron in pop up, if it is more than one. Or continue if the proxy patron as single real patron.
301                 if (realPtrnBarcode == null && proxyPatron.size() > 0) {
302                     oleLoanDocument.setRealPatron(proxyPatron);
303                     return oleLoanDocument;
304                 }
305                 oleLoanDocumentForRealPatron = getPatronBarcodeRecord(realPtrnBarcode);      // retrieves Loan Document for real patron.
306                 oleLoanDocument.setProxyPatronId(oleLoanDocumentForRealPatron.getPatronId());
307                 oleLoanDocument.setRealPatronName(getPatronName(oleLoanDocumentForRealPatron.getPatronId()));
308                 oleLoanDocument.setRealPatronType(oleLoanDocumentForRealPatron.getBorrowerTypeCode());
309                 boolean isAddressVerifiedReal = checkAddressVerifiedAndBlocks(oleLoanDocumentForRealPatron); // Checks isAddressVerified for real patron.
310                 termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocumentForRealPatron.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
311                 termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerifiedReal ? OLEConstants.TRUE : OLEConstants.FALSE);
312                 termValues.put(OLEConstants.EXPIR_DATE, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate());  // Checks Expiration Date for real patron.
313                 termValues.put(OLEConstants.PROXY_EXPIR_DATE, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate());                                 // Checks Expiration Date for proxy patron.
314                 termValues.put(OLEConstants.PATRON_BAR, realPtrnBarcode);  // Checks Barcode for real patron.
315                 termValues.put(OLEConstants.IS_PROXY_PATRON, OLEConstants.TRUE);
316                 termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocument.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
317                 termValues.put(OLEConstants.IS_ACTIVE_PROXY_PATRON, oleLoanDocumentForRealPatron.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
318                 termValues.put(OLEConstants.PROXY_PATRON_ACTIVATION_DATE, oleLoanDocumentForRealPatron.getOlePatron().getActivationDate());
319                 termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocument.getOlePatron().getActivationDate());
320                 termValues.put(OLEConstants.PROXY_PATRON_ACTIVATION_DATE_STRING, oleLoanDocumentForRealPatron.getOlePatron().getActivationDate() != null ? oleLoanDocumentForRealPatron.getOlePatron().getActivationDate().toString() : "null");
321                 termValues.put(OLEConstants.PROXY_PATRON_EXPIRATION_DATE_STRING, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate() != null ? oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate().toString() : "null");
322             } else {
323                 boolean isAddressVerified = checkAddressVerifiedAndBlocks(oleLoanDocument);
324                 termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocument.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
325                 termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
326                 termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
327                 termValues.put(OLEConstants.PATRON_BAR, barcode);
328                 termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocument.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
329                 termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocument.getOlePatron().getActivationDate());
330             }
331         } else {
332             OleLoanDocument oleLoanDocumentProxyToReal = new OleLoanDocument();
333             oleLoanDocumentProxyToReal=getPatronBarcodeRecord(barcode);
334             boolean isAddressVerified = checkAddressVerifiedAndBlocks(oleLoanDocumentProxyToReal);
335             termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocumentProxyToReal.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
336             termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
337             termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
338             termValues.put(OLEConstants.PATRON_BAR, barcode);
339             termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocumentProxyToReal.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
340             termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocumentProxyToReal.getOlePatron().getActivationDate());
341         }
342         termValues.put(OLEConstants.ACTIVATION_DATE_STRING, oleLoanDocument.getOlePatron().getActivationDate() != null ? oleLoanDocument.getOlePatron().getActivationDate().toString() : "null");
343         termValues.put(OLEConstants.EXPIRATION_DATE_STRING, oleLoanDocument.getOlePatron().getExpirationDate() != null ? oleLoanDocument.getOlePatron().getExpirationDate().toString() : "null");
344         termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
345         termValues.put(OLEConstants.PATTERN, pattern);
346         EngineResults engineResults = getEngineResults(agendaName, termValues);
347         HashMap<String, String> errorsAndPermission = new HashMap<>();
348         errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
349         StringBuffer failures = new StringBuffer();
350         oleLoanDocument.getErrorsAndPermission().clear();
351         int i = 1;
352         if (errorsAndPermission != null) {
353             Set<String> errorMessage = errorsAndPermission.keySet();
354             if (errorMessage != null && errorMessage.size() > 0) {
355                 //TODO KRMS Code Cleanup
356                 for (String errMsg : errorMessage) {
357                     if (StringUtils.isNotEmpty(errMsg)) {
358                         oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
359                         if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
360                             failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
361                             oleLoanDocument.setBlockLoan(true);
362                         } else {
363                             if (oleLoanDocument.getOlePatron().isGeneralBlock()) {
364                                 if (errMsg.equalsIgnoreCase(OLEConstants.GENERAL_BLOCK_MESSAGE)) {
365                                     failures.append(i++ + ". " + errMsg + " " + OLEConstants.SEMI_COLON + " " + oleLoanDocument.getOlePatron().getGeneralBlockNotes() + OLEConstants.BREAK);
366                                 } else {
367                                     failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
368                                 }
369                             } else {
370                                 failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
371                             }
372 
373                         }
374                     }
375                 }
376             }
377             errorsAndPermission.clear();
378         }
379         List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
380         if (errorMessage != null && errorMessage.size() > 0) {
381             for (String errMsg : errorMessage) {
382                 if (StringUtils.isNotEmpty(errMsg)) {
383                     if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
384                         failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
385                         oleLoanDocument.setBlockLoan(true);
386                     } else {
387                         failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
388                     }
389                 }
390             }
391         }
392         if (!failures.toString().isEmpty()) {
393             oleLoanDocument.setErrorMessage(failures.toString());
394         }
395         getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
396         getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
397         return oleLoanDocument;
398     }
399 
400 
401     /**
402      * Checks whether the patron barcode is Lost/Stolen.
403      *
404      * @param barcode
405      * @return
406      * @throws Exception
407      */
408     private boolean checkLostPatronBarcode(String barcode) throws Exception {
409         LOG.debug("Inside the checkLostPatronBarcode method");
410         Map barMap = new HashMap();
411         barMap.put("invalidOrLostBarcodeNumber", barcode);
412         List<OlePatronLostBarcode> olePatronLostBarcodes = (List<OlePatronLostBarcode>) getBusinessObjectService().findMatching(OlePatronLostBarcode.class, barMap);
413         boolean lostInvalidBarcode = false;
414         if (olePatronLostBarcodes != null) {
415             for (int lostBarcode = 0; lostBarcode < olePatronLostBarcodes.size(); lostBarcode++) {
416                 OlePatronLostBarcode olePatronLostBarcode = (OlePatronLostBarcode) olePatronLostBarcodes.get(lostBarcode);
417                 if (olePatronLostBarcode.getInvalidOrLostBarcodeNumber().equals(barcode) && (!olePatronLostBarcode.isActive())) {
418                     setLostDescription(olePatronLostBarcode.getDescription());
419                     setLostStatus(olePatronLostBarcode.getStatus());
420                     lostInvalidBarcode = true;
421                     setLostPatronId(olePatronLostBarcode.getOlePatronId());
422                     return lostInvalidBarcode;
423                 }
424             }
425         }
426         return lostInvalidBarcode;
427     }
428 
429     /**
430      * Retrieves Patron preferred address.
431      *
432      * @param entityTypeContactInfoBo
433      * @param loanDocument
434      * @return
435      * @throws Exception
436      */
437     private OleLoanDocument getPatronPreferredAddress(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
438         LOG.debug("Inside the getPatronPreferredAddress method");
439         if (entityTypeContactInfoBo.getAddresses() != null) {
440             for (EntityAddressBo entityAddressBo : entityTypeContactInfoBo.getAddresses()) {
441                 if (entityAddressBo.isDefaultValue()) {
442                     String address = "";
443                     if (entityAddressBo.getLine1() != null) {
444                         if (!entityAddressBo.getLine1().isEmpty()) {
445                             address += entityAddressBo.getLine1() + OLEConstants.COMMA;
446                         }
447                     }
448 
449                     if (entityAddressBo.getLine2() != null) {
450                         if (!entityAddressBo.getLine2().isEmpty()) {
451                             address += entityAddressBo.getLine2() + OLEConstants.COMMA;
452                         }
453                     }
454 
455                     if (entityAddressBo.getLine3() != null) {
456                         if (!entityAddressBo.getLine3().isEmpty()) {
457                             address += entityAddressBo.getLine3() + OLEConstants.COMMA;
458                         }
459                     }
460 
461                     if (entityAddressBo.getCity() != null) {
462                         if (!entityAddressBo.getCity().isEmpty()) {
463                             address += entityAddressBo.getCity() + OLEConstants.COMMA;
464                         }
465                     }
466 
467                     if (entityAddressBo.getStateProvinceCode() != null) {
468                         if (!entityAddressBo.getStateProvinceCode().isEmpty()) {
469                             address += entityAddressBo.getStateProvinceCode() + OLEConstants.COMMA;
470                         }
471                     }
472 
473                     if (entityAddressBo.getCountryCode() != null) {
474                         if (!entityAddressBo.getCountryCode().isEmpty()) {
475                             address += entityAddressBo.getCountryCode() + OLEConstants.COMMA;
476                         }
477                     }
478 
479                     if (entityAddressBo.getPostalCode() != null) {
480                         if (!entityAddressBo.getPostalCode().isEmpty()) {
481                             address += entityAddressBo.getPostalCode();
482                         }
483                     }
484 
485                     loanDocument.setPreferredAddress(address);
486                     break;
487                 }
488             }
489         }
490 
491         return loanDocument;
492     }
493 
494     /**
495      * Retrieves Patron home phone number.
496      *
497      * @param entityTypeContactInfoBo
498      * @param loanDocument
499      * @return
500      * @throws Exception
501      */
502     private OleLoanDocument getPatronHomePhoneNumber(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
503         LOG.debug("Inside the getPatronHomePhoneNumber method");
504         if (entityTypeContactInfoBo.getPhoneNumbers() != null) {
505             for (EntityPhoneBo entityPhoneBo : entityTypeContactInfoBo.getPhoneNumbers()) {
506                 if (entityPhoneBo.isDefaultValue()) {
507                     loanDocument.setPhoneNumber(entityPhoneBo.getPhoneNumber());
508                     break;
509                 }
510             }
511         }
512         return loanDocument;
513     }
514 
515     /**
516      * Retrieves Patron home email id.
517      *
518      * @param entityTypeContactInfoBo
519      * @param loanDocument
520      * @return
521      * @throws Exception
522      */
523     private OleLoanDocument getPatronHomeEmailId(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
524         LOG.debug("Inside the getPatronHomeEmailId method");
525         if (entityTypeContactInfoBo.getEmailAddresses() != null) {
526             for (EntityEmailBo entityEmailBo : entityTypeContactInfoBo.getEmailAddresses()) {
527                 if (entityEmailBo.isDefaultValue()) {
528                     loanDocument.setEmail(entityEmailBo.getEmailAddress());
529                     break;
530                 }
531             }
532         }
533         return loanDocument;
534     }
535 
536     /**
537      * Retrieves Patron user note.
538      *
539      * @param olePatronNotes
540      * @param loanDocument
541      * @return
542      * @throws Exception
543      */
544     private OleLoanDocument getPatronNote(List<OlePatronNotes> olePatronNotes, OleLoanDocument loanDocument) throws Exception {
545         LOG.debug("Inside the getPatronNote method");
546         for (OlePatronNotes patronNotes : olePatronNotes) {
547             if (patronNotes.getOlePatronNoteType() != null) {
548                 if (patronNotes.getOlePatronNoteType().getPatronNoteTypeCode().equalsIgnoreCase(OLEConstants.USER)) {
549                     loanDocument.setPatronUserNotes(patronNotes.getPatronNoteText());
550                     loanDocument.setPatronNoteTypeId((String) patronNotes.getPatronNoteTypeId());
551                     break;
552                 }
553             }
554         }
555         return loanDocument;
556     }
557 
558     /**
559      * This method returns Patron information using patron barcode.
560      *
561      * @param barcode
562      * @return loanDocument
563      * @throws Exception
564      */
565     private OleLoanDocument getPatronBarcodeRecord(String barcode) throws Exception {
566         LOG.debug("Inside the getPatronBarcodeRecord method");
567         OleLoanDocument loanDocument = new OleLoanDocument();
568         StringBuffer values_StringBuffer = new StringBuffer();
569         try {
570             Map barMap = new HashMap();
571             barMap.put(OLEConstants.OlePatron.BARCODE, barcode);
572             List<OlePatronDocument> matching = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
573             List<OleLoanDocument> loanDocuments = matching.get(0).getOleLoanDocuments();
574             List<OleLoanDocument> LoanDocumentList = new ArrayList<>();
575             List<OleLoanDocument> indefiniteLoanDocumentList = new ArrayList<>();
576             for (OleLoanDocument loanDoc : loanDocuments) {
577                 if (loanDoc.getLoanDueDate() != null && !(loanDoc.getLoanDueDate().toString().isEmpty())) {
578                     LoanDocumentList.add(loanDoc);
579                 } else {
580                     indefiniteLoanDocumentList.add(loanDoc);
581                 }
582             }
583             Collections.sort(LoanDocumentList, new Comparator<OleLoanDocument>() {
584                 public int compare(OleLoanDocument o1, OleLoanDocument o2) {
585                     return o1.getLoanDueDate().compareTo(o2.getLoanDueDate());
586                 }
587             });
588             LoanDocumentList.addAll(indefiniteLoanDocumentList);
589             if (matching != null && matching.size() > 0) {
590                 OlePatronDocument olePatronDocument = matching.get(0);
591                 olePatronDocument.setOleLoanDocuments(LoanDocumentList);
592                 loanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
593                 OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
594                 loanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
595                 loanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
596                 EntityBo entityBo = olePatronDocument.getEntity();
597                 loanDocument.setPatronName(getPatronName(entityBo));
598                 loanDocument.setPatronId(olePatronDocument.getOlePatronId());
599                 List<OlePatronNotes> olePatronNotes = olePatronDocument.getNotes();
600                 if (olePatronNotes != null) {
601                     loanDocument = getPatronNote(olePatronNotes, loanDocument);
602                 }
603                 EntityTypeContactInfoBo entityTypeContactInfoBo = entityBo!=null ? entityBo.getEntityTypeContactInfos().get(0) : null;
604                 if (entityTypeContactInfoBo != null) {
605                     loanDocument = getPatronPreferredAddress(entityTypeContactInfoBo, loanDocument);
606                     loanDocument = getPatronHomePhoneNumber(entityTypeContactInfoBo, loanDocument);
607                     loanDocument = getPatronHomeEmailId(entityTypeContactInfoBo, loanDocument);
608                 }
609                 loanDocument.setOlePatron(olePatronDocument);
610                 return loanDocument;
611             } else {
612                 LOG.error(OLEConstants.PTRN_BARCD_NOT_EXT);
613                 throw new Exception(OLEConstants.PTRN_BARCD_NOT_EXT);
614             }
615         } catch (Exception e) {
616             LOG.error(OLEConstants.PTRN_BARCD_NOT_EXT + e, e);
617             values_StringBuffer.append(OLEConstants.PTRN_BARCD_NOT_EXT + "  " + OLEConstants.PTRN_START_LINK + ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base") + OLEConstants.PTRN_END_LINK);
618             throw new Exception(values_StringBuffer.toString());
619         }
620 
621     }
622 
623     /**
624      * This method returns BorrowerTypeName using borrowerId
625      *
626      * @param borrowerId
627      * @return String
628      */
629     public OleBorrowerType getborrowerTypeName(String borrowerId) {
630         LOG.debug("Inside the getborrowerTypeName method");
631         OleBorrowerType oleBorrowerType = getBusinessObjectService().findBySinglePrimaryKey(OleBorrowerType.class, borrowerId);
632         return oleBorrowerType;
633     }
634 
635     /**
636      * This method returns PatronName using entityId
637      *
638      * @param entityId
639      * @return String
640      */
641     private String getPatronName(String entityId) {
642         LOG.debug("Inside the getPatronName method");
643         Map barMap = new HashMap();
644         barMap.put(OLEConstants.ENTITY_ID, entityId);
645         List<EntityNameBo> entityNameBo = (List<EntityNameBo>) getBusinessObjectService().findMatching(EntityNameBo.class, barMap);
646         return entityNameBo.get(0).getFirstName() + " " + entityNameBo.get(0).getLastName();
647     }
648 
649     /**
650      * This method returns PatronName using entityBo
651      *
652      * @param entityBo
653      * @return String
654      */
655     private String getPatronName(EntityBo entityBo) {
656         LOG.debug("Inside the getPatronName method");
657         List<EntityNameBo> entityNameBo = entityBo.getNames();
658         return entityNameBo!=null && entityNameBo.size() > 0 ? entityNameBo.get(0).getFirstName() + " " + entityNameBo.get(0).getLastName() : "";
659     }
660 
661 
662 
663     /**
664      * This method returns PatronLoanedItem using patronId
665      *
666      * @param patronId
667      * @return List
668      * @throws Exception
669      */
670     public List<OleLoanDocument> getPatronLoanedItem(String patronId) throws Exception {
671         DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
672         LOG.debug("Inside the getPatronLoanedItem method");
673         Map barMap = new HashMap();
674         barMap.put(OLEConstants.PTRN_ID, patronId);
675         List<OleLoanDocument> matchingLoan = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
676         List<String> idsToExport= new ArrayList<>();
677         HashMap<String,Object> loanMap = new HashMap<>();
678         for (int itemid = 0; itemid < matchingLoan.size(); itemid++) {
679             String itemUuid = matchingLoan.get(itemid).getItemUuid();
680             idsToExport.add(itemUuid);
681             loanMap.put(itemUuid,matchingLoan.get(itemid)) ;
682         }
683         List<Item> itemList = new ArrayList<>();
684         if(idsToExport.size()==1){
685             org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(idsToExport.get(0));
686             itemList.add(item);
687         }else{
688             itemList = getDocstoreClientLocator().getDocstoreClient().retrieveItems(idsToExport);
689         }
690         int count = 0;
691         for(Item item : itemList) {
692             // org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
693             org.kuali.ole.docstore.common.document.content.instance.Item itemContent = getItemOlemlRecordProcessor().fromXML(item.getContent());
694             if(itemContent.isClaimsReturnedFlag()){
695                 count++;
696             }
697             OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
698 
699             OleLoanDocument oleLoanDocument = (OleLoanDocument)loanMap.get(item.getId());
700             oleLoanDocument.setBibUuid(item.getHolding().getBib().getId());
701             oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
702             oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
703             oleLoanDocument.setInstanceUuid(item.getHolding().getId());
704             oleLoanDocument.setItemUuid(item.getId());
705             oleLoanDocument.setClaimsReturnedIndicator(itemContent.isClaimsReturnedFlag());
706             if (oleLoanDocument.isClaimsReturnedIndicator()) {
707                 oleLoanDocument.setClaimsReturnNote(itemContent.getClaimsReturnedNote());
708                 if (itemContent.getClaimsReturnedFlagCreateDate() != null)
709                     oleLoanDocument.setClaimsReturnedDate(new Timestamp(df.parse(itemContent.getClaimsReturnedFlagCreateDate()).getTime()));
710             }
711             if(oleLoanDocument.getOlePatron()!=null){
712                 oleLoanDocument.getOlePatron().setNumberOfClaimsReturned(count);
713             }
714             String callNumber;
715              if(itemContent.getCallNumber()!=null && !StringUtils.isEmpty(itemContent.getCallNumber().getNumber())){
716                 callNumber = itemContent.getCallNumber().getNumber();
717             }else {
718                 callNumber = getItemCallNumber(oleHoldings.getCallNumber());
719             }
720             String itemType;
721             if(itemContent.getTemporaryItemType() != null && itemContent.getTemporaryItemType().getCodeValue()!=null){
722                 itemType = itemContent.getTemporaryItemType().getCodeValue();
723             }else{
724                 itemType = itemContent.getItemType().getCodeValue();
725             }
726             oleLoanDocument.setItemCallNumber(callNumber);
727             getCopyNumber(itemContent,oleHoldings,oleLoanDocument);
728            // oleLoanDocument.setItemCopyNumber(itemContent.getCopyNumber());
729             oleLoanDocument.setEnumeration(itemContent.getEnumeration());
730             oleLoanDocument.setChronology(itemContent.getChronology());
731             oleLoanDocument.setItemStatus(itemContent.getItemStatus().getCodeValue());
732             oleLoanDocument.setItemType(itemType);
733             oleLoanDocument.setItemDamagedStatus(itemContent.isItemDamagedStatus());
734             oleLoanDocument.setItemDamagedNote(itemContent.getDamagedItemNote());
735             oleLoanDocument.setMissingPieceNote(itemContent.getMissingPieceFlagNote());
736             oleLoanDocument.setMissingPieceFlag(itemContent.isMissingPieceFlag());
737             oleLoanDocument.setMissingPiecesCount(itemContent.getMissingPiecesCount());
738             if(itemContent.getNumberOfPieces()!=null && !itemContent.getNumberOfPieces().equalsIgnoreCase("")){
739                 oleLoanDocument.setItemNumberOfPieces(new Integer(itemContent.getNumberOfPieces()));
740                 oleLoanDocument.setBackUpNoOfPieces(itemContent.getNumberOfPieces());
741             }
742             if (itemContent.getLocation().getLocationLevel() != null) {
743                 Location physicalLocation = itemContent.getLocation();
744                 LocationLevel locationLevel = null;
745                 locationLevel = physicalLocation.getLocationLevel();
746                 getOleLocationLevel(oleLoanDocument, locationLevel);
747             } else {
748                 //OleHoldings oleHoldings = getOleHoldings(oleLoanDocument.getInstanceUuid());
749                 if (oleHoldings != null) {
750                     Location physicalLocation = oleHoldings.getLocation();
751                     LocationLevel locationLevel = null;
752                     locationLevel = physicalLocation.getLocationLevel();
753 
754 
755                     getOleLocationLevel(oleLoanDocument, locationLevel);
756                 }
757             }
758             if(itemContent.getProxyBorrower()!=null){
759                 Map<String,String> map=new HashMap<String,String>();
760                 map.put("entityId",itemContent.getProxyBorrower());
761                 EntityNameBo entityNameBo=(EntityNameBo) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(EntityNameBo.class,map);
762                 if(entityNameBo!=null){
763                     oleLoanDocument.setRealPatronName(entityNameBo.getFirstName()+"  "+entityNameBo.getLastName());
764                 }
765             }
766 
767 
768         }
769 
770         return sortLoanDocumentByDueDate(matchingLoan);
771     }
772 
773 
774     public  List<OleLoanDocument>  sortLoanDocumentByDueDate(List<OleLoanDocument>  loanDocuments){
775         List<OleLoanDocument> LoanDocumentList = new ArrayList<>();
776         List<OleLoanDocument> indefiniteLoanDocumentList = new ArrayList<>();
777         for (OleLoanDocument loanDoc : loanDocuments) {
778             if (loanDoc.getLoanDueDate() != null && !(loanDoc.getLoanDueDate().toString().isEmpty())) {
779                 LoanDocumentList.add(loanDoc);
780             } else {
781 
782                 indefiniteLoanDocumentList.add(loanDoc);
783             }
784         }
785         Collections.sort(LoanDocumentList, new Comparator<OleLoanDocument>() {
786             public int compare(OleLoanDocument o1, OleLoanDocument o2) {
787                 return o1.getLoanDueDate().compareTo(o2.getLoanDueDate());
788             }
789         });
790         LoanDocumentList.addAll(indefiniteLoanDocumentList);
791         return LoanDocumentList;
792     }
793 
794 
795     public List<OleLoanDocument> getPatronLoanedItemBySolr(String patronId) throws Exception{
796       LOG.debug("Inside the getPatronLoanedItemBySolr method");
797       Long b1 = System.currentTimeMillis();
798       SearchResponse searchResponse = new SearchResponse();
799         HashMap<String,Object> loanMap = new HashMap<>();
800       if(patronId != null){
801           String itemStatusParam = getParameter(OLEParameterConstants.ITEM_STATUS_FOR_RET_LOAN);
802           String[] itemStatus = new String[0];
803           if(itemStatusParam != null){
804              itemStatus = itemStatusParam.split("[|]");
805           }
806          SearchParams searchParams = new SearchParams();
807          List<SearchCondition> searchConditions = new ArrayList<>();
808           int count = itemStatus.length;
809           for(int i=0; i< count;i++) {
810               if(i == (count-1)) {
811                   searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", itemStatus[i]), "AND"));
812               }
813               else {
814                   searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", itemStatus[i]), "OR"));
815               }
816           }
817 
818           searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField("item", "currentBorrower", patronId), "AND"));
819 
820          searchParams.setPageSize(Integer.parseInt(OLEConstants.MAX_PAGE_SIZE_FOR_LOAN));
821          buildSearchParams(searchParams);
822          searchParams.getSearchConditions().addAll(searchConditions);
823          searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
824       }
825         List<OleLoanDocument> matchingLoan = buildSearchResultsFields(searchResponse,loanMap);
826 
827 
828         Long b2 = System.currentTimeMillis();
829         Long total = b2 - b1;
830         LOG.info("The time taken for Docstore call :"+total);
831         return sortLoanDocumentByDueDate(matchingLoan);
832     }
833     /**
834      * This method returns PatronTemporaryCirculationHistoryRecord using patronId
835      *
836      * @param patronId
837      * @return List
838      * @throws Exception
839      */
840     public List<OleTemporaryCirculationHistory> getPatronTemporaryCirculationHistoryRecords(String patronId) throws Exception {
841         LOG.debug("Inside the getPatronTemporaryCirculationHistoryRecords method");
842         Map barMap = new HashMap();
843         barMap.put("olePatronId", patronId);
844         List<OleTemporaryCirculationHistory> matchingLoan = (List<OleTemporaryCirculationHistory>) getBusinessObjectService().findMatching(OleTemporaryCirculationHistory.class, barMap);
845         //List<String> itemUuids = new ArrayList<String>();
846         for (int itemid = 0; itemid < matchingLoan.size(); itemid++) {
847             String itemUuid = matchingLoan.get(itemid).getItemUuid();
848 
849 
850             org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
851 
852 
853             org.kuali.ole.docstore.common.document.content.instance.Item itemContent = getItemOlemlRecordProcessor().fromXML(item.getContent());
854             HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
855             OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(item.getHolding().getContent());
856             OleTemporaryCirculationHistory oleTemporaryCirculationHistory = matchingLoan.get(itemid);
857             if (oleTemporaryCirculationHistory.getItemUuid().equals(item.getId())) {
858                 oleTemporaryCirculationHistory.setTitle(item.getHolding().getBib().getTitle());
859                 oleTemporaryCirculationHistory.setAuthor(item.getHolding().getBib().getAuthor());
860 
861                 oleTemporaryCirculationHistory.setItemUuid(item.getId());
862 
863 
864                 if(itemContent.getCallNumber()!=null && !StringUtils.isEmpty(itemContent.getCallNumber().getNumber())){
865                    /* String[] callNumber = item.getCallNumber().split(" ");
866                     if (callNumber.length > 0) {
867                         item.setCallNumber(callNumber != null ? callNumber[0] : item.getCallNumber());
868                     }
869                     oleTemporaryCirculationHistory.setCallNumber(getItemCallNumber(item.getCallNumberType(), item.getCallNumberPrefix(), item.getCallNumber()));*/
870                     oleTemporaryCirculationHistory.setCallNumber(itemContent.getCallNumber().getNumber());
871                 } else {
872                    /* String[] callNumber = item.getHolding().getCallNumber().split(" ");
873                     if (callNumber.length > 0) {
874                         item.getHolding().setCallNumber(callNumber != null ? callNumber[0] : item.getHolding().getCallNumber());
875                     }
876                     oleTemporaryCirculationHistory.setCallNumber(getItemCallNumber(item.getHolding().getCallNumberType(), item.getHolding().getCallNumberPrefix(), item.getHolding().getCallNumber()));*/
877                     String callNumber = getItemCallNumber(oleHoldings.getCallNumber());
878                     oleTemporaryCirculationHistory.setCallNumber(callNumber);
879                 }
880                 oleTemporaryCirculationHistory.setCopyNumber(itemContent.getCopyNumber());
881                 oleTemporaryCirculationHistory.setVolumeNumber(itemContent.getVolumeNumber());
882                 oleTemporaryCirculationHistory.setItemStatus(itemContent.getItemStatus().getFullValue());
883                 oleTemporaryCirculationHistory.setItemType(itemContent.getItemType().getCodeValue());
884 
885                 Map<String, String> map = new HashMap<String, String>();
886                 map.put("circulationDeskId", oleTemporaryCirculationHistory.getCirculationLocationId());
887                 List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, map);
888                 for (OleCirculationDesk val : oleCirculationDesks) {
889 
890                     oleTemporaryCirculationHistory.setCirculationLocationCode(val.getCirculationDeskCode());
891 
892                 }
893                 if (oleTemporaryCirculationHistory.getCirculationLocationId() != null && !oleTemporaryCirculationHistory.getCirculationLocationId().equals("")) {
894                     StringBuffer locationLevel = new StringBuffer("");
895                     LocationValuesBuilder locationValuesBuilder = new LocationValuesBuilder();
896                     locationValuesBuilder.getLocation(itemContent, oleTemporaryCirculationHistory, item.getHolding().getId());
897                     /*oleTemporaryCirculationHistory.setShelvingLocation(getShelvingLocation(itemContent.getLocation().getLocationLevel().getName()));
898                     if (oleTemporaryCirculationHistory.getShelvingLocation() == null || (oleTemporaryCirculationHistory.getShelvingLocation() != null && oleTemporaryCirculationHistory.getShelvingLocation().isEmpty())) {
899                         oleTemporaryCirculationHistory.setShelvingLocation(getShelvingLocation(oleHoldings.getLocation().getLocationLevel().getName()));
900                     }*/
901                 }
902                 //break;
903 
904             }
905         }
906 
907 
908         return matchingLoan;
909     }
910 
911 
912     /**
913      * This method returns PatronRequestRecords  using patronId
914      *
915      * @param patronId
916      * @return List
917      * @throws Exception
918      */
919     public List<OleDeliverRequestBo> getPatronRequestRecords(String patronId) throws Exception {
920         LOG.debug("Inside the getPatronRequestRecords method");
921         Map barMap = new HashMap();
922         barMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, patronId);
923         List<OleDeliverRequestBo> matchingLoan = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, barMap);
924 
925         for (int itemid = 0; itemid < matchingLoan.size(); itemid++) {
926             String itemUuid = matchingLoan.get(itemid).getItemUuid();
927 
928 
929             org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
930             org.kuali.ole.docstore.common.document.content.instance.Item itemContent = getItemOlemlRecordProcessor().fromXML(item.getContent());
931             HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
932             OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(item.getHolding().getContent());
933             OleDeliverRequestBo oleDeliverRequestBo = matchingLoan.get(itemid);
934             if (oleDeliverRequestBo.getItemUuid().equals(item.getId())) {
935                 oleDeliverRequestBo.setTitle(item.getHolding().getBib().getTitle());
936                 oleDeliverRequestBo.setAuthor(item.getHolding().getBib().getAuthor());
937                 if(itemContent.getCallNumber()!=null && !StringUtils.isEmpty(itemContent.getCallNumber().getNumber())){
938 
939                     oleDeliverRequestBo.setCallNumber(itemContent.getCallNumber().getNumber());
940                     // oleDeliverRequestBo.setCallNumber(getItemCallNumber(item.getCallNumberType(), item.getCallNumberPrefix(), item.getCallNumber()));
941                 } else {
942               //      String callNumber = getItemCallNumber(itemContent, item.getHolding().getId());
943 
944                     oleDeliverRequestBo.setCallNumber(oleHoldings.getCallNumber().getNumber());
945                     //oleDeliverRequestBo.setCallNumber(getItemCallNumber(item.getHolding().getCallNumberType(), item.getHolding().getCallNumberPrefix(), item.getHolding().getCallNumber()));
946                 }
947                 oleDeliverRequestBo.setCopyNumber(itemContent.getCopyNumber());
948                 oleDeliverRequestBo.setVolumeNumber(itemContent.getVolumeNumber());
949                 oleDeliverRequestBo.setItemStatus(itemContent.getItemStatus().getCodeValue());
950                 oleDeliverRequestBo.setItemType(itemContent.getItemType().getCodeValue());
951 
952 
953                 if (oleDeliverRequestBo.getCirculationLocationCode() != null && !oleDeliverRequestBo.getCirculationLocationCode().equals("")) {
954                     StringBuffer locationLevel = new StringBuffer("");
955                     LocationValuesBuilder locationValuesBuilder = new LocationValuesBuilder();
956                     locationValuesBuilder.getLocation(itemContent, oleDeliverRequestBo, item.getHolding().getId());
957                    /* oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(itemContent.getLocation().getLocationLevel().getName()));
958                     if (oleDeliverRequestBo.getShelvingLocation() == null || (oleDeliverRequestBo.getShelvingLocation() != null && oleDeliverRequestBo.getShelvingLocation().isEmpty())) {
959 
960 
961                         oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleHoldings.getLocation().getLocationLevel().getName()));
962                     }*/
963                 }
964                 break;
965             }
966 
967 
968         }
969 
970         return matchingLoan;
971     }
972 
973 
974     private String getShelvingLocation(String location) throws Exception {
975         if (location != null) {
976             String[] arr = location.split("/");
977             for (int i = arr.length; i >= 0; i--) {
978                 return arr[i - 1];
979             }
980         }
981         return location;
982     }
983 
984 
985     public String getShelvingLocation(LocationLevel oleLocationLevel) {
986         String location = null;
987         if (oleLocationLevel != null) {
988             if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
989                 location = oleLocationLevel.getName();
990         } else {
991             location = getShelvingLocation(oleLocationLevel.getLocationLevel());
992         }
993         if ("".equals(location) || location == null) {
994             return null;
995         }
996         return location;
997     }
998 
999     public String getItemCallNumber(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String instanceUUID) throws Exception {
1000         CallNumber callNumber = null;
1001         if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()) {
1002             callNumber = oleItem.getCallNumber();
1003         } else {
1004             OleHoldings oleHoldings = getOleHoldings(instanceUUID);
1005 
1006             callNumber = oleHoldings.getCallNumber();
1007         }
1008         return getItemCallNumber(callNumber);
1009     }
1010 
1011     /**
1012      * Retrieves Item call number.
1013      *
1014      * @param callNumber
1015      * @return
1016      * @throws Exception
1017      */
1018     public String getItemCallNumber(CallNumber callNumber) throws Exception {
1019         LOG.debug("Inside the getItemCallNumber method");
1020         String itemCallNumber = "";
1021         if (callNumber != null) {
1022 
1023             if (StringUtils.isNotBlank(callNumber.getType())) {
1024                 itemCallNumber += callNumber.getType() + OLEConstants.DELIMITER_DASH;
1025             }
1026             if (StringUtils.isNotBlank(callNumber.getPrefix())) {
1027                 itemCallNumber += callNumber.getPrefix() + OLEConstants.DELIMITER_DASH;
1028             }
1029             if (callNumber.getNumber() != null) {
1030                 itemCallNumber += callNumber.getNumber();
1031             }
1032 
1033         }
1034         return itemCallNumber;
1035     }
1036 
1037     /**
1038      * Retrieves item xml using itemuuid.
1039      *
1040      * @param itemUUID
1041      * @return
1042      * @throws Exception
1043      */
1044     public String getItemXML(String itemUUID) throws Exception {
1045         LOG.debug("Inside the getItemXML method");
1046         String itemXml = "";
1047         try {
1048             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1049             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
1050             itemXml = item.getContent();
1051             if (LOG.isDebugEnabled()){
1052                 LOG.debug("item XML ----- > " + itemXml);
1053             }
1054         } catch (Exception e) {
1055             LOG.error(OLEConstants.ITM_BARCD_NT_AVAL_DOC, e);
1056             throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
1057         }
1058         return itemXml;
1059     }
1060 
1061     /**
1062      * Converts item xml to item pojo.
1063      *
1064      * @param itemXml
1065      * @return
1066      * @throws Exception
1067      */
1068     public org.kuali.ole.docstore.common.document.content.instance.Item getItemPojo(String itemXml) throws Exception {
1069         LOG.debug("Inside the getItemPojo method");
1070         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = null;
1071         try {
1072             oleItem = getItemOlemlRecordProcessor().fromXML(itemXml);
1073         } catch (Exception e) {
1074             LOG.error(OLEConstants.PAR_EXP, e);
1075             throw new Exception(OLEConstants.PAR_EXP);
1076         }
1077         return oleItem;
1078     }
1079 
1080     public void getDefaultHoldingLocation(OleLoanDocument oleLoanDocument) throws Exception {
1081         try {
1082             OleHoldings oleHoldings = getOleHoldings(oleLoanDocument.getInstanceUuid());
1083             if (oleHoldings != null) {
1084                 Location physicalLocation = oleHoldings.getLocation();
1085                 LocationLevel locationLevel = null;
1086                 locationLevel = physicalLocation.getLocationLevel();
1087                 getOleLocationLevel(oleLoanDocument, locationLevel);
1088             }
1089         } catch (Exception holdingException) {
1090             LOG.error("--------------Invalid Holding location data.---------------", holdingException);
1091 
1092             throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
1093         }
1094     }
1095 
1096     private void getCopyNumber( org.kuali.ole.docstore.common.document.content.instance.Item  item,OleHoldings oleHoldings,OleLoanDocument oleLoanDocument) throws Exception{
1097         if(item.getCopyNumber()!=null && !item.getCopyNumber().equals("")){
1098             oleLoanDocument.setItemCopyNumber(item.getCopyNumber());
1099         }else if(oleHoldings.getCopyNumber() != null && !oleHoldings.getCopyNumber().equals("")){
1100             oleLoanDocument.setItemCopyNumber(oleHoldings.getCopyNumber());
1101         }
1102     }
1103 
1104     /**
1105      * Retrieved item object from docstore using itemid .Fetch location code,item available status from item object and
1106      * retrieve title from bib object.
1107      *
1108      * @param patronBarcode
1109      * @param itemBarcode
1110      * @param oleLoanDocument
1111      * @return OleLoanDocument
1112      */
1113     public OleLoanDocument addLoan(String patronBarcode, String itemBarcode, OleLoanDocument oleLoanDocument,String operatorId) throws Exception {
1114 
1115         LOG.debug("Inside the addLoan method");
1116         String itemUUID= oleLoanDocument.getItemUuid();
1117         String holdingsId = null;
1118         Long begin = System.currentTimeMillis();
1119         if(itemUUID==null){
1120             try {
1121                 org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1122                 org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
1123                 SearchResponse searchResponse = null;
1124                 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, itemBarcode), ""));
1125                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
1126 //                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode(), "id"));
1127                 searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
1128                 for (SearchResult searchResult : searchResponse.getSearchResults()) {
1129                     for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1130                         String fieldName = searchResultField.getFieldName();
1131                         String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
1132 //                        if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("holdings")) {
1133 //                            holdingsId = fieldValue;
1134 //                        } else {
1135                         itemUUID = fieldValue;
1136                         oleLoanDocument.setItemUuid(itemUUID);
1137 //                        }
1138                     }
1139                 }
1140             } catch (Exception ex) {
1141                 GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "Item Exists");
1142                 LOG.error(OLEConstants.ITEM_EXIST + ex);
1143             }
1144         }
1145         Map<String,Object> detailMap = getOleDeliverRequestDocumentHelperService().retrieveBIbItemHoldingData(itemUUID);
1146         Bib bib = (Bib)detailMap.get(OLEConstants.BIB);
1147         oleLoanDocument.setTitle(bib.getTitle());
1148         oleLoanDocument.setAuthor(bib.getAuthor());
1149         org.kuali.ole.docstore.common.document.content.instance.Item item = (org.kuali.ole.docstore.common.document.content.instance.Item)detailMap.get(OLEConstants.ITEM);
1150         OleHoldings oleHoldings = (OleHoldings)detailMap.get(OLEConstants.HOLDING);
1151         org.kuali.ole.docstore.common.document.Item item1 = (org.kuali.ole.docstore.common.document.Item)detailMap.get("documentItem");
1152         oleLoanDocument.setInstanceUuid(oleHoldings.getHoldingsIdentifier());
1153         Long end = System.currentTimeMillis();
1154         Long timeTaken = end-begin;
1155         LOG.info("The Time Taken for Docstore call in Add Item"+timeTaken);
1156         Date pastDueDate = oleLoanDocument.getLoanDueDate();
1157         boolean itemValidation = itemValidation(item);
1158         if (!itemValidation) {
1159             if (oleLoanDocument.isRenewalItemFlag()) {
1160                 oleLoanDocument.setErrorMessage(OLEConstants.INVAL_ITEM);
1161                 return oleLoanDocument;
1162             } else {
1163                 throw new Exception(OLEConstants.INVAL_ITEM);
1164             }
1165         }
1166         oleLoanDocument.setOleItem(item);
1167         try {
1168             getCopyNumber(item,oleHoldings,oleLoanDocument);
1169             if(item.getCallNumber()!=null && !StringUtils.isEmpty(item.getCallNumber().getNumber())){
1170                 oleLoanDocument.setItemCallNumber(item.getCallNumber().getNumber());
1171             }else {
1172                 oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
1173             }
1174             oleLoanDocument.setEnumeration(item.getEnumeration());
1175             oleLoanDocument.setChronology(item.getChronology());
1176             String status = item.getItemStatus().getCodeValue();
1177             oleLoanDocument.setItemLoanStatus(status);
1178         } catch (Exception e) {
1179             LOG.error(OLEConstants.ITM_STS_NT_AVAL, e);
1180             if (oleLoanDocument.isRenewalItemFlag()) {
1181                 oleLoanDocument.setErrorMessage(OLEConstants.ITM_STS_NT_AVAL);
1182                 return oleLoanDocument;
1183             } else {
1184                 throw new Exception(OLEConstants.ITM_STS_NT_AVAL);
1185             }
1186         }
1187         oleLoanDocument.setItemId(itemBarcode);
1188         oleLoanDocument.setMissingPieceFlag(item.isMissingPieceFlag());
1189         oleLoanDocument.setMissingPiecesCount(item.getMissingPiecesCount());
1190         try {
1191             if (item.getTemporaryItemType() != null && item.getTemporaryItemType().getCodeValue() != "") {
1192                 OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(item.getTemporaryItemType().getCodeValue());
1193                 oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
1194                 oleLoanDocument.setItemType(oleInstanceItemType.getInstanceItemTypeCode());
1195                 oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
1196             }
1197             else if (item.getItemType() != null && item.getItemType().getCodeValue() != "") {
1198                 OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(item.getItemType().getCodeValue());
1199                 oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
1200                 oleLoanDocument.setItemType(oleInstanceItemType.getInstanceItemTypeCode());
1201                 oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
1202             }
1203         } catch (Exception e) {
1204             LOG.error(OLEConstants.INVAL_ITEM, e);
1205             throw new Exception(OLEConstants.INVAL_ITEM);
1206         }
1207         Long beginLocation = System.currentTimeMillis();
1208         getLocation(item, oleLoanDocument,item1);
1209         if (oleLoanDocument.getLocation() == null || oleLoanDocument.getLocation().isEmpty()) {
1210             getDefaultHoldingLocation(oleLoanDocument);
1211         }
1212         Long endLocation = System.currentTimeMillis();
1213         Long timeTakenLocation = endLocation-beginLocation;
1214         LOG.info("The Time Taken for Location call in Add Item"+timeTakenLocation);
1215         setLoan(oleLoanDocument);
1216         oleLoanDocument.setPatronBarcode(patronBarcode);
1217     /*    HashMap overdueItems = new HashMap();*/
1218       /*  Integer loanedItems = 0;*/
1219         Date expirationDate = null;
1220         Integer numberOfClaimsReturned = 0;
1221         String patronType = "";
1222         HashMap keyLoanMap = new HashMap();
1223 
1224         if (oleLoanDocument.getProxyPatronId() != null) {
1225             // Checking for real patron.
1226             keyLoanMap=getOleCirculationPolicyService().getLoanedKeyMap(oleLoanDocument.getProxyPatronId(),oleLoanDocument.isRenewalItemFlag());
1227             expirationDate = getOleCirculationPolicyService().getPatronMembershipExpireDate(oleLoanDocument.getRealPatronBarcode());
1228             /**
1229              * For performance issue I commenting the below code. The number of claims will be recorded in the patron document.
1230              */
1231             OlePatronDocument olePatronDocument = (OlePatronDocument) keyLoanMap.get("patronDetails");
1232             numberOfClaimsReturned = olePatronDocument!=null?olePatronDocument.getNumberOfClaimsReturned():0; //oleCirculationPolicyService.getNumberOfClaimsReturned(oleLoanDocument.getProxyPatronId());
1233             patronType = oleLoanDocument.getRealPatronType();
1234 
1235         } else {
1236             keyLoanMap=getOleCirculationPolicyService().getLoanedKeyMap(oleLoanDocument.getPatronId(),oleLoanDocument.isRenewalItemFlag());
1237             if (oleLoanDocument.getOlePatron() != null && oleLoanDocument.getOlePatron().getBarcode().equalsIgnoreCase(oleLoanDocument.getPatronBarcode())) {
1238                 expirationDate=oleLoanDocument.getOlePatron().getExpirationDate();
1239             } else {
1240                 expirationDate = getOleCirculationPolicyService().getPatronMembershipExpireDate(oleLoanDocument.getPatronBarcode());
1241             }
1242             /**
1243              * For performance issue I commenting the below code. The number of claims will be recorded in the patron document.
1244              */
1245             OlePatronDocument olePatronDocument = (OlePatronDocument) keyLoanMap.get("patronDetails");
1246             numberOfClaimsReturned = olePatronDocument!=null?olePatronDocument.getNumberOfClaimsReturned():0;
1247             patronType = oleLoanDocument.getBorrowerTypeCode();
1248 
1249         }
1250 
1251 
1252         oleLoanDocument.setExpirationDate(expirationDate);
1253         StringBuffer failures = new StringBuffer();
1254         List<FeeType> feeTypeList = oleCirculationPolicyService.getPatronBillPayment(oleLoanDocument.getPatronId());
1255 
1256         List<Integer> listOfOverDueDays = (List<Integer>)keyLoanMap.get(OLEConstants.LIST_OF_OVERDUE_DAYS);
1257         getDataCarrierService().addData(OLEConstants.LIST_OVERDUE_DAYS, listOfOverDueDays);
1258         getDataCarrierService().addData(OLEConstants.HOURS_DIFF, oleCirculationPolicyService.getHoursDiff(oleLoanDocument.getLoanDueDate(), new Date()));
1259         getDataCarrierService().addData(OLEConstants.DUEDATE, oleLoanDocument.getLoanDueDate());
1260         getDataCarrierService().addData(OLEConstants.CHECKINDATE, oleLoanDocument.getCheckInDate());
1261         getDataCarrierService().addData(OLEConstants.LIST_RECALLED_OVERDUE_DAYS, (List<Integer>) keyLoanMap.get(OLEConstants.LIST_RECALLED_OVERDUE_DAYS));
1262         String patronId = oleLoanDocument.getPatronId()!=null ?  oleLoanDocument.getPatronId() : "";
1263         String itemId = oleLoanDocument.getItemId()!=null ?  oleLoanDocument.getItemId() : "";
1264         getDataCarrierService().removeData(patronId + itemId);
1265         if (oleLoanDocument.isRenewalItemFlag()) {
1266             getDataCarrierService().addData(OLEConstants.EXCLUDE_TIME, true);
1267         }
1268         HashMap<String,Integer> itemTypeMap  = (HashMap<String, Integer>) keyLoanMap.get("itemTypeMap");
1269         getDataCarrierService().addData("itemTypeMap", getItemTypeFromCurrentLoan(itemTypeMap, oleLoanDocument));
1270         Integer overdueFineAmt = 0;
1271         Integer replacementFeeAmt = 0;
1272         Integer serviceFeeAmt = 0;
1273         for (FeeType feeType : feeTypeList) {
1274             Integer fineAmount = feeType.getFeeAmount().subtract(feeType.getPaidAmount()).intValue();
1275             overdueFineAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.OVERDUE_FINE) ? fineAmount : 0;
1276             replacementFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.REPLACEMENT_FEE) ? fineAmount : 0;
1277             serviceFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.SERVICE_FEE) ? fineAmount : 0;
1278         }
1279 
1280         OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ? getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
1281         oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
1282       /* if (oleCirculationDesk != null && oleCirculationDesk.getCalendarGroupId() != null) {
1283             OleCalendarService oleCalendarService = new OleCalendarServiceImpl();
1284             OleCalendar oleCalendar = oleCalendarService.getActiveCalendar(new Timestamp(System.currentTimeMillis()), oleCirculationDesk.getCalendarGroupId());
1285             if (oleCalendar == null) {
1286                 throw new Exception("Calendar does not exist");
1287             }
1288         }
1289         getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");*/
1290         getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");
1291         String operatorsCirculationLocation = circulationDeskLocations(oleCirculationDesk);
1292         if (LOG.isDebugEnabled()){
1293             LOG.debug("operatorsCirculationLocation---->" + operatorsCirculationLocation);
1294         }
1295         String requestType = null;
1296         OlePatronDocument oleRequestPatron = null;
1297         OleDeliverRequestBo oleDeliverRequestForQueue = null;
1298         OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
1299         if (oleDeliverRequestBo != null) {
1300             oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo);
1301             requestType = oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode();
1302             oleRequestPatron = getOlePatronDocument(oleDeliverRequestBo.getBorrowerId());
1303             oleLoanDocument.setOleRequestPatron(oleRequestPatron);
1304             String requestPatronId = oleRequestPatron != null ? oleRequestPatron.getOlePatronId() : null;
1305             if (oleLoanDocument.getPatronId().equals(requestPatronId)) {
1306                 oleLoanDocument.setRequestPatron(true);
1307                 oleLoanDocument.setOleRequestId(oleDeliverRequestBo.getRequestId());
1308             } else {
1309                 oleDeliverRequestForQueue = getCurrentQueue(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid());
1310                 oleLoanDocument.setOleRequestId(oleDeliverRequestForQueue != null ? oleDeliverRequestForQueue.getRequestId() : null);
1311             }
1312         }
1313 
1314         String digitRoutine = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE);
1315         String pattern = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE_PATTERN);
1316         String itemCircLoction = getFullPathLocation(getLocationByLocationCode(oleLoanDocument.getItemLocation()));
1317         DateFormat formatter = new SimpleDateFormat(OLEConstants.DDMMYYYYHHMMSS);
1318         Date loanDueDate = oleLoanDocument.getLoanDueDate() != null ? new Date(oleLoanDocument.getLoanDueDate().getTime()) : null;
1319         String dateToString = oleLoanDocument.getLoanDueDate() != null ? formatter.format(oleLoanDocument.getLoanDueDate()) : null;
1320         checkReplacementFineExist(oleLoanDocument);
1321         checkOverdueExist(oleLoanDocument);
1322         isItemLoanedByDifferentPatron(oleLoanDocument);
1323         checkItemDamagedStatus(oleLoanDocument);
1324         isMissingPieceFlagActive(oleLoanDocument);
1325         String agendaName = oleLoanDocument.isRenewalItemFlag() ? OLEConstants.RENEWAL_AGENDA_NM : OLEConstants.CHECK_OUT_AGENDA_NM;
1326         Integer noOfRenewals = Integer.parseInt(oleLoanDocument.getNumberOfRenewals())+1;
1327         HashMap<String, Object> termValues = new HashMap<String, Object>();
1328         termValues.put(OLEConstants.BORROWER_TYPE, patronType);
1329         termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemTypeName());
1330         termValues.put(OLEConstants.NUM_ITEMS_CHECKED_OUT, keyLoanMap.get(OLEConstants.LOANED_ITEM_COUNT));
1331         termValues.put(OLEConstants.NUM_OVERDUE_ITEMS_CHECKED_OUT, (Integer) keyLoanMap.get(OLEConstants.OVERDUE_COUNT));
1332         termValues.put(OLEConstants.NUM_OVERDUE_RECALLED_ITEMS_CHECKED_OUT, (Integer) keyLoanMap.get(OLEConstants.RECALL_COUNT));
1333         termValues.put(OLEConstants.NUM_CLAIMS_RETURNED, numberOfClaimsReturned);
1334         termValues.put(OLEConstants.OVERDUE_FINE_AMT, overdueFineAmt);
1335         termValues.put(OLEConstants.REPLACEMENT_FEE_AMT, replacementFeeAmt);
1336         termValues.put(OLEConstants.ALL_CHARGES, overdueFineAmt + replacementFeeAmt + serviceFeeAmt);
1337         termValues.put(OLEConstants.IS_RENEWAL, oleLoanDocument.isRenewalItemFlag() ? OLEConstants.TRUE : OLEConstants.FALSE);
1338         termValues.put(OLEConstants.NUM_RENEWALS, noOfRenewals.toString());
1339         termValues.put(OLEConstants.ITEMS_DUE_DATE, loanDueDate);
1340         termValues.put(OLEConstants.ITEMS_DUE_DATE_STRING, dateToString);
1341         termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
1342         termValues.put(OLEConstants.PATTERN, pattern);
1343         termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
1344         termValues.put(OLEConstants.ITEM_LOCATION, itemCircLoction);
1345         termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
1346         termValues.put(OLEConstants.IS_PATRON_POSITION_ONE, oleLoanDocument.getPatronId().equals(oleRequestPatron != null ? oleRequestPatron.getOlePatronId() : null) ? OLEConstants.TRUE : OLEConstants.FALSE);
1347         termValues.put(OLEConstants.REQUEST_TYPE, requestType);
1348       /*  termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());*/
1349         termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
1350         termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
1351         termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
1352         termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
1353         termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
1354         termValues.put(OLEConstants.REPLACEMENT_FEE_EXIST, oleLoanDocument.isReplacementFeeExist());
1355         termValues.put(OLEConstants.OVERDUE_FINE_EXIST, oleLoanDocument.isOverdueFineExist());
1356         termValues.put(OLEConstants.DIFF_PATRON_FLD, oleLoanDocument.isDifferentPatron());
1357         termValues.put(OLEConstants.ITEM_DAMAGED_STATUS_FLD, oleLoanDocument.isItemDamagedStatus());
1358         termValues.put(OLEConstants.ITEM_MISING_PICS_FLAG_FLD, oleLoanDocument.isMissingPieceFlag());
1359         termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
1360         termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
1361         EngineResults engineResults = getEngineResults(agendaName, termValues);
1362         getDataCarrierService().removeData(patronId + itemId);
1363         Timestamp dueDate = (Timestamp) engineResults.getAttribute(OLEConstants.DUE_DATE);
1364         BigDecimal fineRate = (BigDecimal) engineResults.getAttribute(OLEConstants.FINE_RATE);
1365         BigDecimal maxFine = (BigDecimal) engineResults.getAttribute(OLEConstants.MAX_FINE);
1366         String circulationPolicySetId = (String) engineResults.getAttribute(OLEConstants.CIRCULATION_POLICY_SET_ID);
1367         oleLoanDocument.setCirculationPolicyId(circulationPolicySetId != null ? circulationPolicySetId : OLEConstants.NO_CIRC_POLICY_FOUND);
1368         oleLoanDocument.setFineRate(maxFine != null ? maxFine : fineRate);
1369         oleLoanDocument.getErrorsAndPermission().clear();
1370         HashMap<String, String> errorsAndPermission = new HashMap<>();
1371         if( oleLoanDocument.isRenewalItemFlag() && checkPendingRequestforItem(oleLoanDocument.getItemUuid())){
1372             failures.append(OLEConstants.PENDING_RQST_RENEWAL_ITM_INFO+ OLEConstants.OR);
1373         }
1374         errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
1375         PermissionService service = KimApiServiceLocator.getPermissionService();
1376         if (dueDate == null) {
1377             oleLoanDocument.setDueDateEmpty(true);
1378         }
1379         int i = 1;
1380         if (errorsAndPermission != null) {
1381             Set<String> errorMessage = errorsAndPermission.keySet();
1382             if (errorMessage != null && errorMessage.size() > 0) {
1383                 for (String errMsg : errorMessage) {
1384                     if (StringUtils.isNotEmpty(errMsg)) {
1385                         oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
1386                         if (oleLoanDocument.isRenewalItemFlag()) {
1387                             String permission = errorsAndPermission.get(errMsg);
1388                             if(operatorId == null){
1389                                 if(GlobalVariables.getUserSession()!=null){
1390                                    operatorId = GlobalVariables.getUserSession().getPrincipalId();
1391                                 }
1392                             }
1393                             boolean hasRenewPermission = service.hasPermission(operatorId, OLEConstants.DLVR_NMSPC, permission);
1394                             if (!hasRenewPermission) {
1395                                 oleLoanDocument.setRenewPermission(false);
1396                             } else {
1397                                 oleLoanDocument.setRenewPermission(true);
1398                             }
1399                             failures.append(errMsg + OLEConstants.OR);
1400                         } else {
1401                             failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
1402                         }
1403                     }
1404                 }
1405             }
1406             errorsAndPermission.clear();
1407         }
1408         List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
1409         if (errorMessage != null && errorMessage.size() > 0) {
1410             for (String errMsg : errorMessage) {
1411                 if (StringUtils.isNotEmpty(errMsg)) {
1412                     if (errMsg.equalsIgnoreCase("Inform the current borrower that this item has some missing pieces before proceeding with checkout.")) {
1413                         if (item != null && item.getMissingPiecesCount() != null) {
1414                             errMsg = errMsg.replace("some", item.getMissingPiecesCount());
1415                         }
1416                     }
1417                     if (oleLoanDocument.isRenewalItemFlag()) {
1418                         failures.append(errMsg + OLEConstants.OR);
1419                     } else {
1420                         if (errMsg.equalsIgnoreCase("Item status is Lost")) {
1421                             //oleLoanDocument.setStatusLost(true);
1422                             failures.append(i++ + "." + errMsg + "-" + OLEConstants.ITEMSTATUSLOST + OLEConstants.BREAK);
1423                         } else {
1424                             failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
1425                         }
1426                     }
1427                 }
1428             }
1429         }
1430         if(oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.ITEM_STATUS_CHECKEDOUT)&& !oleLoanDocument.isRenewalItemFlag()){
1431             Map barMap = new HashMap();
1432             barMap.put("itemId", oleLoanDocument.getItemId());
1433             List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
1434             if (oleLoanDocuments != null && oleLoanDocuments.size()>0) {
1435                 String url = "<a target=\"_blank\" href=" + OLEConstants.ASSIGN_INQUIRY_PATRON_ID + oleLoanDocuments.get(0).getPatronId() + OLEConstants.ASSIGN_PATRON_INQUIRY + ">" + oleLoanDocuments.get(0).getPatronId() + "</a>";
1436                 failures.append(i++ + ". " + OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + "&nbsp;&nbsp;:&nbsp;" + url + OLEConstants.BREAK);
1437             }
1438         }
1439         getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
1440         getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
1441         if (item.getItemType().getCodeValue().equalsIgnoreCase(OLEConstants.NONCIRC) || circulationPolicySetId == null) {
1442             oleLoanDocument.setNonCirculatingItem(true);
1443         }
1444         if ((!oleLoanDocument.isRenewalItemFlag() || (oleLoanDocument.isRenewalItemFlag() && failures.toString().isEmpty()))) {
1445             oleLoanDocument.setLoanDueDate(dueDate != null ? dueDate : null);
1446         }
1447         if ((!oleLoanDocument.isRenewalItemFlag() || (oleLoanDocument.isRenewalItemFlag()))) {
1448             oleLoanDocument.setRenewalLoanDueDate(dueDate != null ? dueDate : null);
1449         }
1450         if (!failures.toString().isEmpty()) {
1451             oleLoanDocument.setErrorMessage(failures.toString());
1452             return oleLoanDocument;
1453         }
1454 
1455         if (oleLoanDocument.isRenewalItemFlag()) {
1456             if (oleLoanDocument.getNumberOfRenewals() == null) {
1457                 oleLoanDocument.setNumberOfRenewals(OLEConstants.ZERO);
1458             }
1459             String noOfRenewal = "" + (Integer.parseInt(oleLoanDocument.getNumberOfRenewals()) + 1);
1460             if(noOfRenewal!=null && !noOfRenewal.isEmpty()){
1461                 oleLoanDocument.setNumberOfOverdueNoticesSent("0");
1462             }
1463             oleLoanDocument.setNumberOfRenewals(noOfRenewal);
1464             oleLoanDocument.setPastDueDate(pastDueDate);
1465             oleLoanDocument.setRenewalItemFlag(false);
1466         }
1467         Long beginSaveLoan = System.currentTimeMillis();
1468         saveLoan(oleLoanDocument);
1469         Long endSaveLoan = System.currentTimeMillis();
1470         Long timeTakenSaveLoan = endSaveLoan-beginSaveLoan;
1471         LOG.info("The Time Taken for save loan in Add Item"+timeTakenSaveLoan);
1472         return oleLoanDocument;
1473     }
1474 
1475     public String circulationDeskLocations(OleCirculationDesk oleCirculationDesk) throws Exception {
1476         String operatorsCirculationLocation = "";
1477         if (oleCirculationDesk != null) {
1478             List<OleLocation> oleLocations = new ArrayList<OleLocation>();
1479             if (oleCirculationDesk.getOleCirculationDeskLocations() != null) {
1480                 for (OleCirculationDeskLocation oleCirculationDeskLocation : oleCirculationDesk.getOleCirculationDeskLocations()) {
1481                     oleLocations.add(oleCirculationDeskLocation.getLocation());
1482                 }
1483             } else {
1484                 throw new Exception(OLEConstants.NO_LOC_CIR_DESK);
1485             }
1486             StringBuffer location = new StringBuffer();
1487             for (OleLocation oleLocation : oleLocations) {
1488                 location.append(getFullPathLocation(oleLocation)).append(OLEConstants.DELIMITER_HASH);
1489             }
1490             operatorsCirculationLocation = location.toString();
1491         }
1492         return operatorsCirculationLocation;
1493     }
1494 
1495     public String getFullPathLocationByName(OleLocation oleLocation) throws Exception {
1496         String levelFullCode = "";
1497         if (oleLocation != null) {
1498             levelFullCode = oleLocation.getLocationName();
1499             boolean parentId = oleLocation.getParentLocationId() != null ? true : false;
1500             while (parentId) {
1501                 Map criteriaMap = new HashMap();
1502                 criteriaMap.put(OLEConstants.LOCATION_ID, oleLocation.getParentLocationId());
1503                 OleLocation location = businessObjectService.findByPrimaryKey(OleLocation.class,
1504                         criteriaMap);
1505                 if (levelFullCode != null) {
1506                     levelFullCode = location.getLocationName() + "-" + levelFullCode;
1507                 }
1508                 parentId = location.getParentLocationId() != null ? true : false;
1509                 oleLocation = location;
1510             }
1511         }
1512         return levelFullCode;
1513     }
1514 
1515     public String getFullPathLocation(OleLocation oleLocation) throws Exception {
1516         String levelFullCode = "";
1517         if (oleLocation != null) {
1518             levelFullCode = oleLocation.getLocationCode();
1519             boolean parentId = oleLocation.getParentLocationId() != null ? true : false;
1520             while (parentId) {
1521                 Map criteriaMap = new HashMap();
1522                 criteriaMap.put(OLEConstants.LOCATION_ID, oleLocation.getParentLocationId());
1523                 OleLocation location = businessObjectService.findByPrimaryKey(OleLocation.class,
1524                         criteriaMap);
1525                 if (levelFullCode != null) {
1526                     levelFullCode = location.getLocationCode() + OLEConstants.SLASH + levelFullCode;
1527                 }
1528                 parentId = location.getParentLocationId() != null ? true : false;
1529                 oleLocation = location;
1530             }
1531         }
1532         return levelFullCode;
1533     }
1534 
1535     /**
1536      * Retrieves Holding Object for given instance UUID.
1537      *
1538      * @param instanceUUID
1539      * @return
1540      * @throws Exception
1541      */
1542     public OleHoldings getOleHoldings(String instanceUUID) throws Exception {
1543         LOG.debug("--Inside getOleHoldings---");
1544 
1545         Holdings holdings = new Holdings();
1546 
1547 
1548         holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(instanceUUID);
1549 
1550 
1551         HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
1552         OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
1553 
1554 
1555         return oleHoldings;
1556     }
1557 
1558 
1559     /*private boolean CheckItemStatusIsCheckedOut(Item oleItem) {
1560         LOG.debug("Inside the CheckItemStatusIsCheckedOut method");
1561         String itemStatus = oleItem.getItemStatus();
1562         if(itemStatus.equalsIgnoreCase(OLEConstants.ITEM_STATUS_CHECKEDOUT)){
1563             return true;
1564         }else {
1565             return false;
1566         }
1567     }*/
1568 
1569    /* *//**
1570      * Check item barcode exist in docstore.
1571      * @param barcode
1572      * @return
1573      * @throws Exception
1574      *//*
1575     public boolean validateFastAddItem(String barcode) throws Exception{
1576         LOG.debug("Inside the validateFastAddItem method");
1577         SolrRequestReponseHandler solrRequestReponseHandler = new SolrRequestReponseHandler();
1578         List<HashMap<String, Object>> documentList = null;
1579         if(barcode != null){
1580           documentList= solrRequestReponseHandler.retriveResults(OLEConstants.ITEM_BARCODE_DISPLAY+barcode);
1581         }
1582         if(documentList != null && documentList.size() >0){
1583             return false;
1584         }else{
1585             return true;
1586         }
1587     }*/
1588 
1589     /**
1590      * Compares expiration date with due date.
1591      *
1592      * @param oleLoanDocument
1593      */
1594     private void compareExpirationDateWithDueDate(OleLoanDocument oleLoanDocument) {
1595         LOG.debug("Inside the compareExpirationDateWithDueDate method");
1596         if (oleLoanDocument.getExpirationDate() != null && oleLoanDocument.getLoanDueDate()!=null) {
1597             Timestamp expirationDate = new Timestamp(oleLoanDocument.getExpirationDate().getTime());
1598            /* if (oleLoanDocument.getLoanDueDate() == null) {
1599                 oleLoanDocument.setLoanDueDate(expirationDate);
1600             } else*/
1601             if (expirationDate.compareTo(oleLoanDocument.getLoanDueDate()) < 0) {
1602                 oleLoanDocument.setLoanDueDate(expirationDate);
1603             }
1604         }
1605     }
1606 
1607 
1608     public EngineResults getEngineResults(String agendaName, HashMap<String, Object> termValues) throws Exception {
1609         Long begin = System.currentTimeMillis();
1610         LOG.debug("Inside the getEngineResults method");
1611         EngineResults engineResult = null;
1612         try {
1613             Engine engine = KrmsApiServiceLocator.getEngine();
1614             ContextDefinition contextDefinition = KrmsRepositoryServiceLocator.getContextBoService().getContextByNameAndNamespace("OLE-CONTEXT","OLE");
1615             AgendaDefinition agendaDefinition = KrmsRepositoryServiceLocator.getAgendaBoService().getAgendaByNameAndContextId(agendaName,contextDefinition.getId());
1616             HashMap<String, String> map = new HashMap<String, String>();
1617             map.put(OLEConstants.AGENDA_NAME,agendaDefinition.getName());
1618             List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
1619 
1620             SelectionCriteria selectionCriteria =
1621                     SelectionCriteria.createCriteria(null, getSelectionContext(contextDefinition.getName()), getAgendaContext(agendaName));
1622 /*
1623             HashMap<String, Object> agendaValue = new HashMap<String, Object>();
1624             agendaValue.put(OLEConstants.NAME_NM, agendaName);
1625             List<AgendaBo> agendaBos = (List<AgendaBo>) getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
1626             AgendaBo agendaBo = agendaBos.get(0);
1627             HashMap<String, String> map = new HashMap<String, String>();
1628             map.put(OLEConstants.AGENDA_NAME, agendaBo.getName());
1629             List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
1630 
1631             SelectionCriteria selectionCriteria =
1632                     SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()), getAgendaContext(agendaName));*/
1633 
1634             Long end = System.currentTimeMillis();
1635             Long timeTaken = end - begin;
1636             LOG.info("-----------TimeTaken to complete inside KRMS Call-----------"+timeTaken);
1637             ExecutionOptions executionOptions = new ExecutionOptions();
1638             executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
1639 
1640             Facts.Builder factBuilder = Facts.Builder.create();
1641 
1642             for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
1643                 MatchBo matchBo = matchBoIterator.next();
1644                 factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
1645             }
1646             long b1 = System.currentTimeMillis();
1647             engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
1648             long b2 = System.currentTimeMillis();
1649             long tot = b2 - b1;
1650             LOG.info("-----------TimeTaken to complete Only KRMS Call -----------"+tot);
1651         } catch (Exception krmsException) {
1652             LOG.error("-----------KRMS EXCEPTION------------------", krmsException);
1653 
1654             throw new RuntimeException(krmsException);
1655         }
1656         Long end = System.currentTimeMillis();
1657         Long timeTaken = end - begin;
1658         LOG.info("-----------TimeTaken to complete KRMS Call-----------"+agendaName+"-------"+timeTaken);
1659         return engineResult;
1660     }
1661 
1662     /**
1663      * This method returns selectionContext using contextName.
1664      *
1665      * @param contextName
1666      * @return Map
1667      * @throws Exception
1668      */
1669     protected Map<String, String> getSelectionContext(String contextName) throws Exception {
1670         LOG.debug("Inside the getSelectionContext method");
1671         Map<String, String> selector = new HashMap<String, String>();
1672         selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
1673         selector.put(NAME_SELECTOR, contextName);
1674         return selector;
1675     }
1676 
1677     /**
1678      * This method returns agendaContext using agendaName.
1679      *
1680      * @param agendaName
1681      * @return Map
1682      * @throws Exception
1683      */
1684     protected Map<String, String> getAgendaContext(String agendaName) throws Exception {
1685         LOG.debug("Inside the getAgendaContext method");
1686         Map<String, String> selector = new HashMap<String, String>();
1687         selector.put(NAME_SELECTOR, agendaName);
1688         return selector;
1689     }
1690 
1691 
1692     /**
1693      * This method returns ItemTypeId using itemTypeName.
1694      *
1695      * @param itemTypeCode
1696      * @return OleInstanceItemType
1697      * @throws Exception
1698      */
1699     public OleInstanceItemType getItemTypeIdByItemType(String itemTypeCode) throws Exception {
1700         LOG.debug("Inside the getItemTypeIdByItemType method");
1701         Map barMap = new HashMap();
1702         barMap.put(OLEConstants.OleInstanceItemType.INSTANCE_ITEM_TYPE_CD, itemTypeCode);
1703         List<OleInstanceItemType> matchingItemType = (List<OleInstanceItemType>) getBusinessObjectService().findMatching(OleInstanceItemType.class, barMap);
1704         return matchingItemType.get(0);
1705     }
1706 
1707     /**
1708      * * This method returns location level using location name.
1709      *
1710      * @param levelName
1711      * @return List
1712      * @throws Exception
1713      */
1714     public OleLocationLevel getLocationLevelByName(String levelName) throws Exception {
1715         LOG.debug("Inside the getLocationLevelByName method");
1716         Map barMap = new HashMap();
1717         barMap.put(OLEConstants.LEVEL_NAME, levelName);
1718         List<OleLocationLevel> matchingLocationLevel = (List<OleLocationLevel>) getBusinessObjectService().findMatching(OleLocationLevel.class, barMap);
1719         return matchingLocationLevel.get(0);
1720     }
1721 
1722     private List<OleLocationLevel> getLocationLevel() throws Exception {
1723         LOG.debug("Inside the getLocationLevel method");
1724         List<OleLocationLevel> locationLevel = (List<OleLocationLevel>) getBusinessObjectService().findAllOrderBy(OleLocationLevel.class, OLEConstants.LEVEL_ID, true);
1725 
1726         return locationLevel;
1727     }
1728 
1729     /**
1730      * This method returns location using location code.
1731      *
1732      * @param locationCode
1733      * @return
1734      * @throws Exception
1735      */
1736     public OleLocation getLocationByLocationCode(String locationCode) throws Exception {
1737         LOG.debug("Inside the getLocationByLocationCode method");
1738         Map barMap = new HashMap();
1739         barMap.put(OLEConstants.LOC_CD, locationCode);
1740         List<OleLocation> matchingLocation = (List<OleLocation>) getBusinessObjectService().findMatching(OleLocation.class, barMap);
1741         return matchingLocation!=null && matchingLocation.size() >0 ? matchingLocation.get(0) : null;
1742     }
1743 
1744     /**
1745      * This method returns Location using locationId.
1746      *
1747      * @param locationId
1748      * @return OleLocation
1749      * @throws Exception
1750      */
1751     public OleLocation getLocationByLocationId(String locationId) throws Exception {
1752         LOG.debug("Inside the getLocationByLocationId method");
1753         Map location = new HashMap();
1754         location.put(OLEConstants.LOCATION_ID, locationId);
1755         OleLocation oleLocation = getBusinessObjectService().findByPrimaryKey(OleLocation.class, location);
1756         return oleLocation;
1757     }
1758 
1759 
1760     /**
1761      * This method returns LoanStatusId.
1762      *
1763      * @return String
1764      * @throws Exception
1765      */
1766     private String getLoanStatusId() throws Exception {
1767         LOG.debug("Inside the getLoanStatusId method");
1768         Map barMap1 = new HashMap();
1769         barMap1.put(OLEConstants.OleItemAvailableStatus.ITEM_AVAILABLE_STATUS_CD, OLEConstants.ITEM_STATUS_CHECKEDOUT);
1770         List<OleItemAvailableStatus> matchingOleLoanStatus = (List<OleItemAvailableStatus>) getBusinessObjectService().findMatching(OleItemAvailableStatus.class, barMap1);
1771         if (matchingOleLoanStatus.size() > 0)
1772             return matchingOleLoanStatus.get(0).getItemAvailableStatusId();
1773         return null;
1774     }
1775 
1776     /**
1777      * sets the value for location levels in Loan Document.
1778      *
1779      * @param locationLevelName
1780      * @param locationCode
1781      * @param oleLoanDoc
1782      * @return OleLoanDocument
1783      * @throws Exception
1784      */
1785     private OleLoanDocument setLocation(StringBuffer location,StringBuffer locationCodeBuff ,String locationLevelName, String locationCode, String locationName, OleLoanDocument oleLoanDoc) throws Exception {
1786         LOG.debug("Inside the setLocation method");
1787         if (locationCode != null) {
1788             if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_SHELVING)) {
1789                 location.append(locationName);
1790                 locationCodeBuff.append(locationCode);
1791                 oleLoanDoc.setItemLocation(locationCode);
1792             } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_COLLECTION)) {
1793 
1794                 location.append(locationName + "-");
1795                 locationCodeBuff.append(locationCode + "/");
1796                 oleLoanDoc.setItemCollection(locationCode);
1797 
1798             } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_LIBRARY)) {
1799                 location.append(locationName + "-");
1800                 locationCodeBuff.append(locationCode + "/");
1801                 oleLoanDoc.setItemLibrary(locationCode);
1802             } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_INSTITUTION)) {
1803                 location.append(locationName + "-");
1804                 locationCodeBuff.append(locationCode + "/");
1805                 oleLoanDoc.setItemInstitution(locationCode);
1806             } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_CAMPUS)) {
1807                 location.append(locationName + "-");
1808                 locationCodeBuff.append(locationCode + "/");
1809                 oleLoanDoc.setItemCampus(locationCode);
1810             }
1811         }
1812         return oleLoanDoc;
1813 
1814     }
1815 
1816     /**
1817      * This method returns location details.
1818      *
1819      * @param oleItem
1820      * @param oleLoanDoc
1821      * @throws Exception
1822      */
1823     public void getLocation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument oleLoanDoc) throws Exception {
1824         LOG.debug("Inside the getLocation method");
1825         try {
1826             Location physicalLocation = oleItem.getLocation();
1827             LocationLevel locationLevel = null;
1828             locationLevel = physicalLocation.getLocationLevel();
1829             getOleLocationLevel(oleLoanDoc, locationLevel);
1830         } catch (Exception itemException) {
1831             LOG.error("--------------Invalid Item location data.---------------");
1832             try {
1833                 OleHoldings oleHoldings = getOleHoldings(oleLoanDoc.getInstanceUuid());
1834                 if (oleHoldings != null) {
1835                     Location physicalLocation = oleHoldings.getLocation();
1836                     LocationLevel locationLevel = null;
1837                     locationLevel = physicalLocation.getLocationLevel();
1838                     getOleLocationLevel(oleLoanDoc, locationLevel);
1839                 }
1840             } catch (Exception holdingException) {
1841                 LOG.error("--------------Invalid Holding location data.---------------" + holdingException, holdingException);
1842                 throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
1843             }
1844         }
1845     }
1846 
1847     /**
1848      * This method returns location details.
1849      *
1850      * @param oleItem
1851      * @param oleLoanDoc
1852      * @throws Exception
1853      */
1854     public void getLocation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument oleLoanDoc,org.kuali.ole.docstore.common.document.Item item) throws Exception {
1855         LOG.debug("Inside the getLocation method");
1856         try {
1857             Location physicalLocation = oleItem.getLocation();
1858             LocationLevel locationLevel = null;
1859             locationLevel = physicalLocation.getLocationLevel();
1860             getOleLocationLevel(oleLoanDoc, locationLevel);
1861         } catch (Exception itemException) {
1862             LOG.error("--------------Invalid Item location data.---------------");
1863             try {
1864                 OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
1865                 if (oleHoldings != null) {
1866                     Location physicalLocation = oleHoldings.getLocation();
1867                     LocationLevel locationLevel = null;
1868                     locationLevel = physicalLocation.getLocationLevel();
1869                     getOleLocationLevel(oleLoanDoc, locationLevel);
1870                 }
1871             } catch (Exception holdingException) {
1872                 LOG.error("--------------Invalid Holding location data.---------------" + holdingException, holdingException);
1873                 throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
1874             }
1875         }
1876     }
1877 
1878     /**
1879      * Populate location levels.
1880      *
1881      * @param oleLoanDocument
1882      * @param locationLevel
1883      * @throws Exception
1884      */
1885     public void getOleLocationLevel(OleLoanDocument oleLoanDocument, LocationLevel locationLevel) throws Exception {
1886         LOG.debug("Inside the getOleLocationLevel method");
1887         StringBuffer location = new StringBuffer();
1888         StringBuffer locationCodeBuff = new StringBuffer();
1889         while (locationLevel.getLocationLevel() != null) {
1890             OleLocationLevel oleLocationLevel = getLocationLevelByName(locationLevel.getLevel());
1891             OleLocation oleLocation = new OleLocation();
1892             if (!"".equals(locationLevel.getName())) {
1893                 oleLocation = getLocationByLocationCode(locationLevel.getName());
1894                 oleLoanDocument.setOleLocation(oleLocation);
1895             }
1896             setLocation(location, locationCodeBuff,oleLocationLevel.getLevelName(), oleLocation.getLocationCode(), oleLocation.getLocationName(), oleLoanDocument);
1897             OleCirculationDesk oleCirculationDesk = getCirculationDeskByLocationId(oleLocation.getLocationId());
1898             if(oleCirculationDesk!=null){
1899                 oleLoanDocument.setLocationCode(oleCirculationDesk.getCirculationDeskCode());
1900                 oleLoanDocument.setRouteToLocationName(oleCirculationDesk.getCirculationDeskPublicName());
1901             }
1902             locationLevel = locationLevel.getLocationLevel();
1903         }
1904 
1905         oleLoanDocument.setItemLocation(locationLevel.getName());
1906         OleLocation oleLocation = getLocationByLocationCode(oleLoanDocument.getItemLocation());
1907         OleCirculationDesk oleCirculationDesk = getCirculationDeskByLocationId(oleLocation.getLocationId());
1908         OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
1909         OleCirculationDesk pickUpCircDesk = oleDeliverRequestBo != null && oleDeliverRequestBo.getPickUpLocationId() != null ? getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId()) : null;
1910         OleCirculationDesk destinationCircDesk = oleDeliverRequestBo != null && oleDeliverRequestBo.getCirculationLocationId() != null ? getOleCirculationDesk(oleDeliverRequestBo.getCirculationLocationId()) : null;
1911         if (pickUpCircDesk != null) {
1912             oleLoanDocument.setLocationCode(pickUpCircDesk.getCirculationDeskCode());
1913             oleLoanDocument.setRouteToLocationName(pickUpCircDesk.getCirculationDeskPublicName());
1914         } else if (destinationCircDesk != null) {
1915             oleLoanDocument.setLocationCode(destinationCircDesk.getCirculationDeskCode());
1916             oleLoanDocument.setRouteToLocationName(destinationCircDesk.getCirculationDeskPublicName());
1917         } else if (oleCirculationDesk != null) {
1918             oleLoanDocument.setLocationCode(oleCirculationDesk.getCirculationDeskCode());
1919             oleLoanDocument.setRouteToLocationName(oleCirculationDesk.getCirculationDeskPublicName());
1920         } else {
1921             oleLoanDocument.setRouteToLocationName(oleLocation.getLocationName());
1922         }
1923         location.append(oleLocation.getLocationName());
1924         locationCodeBuff.append(oleLocation.getLocationCode());
1925         oleLoanDocument.setLocation(location.toString());
1926         oleLoanDocument.setOleLocationCode(locationCodeBuff.toString());
1927         // }
1928     }
1929 
1930 
1931     /**
1932      * This method sets Title,loan Status,loan approver,loan operator,borrowerLimit and Item Unavailable in Loan Document..
1933      *
1934      * @param oleLoanDocument
1935      * @return OleLoanDocument
1936      * @throws Exception
1937      */
1938     public OleLoanDocument setLoan(OleLoanDocument oleLoanDocument) throws Exception {
1939         LOG.debug("Inside the setLoan method");
1940         if (StringUtils.isEmpty(oleLoanDocument.getTitle())) {
1941             org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1942             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
1943             SearchResponse searchResponse = null;
1944             if (oleLoanDocument.getBibUuid() == null) {
1945                 if (oleLoanDocument.getItemId() != null) {
1946                     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, oleLoanDocument.getItemId()), ""));
1947                 } else {
1948                     search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.ID, oleLoanDocument.getItemUuid()), ""));
1949                 }
1950                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
1951                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.TITLE));
1952                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.AUTHOR));
1953             } else {
1954                 search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), Bib.ID, oleLoanDocument.getBibUuid()), ""));
1955                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(DocType.BIB.getCode(), Bib.TITLE));
1956                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), Bib.AUTHOR));
1957             }
1958             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
1959             for (SearchResult searchResult : searchResponse.getSearchResults()) {
1960                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1961                     String fieldName = searchResultField.getFieldName();
1962                     String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
1963                     if (fieldName.equalsIgnoreCase(Bib.TITLE) && !fieldValue.isEmpty()) {
1964                         oleLoanDocument.setTitle(fieldValue);
1965                     } else if (fieldName.equalsIgnoreCase(Bib.AUTHOR) && !fieldValue.isEmpty()) {
1966                         oleLoanDocument.setAuthor(fieldValue);
1967                     }
1968                 }
1969             }
1970         }
1971         oleLoanDocument.setLoanStatusId(getLoanStatusId());
1972         //  String circPolciyId = oleLoanDocument.getCirculationPolicySetId();
1973         //  oleLoanDocument.setCirculationPolicyId(circPolciyId!=null?circPolciyId :OLEConstants.NO_CIRC_POLICY_FOUND);
1974         //commented for jira OLE-5675
1975         //oleLoanDocument.setMachineId("MACH12233");  // TODO: Need to fetch machine IP.
1976         oleLoanDocument.setCreateDate(new Timestamp(new Date().getTime()));
1977         String principalId = "";
1978         if (oleLoanDocument.getLoanOperatorId() == null) {
1979             oleLoanDocument.setLoanOperatorId(principalId);
1980         }
1981         //oleLoanDocument.setLoanApproverId("");
1982         if (GlobalVariables.getUserSession() != null) {
1983             principalId = GlobalVariables.getUserSession().getPrincipalId();
1984             String principalName = GlobalVariables.getUserSession().getPrincipalName();
1985             /*if (GlobalVariables.getUserSession().getPerson() != null) {
1986                 oleLoanDocument.setLoanApproverId(GlobalVariables.getUserSession().getPerson().getEntityId());
1987             }*/
1988             GlobalVariables.getUserSession().clearBackdoorUser();
1989             if (!principalId.equals(GlobalVariables.getUserSession().getPrincipalId())) {
1990                 oleLoanDocument.setLoanOperatorId(principalId);
1991                 GlobalVariables.getUserSession().setBackdoorUser(principalName);
1992             } else
1993                 oleLoanDocument.setLoanOperatorId(principalId);
1994         }
1995         return oleLoanDocument;
1996     }
1997 
1998     /**
1999      * persist the loan document and update item status to docstore.
2000      *
2001      * @param oleLoanDocument
2002      */
2003     public void saveLoan(OleLoanDocument oleLoanDocument) throws Exception {
2004         LOG.debug("Inside the saveLoan method");
2005         if (oleLoanDocument != null) {
2006             if (oleLoanDocument.getProxyPatronId() != null) {
2007                 String proxyPatronId = oleLoanDocument.getProxyPatronId();
2008                 oleLoanDocument.setProxyPatronId(oleLoanDocument.getPatronId());
2009                 oleLoanDocument.setPatronId(proxyPatronId);
2010             }
2011             if (oleLoanDocument.getFineRate() != null) {
2012                 if (oleLoanDocument.getOlePatron() == null) {
2013                     oleLoanDocument.setOlePatron(getOlePatronDocument(oleLoanDocument.getPatronId()));
2014                 }
2015                 if (oleLoanDocument.getFineRate().intValue() > 0)
2016                     generatePatronBillPayment(oleLoanDocument, OLEConstants.OVERDUE_FINE, oleLoanDocument.getFineRate());
2017             }
2018             compareExpirationDateWithDueDate(oleLoanDocument);
2019             getBusinessObjectService().save(oleLoanDocument);
2020             if (oleLoanDocument.isRequestPatron() || (!oleLoanDocument.isRequestPatron() && oleLoanDocument.getOleRequestId() != null && !"".equalsIgnoreCase(oleLoanDocument.getOleRequestId()))) {
2021                 String operatorId = (oleLoanDocument.getLoanApproverId() != null && !oleLoanDocument.getLoanApproverId().isEmpty()) ? oleLoanDocument.getLoanApproverId() : oleLoanDocument.getLoanOperatorId();
2022                 getOleDeliverRequestDocumentHelperService().deleteRequest(oleLoanDocument.getOleRequestId(), oleLoanDocument.getItemUuid(), operatorId, oleLoanDocument.getLoanId());
2023                 OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
2024                 if (oleDeliverRequestBo != null && oleDeliverRequestBo.getRequestTypeCode() != null &&
2025                         (oleDeliverRequestBo.getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_DELIVERY) ||
2026                                 oleDeliverRequestBo.getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_HOLD))) {
2027                     getDocstoreUtil().isItemAvailableInDocStore(oleDeliverRequestBo);
2028                     getOleDeliverRequestDocumentHelperService().executeEngineResults(oleDeliverRequestBo);
2029                     oleLoanDocument.setSuccessMessage(OLEConstants.DUE_DATE_INFO);
2030                 }
2031             }
2032             org.kuali.ole.docstore.common.document.content.instance.Item oleItem = oleLoanDocument.getOleItem();
2033             if(oleItem!=null){
2034                 oleItem.setCurrentBorrower(oleLoanDocument.getPatronId());
2035                 oleItem.setProxyBorrower(oleLoanDocument.getProxyPatronId());
2036         oleItem.setCheckOutDateTime(convertDateToString(oleLoanDocument.getCreateDate(),"MM/dd/yyyy HH:mm:ss"));
2037                 if (oleLoanDocument.getLoanDueDate() != null) {
2038                     oleItem.setDueDateTime(convertToString(oleLoanDocument.getLoanDueDate()));
2039                 }else{
2040                     oleItem.setDueDateTime("");
2041                 }
2042                 oleItem.setNumberOfRenew(Integer.parseInt(oleLoanDocument.getNumberOfRenewals()));
2043                 postLoan(oleItem);
2044             }
2045             if (getItemStatus() != null) {
2046                 oleLoanDocument.setItemStatus(getItemStatus());
2047             }
2048             if(oleLoanDocument.isRenewalItemFlag()){
2049                 oleLoanDocument.setRenewalItemFlag(false);
2050                 getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
2051             }
2052             getOleDeliverNoticeHelperService().generateDeliverNotices(oleLoanDocument);
2053         }
2054     }
2055 
2056     /**
2057      * This method is used to convert the date to string based on the given input format
2058      * @param format
2059      * @param date
2060      * @return
2061      */
2062     public String convertDateToString(Date date ,String format){
2063         LOG.info("Date Format : " +format + "Date : " + date);
2064         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
2065         String dateValue ="";
2066          try{
2067             dateValue = simpleDateFormat.format(date);
2068         }catch(Exception e){
2069              LOG.error(e,e);
2070          }
2071         LOG.info("Formatted Date : " + dateValue);
2072        return dateValue;
2073     }
2074 
2075     public String convertToString(Timestamp date) {
2076 //        Timestamp timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).format(date).concat(" ").concat(new SimpleDateFormat("HH:mm:ss").format(new Date())));
2077         SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
2078         SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2079         Date itemDate = null;
2080         try {
2081             itemDate = format2.parse(date.toString());
2082         } catch (ParseException e) {
2083             LOG.error("format string to Date " + e);
2084         }
2085         return format1.format(itemDate).toString();
2086     }
2087 
2088     private XMLGregorianCalendar getGregorianCalendar(Date date) throws DatatypeConfigurationException {
2089         GregorianCalendar gregory = new GregorianCalendar();
2090         gregory.setTime(date);
2091         XMLGregorianCalendar dealCloseDate = DatatypeFactory.newInstance()
2092                 .newXMLGregorianCalendar(gregory);
2093         return dealCloseDate;
2094     }
2095 
2096     public Collection getLoanObjectsFromDAO(List<OleLoanDocument> loanDocuments,String patronId){
2097         List<String> itemIds = new ArrayList<>();
2098         for(OleLoanDocument loanDocument : loanDocuments){
2099             itemIds.add(loanDocument.getItemUuid());
2100         }
2101         Collection loanObjects = getOleLoanDocumentDaoOjb().getLoanDocumentsUsingItemIdsAndPatronId(patronId,itemIds);
2102         return loanObjects;
2103     }
2104 
2105     public OleLoanDocument getLoanDocumentsUsingItemIdAndPatronId(String itemId ,String patronId){
2106         Map loanMap = new HashMap();
2107         loanMap.put("itemUuid",itemId);
2108         loanMap.put("patronId",patronId);
2109         List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class,loanMap);
2110         return oleLoanDocuments!=null && oleLoanDocuments.size()>0 ? oleLoanDocuments.get(0):null;
2111     }
2112     /**
2113      * Update loan due date in loan record.
2114      *
2115      * @param updateDueDate
2116      * @throws Exception
2117      */
2118     public boolean updateLoan(List<OleLoanDocument> updateDueDate, String patronId, boolean claimsReturn, boolean removeClaimsReturnFlag,String borrowerCode) throws Exception {
2119         Collection loanObjects = getLoanObjectsFromDAO(updateDueDate, patronId);
2120         int i = 0;
2121         LOG.debug("Inside the updateLoan method");
2122         if (loanObjects != null && loanObjects.size() > 0) {
2123             for (Object loanObject : loanObjects) {
2124                 OleLoanDocument oleLoanDocument = (OleLoanDocument) loanObject;
2125                 OleLoanDocument existingLoanObject = updateDueDate.size() > i ? updateDueDate.get(i) : null;
2126                 if (existingLoanObject != null) {
2127                     existingLoanObject.setCheckNo(false);
2128                     if (existingLoanObject.getLoanDueDateToAlter() != null) {
2129                         Timestamp timestamp;
2130                         Pattern pattern;
2131                         Matcher matcher;
2132                         SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OlePatron.PATRON_MAINTENANCE_DATE_FORMAT);
2133                         boolean timeFlag = false;
2134                         if (existingLoanObject.getLoanDueDateTimeToAlter() != null && !existingLoanObject.getLoanDueDateTimeToAlter().isEmpty()) {
2135                             String[] str = existingLoanObject.getLoanDueDateTimeToAlter().split(":");
2136                             pattern = Pattern.compile(OLEConstants.TIME_24_HR_PATTERN);
2137                             matcher = pattern.matcher(existingLoanObject.getLoanDueDateTimeToAlter());
2138                             timeFlag = matcher.matches();
2139                             if (timeFlag) {
2140                                 if (str != null && str.length <= 2) {
2141                                     existingLoanObject.setLoanDueDateTimeToAlter(existingLoanObject.getLoanDueDateTimeToAlter() + OLEConstants.CHECK_IN_TIME_MS);
2142                                 }
2143                                 timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
2144                                         format(existingLoanObject.getLoanDueDateToAlter()).concat(" ").concat(existingLoanObject.getLoanDueDateTimeToAlter()));
2145                             } else {
2146                                 return false;
2147                             }
2148                         } else if (fmt.format(existingLoanObject.getLoanDueDateToAlter()).compareTo(fmt.format(new Date())) == 0) {
2149                             String defaultCloseTime = getParameter(OLEParameterConstants.DEF_CLOSE_TIME);
2150                             timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
2151                                     format(new Date()).concat(" ").concat(defaultCloseTime));
2152                         } else {
2153                             String defaultCloseTime = getParameter(OLEParameterConstants.DEF_CLOSE_TIME);
2154                             timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
2155                                     format(existingLoanObject.getLoanDueDateToAlter()).concat(" ").concat(defaultCloseTime));
2156                         }
2157                         existingLoanObject.setLoanDueDate(timestamp);
2158                         oleLoanDocument.setLoanDueDate(timestamp);
2159                     }
2160                     if (claimsReturn && existingLoanObject != null) {
2161                         oleLoanDocument.setClaimsReturnNote(existingLoanObject.getClaimsReturnNote());
2162                         oleLoanDocument.setClaimsReturnedDate(existingLoanObject.getClaimsReturnedDate());
2163                         oleLoanDocument.setClaimsReturnedIndicator(existingLoanObject.isClaimsReturnedIndicator());
2164                     }
2165                     getBusinessObjectService().save(oleLoanDocument);
2166                     i++;
2167 
2168                     String itemXmlContent = getItemXML(existingLoanObject.getItemUuid());
2169                     org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(existingLoanObject.getItemUuid());
2170 
2171                     org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXmlContent);
2172                     if (claimsReturn && !removeClaimsReturnFlag) {
2173                         oleItem.setClaimsReturnedFlag(existingLoanObject.isClaimsReturnedIndicator());
2174                         if (existingLoanObject.getClaimsReturnedDate() != null) {
2175                             oleItem.setClaimsReturnedFlagCreateDate(convertToString(existingLoanObject.getClaimsReturnedDate()));
2176                         }
2177                         oleItem.setClaimsReturnedNote(existingLoanObject.getClaimsReturnNote());
2178                         getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(oleItem.getItemIdentifier());
2179                     } else if (removeClaimsReturnFlag) {
2180                         oleItem.setClaimsReturnedFlag(false);
2181                         oleItem.setClaimsReturnedFlagCreateDate(null);
2182                         oleItem.setClaimsReturnedNote(null);
2183                     } else {
2184                         if (existingLoanObject.getLoanDueDate() != null) {
2185                             oleItem.setDueDateTime(convertToString(existingLoanObject.getLoanDueDate()));
2186                         }
2187                     }
2188                     item.setId(existingLoanObject.getItemUuid());
2189                     item.setCategory(OLEConstants.WORK_CATEGORY);
2190                     item.setType(DocType.ITEM.getCode());
2191                     item.setFormat(OLEConstants.OLEML_FORMAT);
2192                     item.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
2193                     getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2194                     if(!claimsReturn){
2195                         Map<String,String> locationMap = existingLoanObject.getItemFullLocation()!= null ?
2196                                 getOleDeliverRequestDocumentHelperService().getLocationMap(existingLoanObject.getItemFullLocation()) : new HashMap<String,String>();
2197                         if(oleLoanDocument.getOleCirculationDesk()==null){
2198                             OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ? getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
2199                             oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
2200                         }
2201                         if(existingLoanObject.getItemTypeName()==null){
2202                             if(oleItem!=null){
2203                                 if(oleItem.getTemporaryItemType()!=null){
2204                                     existingLoanObject.setItemTypeName(oleItem.getTemporaryItemType().getCodeValue());
2205                                 }else if(oleItem.getItemType()!=null){
2206                                     existingLoanObject.setItemTypeName(oleItem.getItemType().getCodeValue());
2207                                 }
2208                             }
2209                         }
2210                         if(locationMap.size()>0){
2211                             existingLoanObject.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
2212                             existingLoanObject.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
2213                             existingLoanObject.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
2214                             existingLoanObject.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
2215                             existingLoanObject.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
2216                         }
2217                     }
2218                     getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
2219                     getOleDeliverNoticeHelperService().generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
2220                             oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
2221                             borrowerCode,existingLoanObject.getItemTypeName(), existingLoanObject.getItemStatus(),
2222                             existingLoanObject.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
2223                             oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
2224                             existingLoanObject.getItemLocation(), existingLoanObject.getItemCollection(), existingLoanObject.getItemLibrary(),
2225                             existingLoanObject.getItemCampus(), existingLoanObject.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
2226                 }
2227             }
2228         }
2229         return true;
2230     }
2231 
2232 
2233     public void updateItem(List<OleLoanDocument> loanList, boolean claimsReturn, boolean removeClaimsReturnFlag) throws Exception {
2234         if (loanList != null && !loanList.isEmpty()) {
2235             for (int existingLoan = 0; existingLoan < loanList.size(); existingLoan++) {
2236                 OleLoanDocument oleLoanDocument = (OleLoanDocument) loanList.get(existingLoan);
2237                 if (oleLoanDocument != null) {
2238                     String itemXmlContent = getItemXML(oleLoanDocument.getItemUuid());
2239                     org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2240 
2241                     org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXmlContent);
2242                     if (claimsReturn && !removeClaimsReturnFlag) {
2243                         oleItem.setClaimsReturnedFlag(oleLoanDocument.isClaimsReturnedIndicator());
2244                         if (oleLoanDocument.getClaimsReturnedDate() != null) {
2245                             oleItem.setClaimsReturnedFlagCreateDate(convertToString(oleLoanDocument.getClaimsReturnedDate()));
2246                         }
2247                         oleItem.setClaimsReturnedNote(oleLoanDocument.getClaimsReturnNote());
2248                         getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(oleItem.getItemIdentifier());
2249                     } else if (removeClaimsReturnFlag) {
2250                         oleItem.setClaimsReturnedFlag(false);
2251                         oleItem.setClaimsReturnedFlagCreateDate(null);
2252                         oleItem.setClaimsReturnedNote(null);
2253                     } else {
2254                         if (oleLoanDocument.getLoanDueDate() != null) {
2255                             oleItem.setDueDateTime(convertToString(oleLoanDocument.getLoanDueDate()));
2256                         }
2257                     }
2258                     item.setId(oleLoanDocument.getItemUuid());
2259                     item.setCategory(OLEConstants.WORK_CATEGORY);
2260                     item.setType(DocType.ITEM.getCode());
2261                     item.setFormat(OLEConstants.OLEML_FORMAT);
2262                     item.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
2263                     getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2264 
2265                     //LOG.info(itemRecordUpdateResponse);
2266                 }
2267             }
2268         }
2269     }
2270 
2271     /**
2272      * Compares the checked items from existing and current loan session and form a common list.
2273      *
2274      * @param loanList
2275      * @param existingLoanList
2276      * @param claimsFlag
2277      * @param claimsReturnNote
2278      * @return
2279      */
2280     public List<OleLoanDocument> setListValues(List<OleLoanDocument> loanList, List<OleLoanDocument> existingLoanList, boolean claimsFlag, String claimsReturnNote, boolean removeClaimsReturnFlag) {
2281         LOG.debug("Inside the setListValues method");
2282         List<OleLoanDocument> commonList = new ArrayList<OleLoanDocument>();
2283         List<OleLoanDocument> changeList = new ArrayList<OleLoanDocument>();
2284         if (loanList != null && !loanList.isEmpty()) {
2285             for (int curremtLoan = 0; curremtLoan < loanList.size(); curremtLoan++) {
2286                 OleLoanDocument oleLoanDocument = (OleLoanDocument) loanList.get(curremtLoan);
2287                 if (oleLoanDocument.isCheckNo()) {
2288                     if (claimsFlag) {
2289                         oleLoanDocument.setClaimsReturnNote(claimsReturnNote);
2290                         oleLoanDocument.setClaimsReturnedIndicator(claimsFlag);
2291                         oleLoanDocument.setClaimsReturnedDate(new Timestamp(new Date().getTime()));
2292                     } else if (removeClaimsReturnFlag) {
2293                         oleLoanDocument.setClaimsReturnedIndicator(false);
2294                         oleLoanDocument.setClaimsReturnedDate(null);
2295                         oleLoanDocument.setClaimsReturnNote(null);
2296                     } else {
2297                         if (oleLoanDocument.getLoanDueDate() != null) {
2298                         oleLoanDocument.setPastDueDate(oleLoanDocument.getLoanDueDate());
2299                         oleLoanDocument.setLoanDueDateToAlter(new Date(oleLoanDocument.getLoanDueDate().getTime()));
2300                         }
2301                     }
2302                     commonList.add(oleLoanDocument);
2303                 }
2304             }
2305         }
2306         if (existingLoanList != null && !existingLoanList.isEmpty()) {
2307             for (int existingLoan = 0; existingLoan < existingLoanList.size(); existingLoan++) {
2308                 OleLoanDocument oleLoanDocument = (OleLoanDocument) existingLoanList.get(existingLoan);
2309                 if (oleLoanDocument.isCheckNo()) {
2310                     if (claimsFlag) {
2311                         oleLoanDocument.setClaimsReturnNote(claimsReturnNote);
2312                         oleLoanDocument.setClaimsReturnedIndicator(true);
2313                         oleLoanDocument.setClaimsReturnedDate(new Timestamp(new Date().getTime()));
2314                     } else if (removeClaimsReturnFlag) {
2315                         oleLoanDocument.setClaimsReturnedIndicator(false);
2316                         oleLoanDocument.setClaimsReturnedDate(null);
2317                         oleLoanDocument.setClaimsReturnNote(null);
2318                     } else {
2319                         if (oleLoanDocument.getLoanDueDate() != null) {
2320                             oleLoanDocument.setPastDueDate(oleLoanDocument.getLoanDueDate());
2321                             oleLoanDocument.setLoanDueDateToAlter(new Date(oleLoanDocument.getLoanDueDate().getTime()));
2322                         }
2323                     }
2324                 commonList.add(oleLoanDocument);
2325             }
2326         }
2327         }
2328 
2329         return commonList;
2330     }
2331 
2332     /**
2333      * This method creates and return itemContent using OleItem
2334      *
2335      * @param oleItem
2336      * @return String
2337      * @throws Exception
2338      */
2339     public String buildItemContent(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
2340         LOG.debug("Inside the buildItemContent method");
2341         ItemStatus itemStatus = new ItemStatus();
2342         itemStatus.setCodeValue(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2343         itemStatus.setFullValue(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2344         this.setItemStatus(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2345         oleItem.setItemStatus(itemStatus);
2346         oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
2347         String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
2348         return itemContent;
2349     }
2350 
2351     /**
2352      * This method invokes docStore to store item and returns itemRecordUpdateResponse.
2353      *
2354      * @param oleItem
2355      * @throws Exception
2356      */
2357     public void postLoan(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
2358         LOG.debug("Inside the postLoan method");
2359         try {
2360             String itemUuid = oleItem.getItemIdentifier();
2361             String itemXmlContent = buildItemContent(oleItem);
2362             Item item = new ItemOleml();
2363             item.setId(itemUuid);
2364             item.setContent(itemXmlContent);
2365             item.setCategory(OLEConstants.WORK_CATEGORY);
2366             item.setType(DocType.ITEM.getCode());
2367             item.setFormat(OLEConstants.OLEML_FORMAT);
2368             item.setStaffOnly(oleItem.isStaffOnlyFlag());
2369             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2370         } catch (Exception e) {
2371             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
2372             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
2373         }
2374     }
2375 
2376 
2377     public BibliographicRecord getBibliographicRecord(String title, String author) {
2378         LOG.debug("Inside the getBibliographicRecord method");
2379 
2380         BibliographicRecord bibliographicRecord = new BibliographicRecord();
2381 
2382         List<DataField> dataFieldList = new ArrayList<DataField>();
2383         DataField titleDataField = new DataField();
2384         titleDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_245);
2385         List<SubField> subFields = new ArrayList<SubField>();
2386         SubField subField = new SubField();
2387         subField.setCode(OLEConstants.A);
2388         subField.setValue(title);
2389         subFields.add(subField);
2390         titleDataField.setSubFields(subFields);
2391         dataFieldList.add(titleDataField);
2392 
2393         if (author != null && !author.trim().isEmpty()) {
2394             DataField authorDataField = new DataField();
2395             authorDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_100);
2396             subFields = new ArrayList<SubField>();
2397             subField = new SubField();
2398             subField.setCode(OLEConstants.A);
2399             subField.setValue(author);
2400             subFields.add(subField);
2401             authorDataField.setSubFields(subFields);
2402             dataFieldList.add(authorDataField);
2403         }
2404         bibliographicRecord.setDatafields(dataFieldList);
2405         return bibliographicRecord;
2406 
2407     }
2408 
2409     public BibMarcRecord getBibMarcRecord(String title, String author) {
2410         LOG.debug("Inside the getBibliographicRecord method");
2411 
2412         BibMarcRecord bibMarcRecord = new BibMarcRecord();
2413         List<org.kuali.ole.docstore.common.document.content.bib.marc.DataField> dataFieldList = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.DataField>();
2414         org.kuali.ole.docstore.common.document.content.bib.marc.DataField titleDataField = new org.kuali.ole.docstore.common.document.content.bib.marc.DataField();
2415         titleDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_245);
2416         List<org.kuali.ole.docstore.common.document.content.bib.marc.SubField> subFields = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.SubField>();
2417         org.kuali.ole.docstore.common.document.content.bib.marc.SubField subField = new org.kuali.ole.docstore.common.document.content.bib.marc.SubField();
2418         subField.setCode(OLEConstants.A);
2419         subField.setValue(title);
2420         subFields.add(subField);
2421         titleDataField.setSubFields(subFields);
2422         dataFieldList.add(titleDataField);
2423 
2424         if (author != null && !author.trim().isEmpty()) {
2425             org.kuali.ole.docstore.common.document.content.bib.marc.DataField authorDataField = new org.kuali.ole.docstore.common.document.content.bib.marc.DataField();
2426             authorDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_100);
2427             subFields = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.SubField>();
2428             subField = new org.kuali.ole.docstore.common.document.content.bib.marc.SubField();
2429             subField.setCode(OLEConstants.A);
2430             subField.setValue(author);
2431             subFields.add(subField);
2432             authorDataField.setSubFields(subFields);
2433             dataFieldList.add(authorDataField);
2434         }
2435 
2436         bibMarcRecord.setDataFields(dataFieldList);
2437         return bibMarcRecord;
2438     }
2439 
2440     public LocationLevel createLocationLevel(String locationName, LocationLevel locationLevel) {
2441         LOG.debug("Inside the createLocationLevel method");
2442         if (locationName != null && !locationName.equalsIgnoreCase("")) {
2443             BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2444             String[] names = locationName.split("/");
2445             Map parentCriteria = new HashMap();
2446             parentCriteria.put(OLEConstants.LOC_CD, names[0]);
2447             OleLocation oleLocationCollection = businessObjectService.findByPrimaryKey(OleLocation.class, parentCriteria);
2448             String levelName = oleLocationCollection.getLocationName();
2449             String locationCode = oleLocationCollection.getLocationCode();
2450             String levelCode = oleLocationCollection.getOleLocationLevel().getLevelName();
2451             locationLevel.setName(locationCode);
2452             locationLevel.setLevel(levelCode);
2453             String locName = "";
2454             if (locationName.contains(OLEConstants.SLASH))
2455                 locName = locationName.replace(names[0] + OLEConstants.SLASH, "");
2456             else
2457                 locName = locationName.replace(names[0], "");
2458             if (locName != null && !locName.equals("")) {
2459                 LocationLevel newLocationLevel = new LocationLevel();
2460                 locationLevel.setLocationLevel(createLocationLevel(locName, newLocationLevel));
2461             }
2462         }
2463         return locationLevel;
2464     }
2465 
2466     public OleHoldings getHoldingRecord(OleLoanFastAdd oleLoanFastAdd) {
2467         OleHoldings oleHolding = new OleHoldings();
2468         LocationLevel locationLevel = new LocationLevel();
2469         locationLevel = createLocationLevel(oleLoanFastAdd.getLocationName(), locationLevel);
2470         Location location = new Location();
2471         location.setPrimary(OLEConstants.TRUE);
2472         location.setStatus(OLEConstants.PERMANENT);
2473         location.setLocationLevel(locationLevel);
2474 
2475         oleHolding.setLocation(location);
2476         oleHolding.setCallNumber(getCallNumber(oleLoanFastAdd));
2477         oleHolding.setPrimary(OLEConstants.TRUE);
2478         //oleHolding.setExtension(getExtension());
2479         return oleHolding;
2480     }
2481 
2482     public org.kuali.ole.docstore.common.document.content.instance.Item getItemRecord(OleLoanFastAdd oleLoanFastAdd) {
2483         LOG.debug("Inside the getItemRecord method");
2484         org.kuali.ole.docstore.common.document.content.instance.Item item = new org.kuali.ole.docstore.common.document.content.instance.Item();
2485 
2486         ItemType itemType = new ItemType();
2487         itemType.setCodeValue(oleLoanFastAdd.getItemType());
2488         item.setItemType(itemType);
2489         item.setCallNumber(getCallNumber(oleLoanFastAdd));
2490         item.setCopyNumberLabel(oleLoanFastAdd.getCopyNumber());
2491         item.setEnumeration(oleLoanFastAdd.getEnumeration());
2492         item.setCheckinNote(oleLoanFastAdd.getCheckinNote());
2493         item.setFastAddFlag(true);
2494         item.setNumberOfPieces(oleLoanFastAdd.getNumberOfPieces());
2495     /* LocationLevel locationLevel=new LocationLevel();
2496         locationLevel.setName(oleLoanFastAdd.getLocationName());
2497      Location value=new Location();
2498 */
2499 
2500 
2501         List<Note> notes = new ArrayList<Note>();
2502         Note note = new Note();
2503         note.setValue(oleLoanFastAdd.getNote());
2504         notes.add(note);
2505         item.setNote(notes);
2506 
2507         AccessInformation accessInformation = new AccessInformation();
2508         accessInformation.setBarcode(oleLoanFastAdd.getBarcode());
2509 
2510         item.setAccessInformation(accessInformation);
2511         OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(getParameter(OLEParameterConstants.FAST_ADD_ITEM_DEFAULT_STATUS));
2512         ItemStatus itemStatus = new ItemStatus();
2513         itemStatus.setCodeValue(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusCode() : null);
2514         itemStatus.setFullValue(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusCode() : null);
2515         item.setItemStatus(itemStatus);
2516         item.setCopyNumber(oleLoanFastAdd.getCopyNumber());
2517         //item.setExtension(getExtension());
2518 
2519         return item;
2520     }
2521 
2522     public OleItemAvailableStatus validateAndGetItemStatus(String itemStatusCode) {
2523         Map criteriaMap = new HashMap();
2524         criteriaMap.put(OLEConstants.ITEM_STATUS_CODE, itemStatusCode);
2525         OleItemAvailableStatus itemAvailableStatus = getBusinessObjectService().findByPrimaryKey(OleItemAvailableStatus.class, criteriaMap);
2526         return itemAvailableStatus;
2527     }
2528 
2529     public boolean canOverrideLoan(String principalId) {
2530         LOG.debug("Inside the canOverrideLoan method");
2531         PermissionService service = KimApiServiceLocator.getPermissionService();
2532         return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_OVERRIDE_LOAN);
2533     }
2534 
2535     /*public boolean canLoan(String principalId) {
2536         LOG.debug("Inside the canLoan method");
2537         PermissionService service = KimApiServiceLocator.getPermissionService();
2538         return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN);
2539     }*/
2540 
2541     public boolean hasCirculationDesk(String principalId) {
2542         boolean hasCirculationDesk = false;
2543         String circkDesk = null;
2544         Map<String, String> userMap = new HashMap<String, String>();
2545         userMap.put("operatorId", principalId);
2546         List<OleCirculationDeskDetail> oleCirculationDeskDetails = (List<OleCirculationDeskDetail>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, userMap);
2547         if (oleCirculationDeskDetails != null && oleCirculationDeskDetails.size() > 0) {
2548             hasCirculationDesk = true;
2549         }
2550         return hasCirculationDesk;
2551     }
2552 
2553     public boolean canEdit(String principalId) {
2554         PermissionService service = KimApiServiceLocator.getPermissionService();
2555         return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.EDIT_PATRON);
2556     }
2557 
2558     public String patronNameURL(String loginUser, String patronId) {
2559         boolean canEdit = canEdit(loginUser);
2560         String patronNameURL = "";
2561         if (canEdit) {
2562             patronNameURL = OLEConstants.ASSIGN_EDIT_PATRON_ID + patronId + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT;
2563         } else {
2564             patronNameURL = OLEConstants.ASSIGN_INQUIRY_PATRON_ID + patronId + OLEConstants.ASSIGN_PATRON_INQUIRY;
2565         }
2566         return patronNameURL;
2567     }
2568 
2569     public boolean checkOverRidePermission(String principalId, OleLoanForm oleLoanForm) {
2570         LOG.debug("Inside the checkOverRidePermission method");
2571         boolean overRideFlag = true;
2572         PermissionService service = KimApiServiceLocator.getPermissionService();
2573         if (oleLoanForm.getErrorsAndPermission() != null) {
2574             Set<String> errorMessages = oleLoanForm.getErrorsAndPermission().keySet();
2575             for (String errorMessage : errorMessages) {
2576                 if (StringUtils.isNotEmpty(errorMessage)) {
2577                     String permission = oleLoanForm.getErrorsAndPermission().get(errorMessage);
2578                     boolean hasPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, permission);
2579                     if (!hasPermission) {
2580                         if (errorMessage.equalsIgnoreCase(OLEConstants.GENERAL_BLOCK_MESSAGE)) {
2581                             errorMessage = errorMessage + " " + OLEConstants.SEMI_COLON + " " + oleLoanForm.getDummyLoan().getOlePatron().getGeneralBlockNotes();
2582                         }
2583                         oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2584                                 errorMessage + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + errorMessage + OLEConstants.BREAK);
2585                         overRideFlag = false;
2586                     }
2587                 }
2588             }
2589             if (StringUtils.isNotEmpty(oleLoanForm.getMessage())) {
2590                 if (oleLoanForm.getMessage().contains(OLEConstants.OVERDUE_DAY_LIMIT_ERROR)) {
2591                     boolean hasOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.PATRON_OVERDUE_DAY);
2592                     if (!hasOverdueDayPermission) {
2593                         oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2594                                 OLEConstants.OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK);
2595                         overRideFlag = false;
2596                     }
2597                 }
2598                 if (oleLoanForm.getMessage().contains(OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR)) {
2599                     boolean hasRecalledOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.PATRON_RECALLED_OVERDUE_DAY);
2600                     if (!hasRecalledOverdueDayPermission) {
2601                         oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2602                                 OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK);
2603                         overRideFlag = false;
2604                     }
2605                 }
2606                 if (oleLoanForm.getMessage().contains(OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION)) {
2607                     boolean hasRecalledOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC,OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION);
2608                     if (!hasRecalledOverdueDayPermission) {
2609                         oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2610                                 OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + OLEConstants.BREAK);
2611                         overRideFlag = false;
2612                     }
2613                 }
2614             }
2615         }
2616         return overRideFlag;
2617     }
2618 
2619     public boolean itemValidation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) {
2620         LOG.debug("Inside the itemValidation method");
2621         boolean itemValidation = true;
2622         if (oleItem == null)
2623             return false;
2624         else if ("".equals(oleItem.getItemType()) || oleItem.getItemType() == null)
2625             itemValidation = itemValidation && false;
2626         else if ("".equals(oleItem.getItemStatus()) || oleItem.getItemStatus() == null || validateAndGetItemStatus(oleItem.getItemStatus().getCodeValue()) == null)
2627             itemValidation = itemValidation && false;
2628 
2629         return itemValidation;
2630     }
2631 
2632     public String getItemValidationLocation(LocationLevel oleLocationLevel) {
2633         String location = null;
2634         if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
2635             location = oleLocationLevel.getName();
2636         else
2637             location = getItemValidationLocation(oleLocationLevel.getLocationLevel());
2638         if ("".equals(location) || location == null)
2639             return null;
2640         return location;
2641     }
2642 
2643     public void deletePatronUserNote(String patronId, String patronNoteTypeId) throws Exception {
2644         LOG.debug("Inside the deletePatronUserNote method");
2645         HashMap<String, String> map = new HashMap<String, String>();
2646         map.put(OLEConstants.OlePatron.PATRON_ID, patronId);
2647         map.put(OLEConstants.PATRON_NOTE_TYPE_ID, patronNoteTypeId);
2648         getBusinessObjectService().deleteMatching(OlePatronNotes.class, map);
2649     }
2650 
2651     /**
2652      * Return the loaned Items
2653      *
2654      * @param itemBarcode
2655      * @param oleLoanDocument
2656      * @return OleLoanDocument
2657      */
2658     public OleLoanDocument returnLoan(String itemBarcode, OleLoanDocument oleLoanDocument) throws Exception {
2659         LOG.debug("Inside the returnLoan method");
2660         long begin = System.currentTimeMillis();
2661         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2662 
2663         if (itemBarcode != null && !itemBarcode.isEmpty()) {
2664 
2665             org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
2666             SearchResponse searchResponse = null;
2667             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, itemBarcode), ""));
2668 
2669 
2670             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), OLEConstants.ID));
2671             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.HOLDINGSIDENTIFIER));
2672             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
2673             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.TITLE));
2674             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.AUTHOR));
2675             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Item.LOCATION));
2676             search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.DESTINATION_FIELD_LOCATION_LEVEL_1));
2677             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
2678             if (searchResponse.getSearchResults() != null && searchResponse.getSearchResults().size() > 0) {
2679 
2680                 for (SearchResult searchResult : searchResponse.getSearchResults()) {
2681                     boolean isItemLevelLocationExist = false;
2682                     for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
2683                         String fieldName = searchResultField.getFieldName();
2684                         String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
2685 
2686                         if (fieldName.equalsIgnoreCase(Holdings.HOLDINGSIDENTIFIER) && !fieldValue.isEmpty()) {
2687                             oleLoanDocument.setInstanceUuid(fieldValue);
2688                         } else if (fieldName.equalsIgnoreCase(OLEConstants.ID) && !fieldValue.isEmpty()) {
2689                             oleLoanDocument.setItemUuid(fieldValue);
2690                         } else if (fieldName.equalsIgnoreCase(Bib.BIBIDENTIFIER) && !fieldValue.isEmpty()) {
2691                             oleLoanDocument.setBibUuid(fieldValue);
2692                         } else if (fieldName.equalsIgnoreCase(Bib.TITLE) && !fieldValue.isEmpty()) {
2693                             oleLoanDocument.setTitle(fieldValue);
2694                         } else if (fieldName.equalsIgnoreCase(Bib.AUTHOR) && !fieldValue.isEmpty()) {
2695                             oleLoanDocument.setAuthor(fieldValue);
2696                         } else if (fieldName.equalsIgnoreCase(Item.LOCATION) && !fieldValue.isEmpty()) {
2697                             isItemLevelLocationExist = true;
2698                             oleLoanDocument.setLocation(fieldValue);
2699                         } else if (fieldName.equalsIgnoreCase(Holdings.DESTINATION_FIELD_LOCATION_LEVEL_1) && !fieldValue.isEmpty()) {
2700                             if (!isItemLevelLocationExist) {
2701                                 oleLoanDocument.setLocation(fieldValue);
2702                             }
2703                         }
2704 
2705                     }
2706                 }
2707             } else {
2708                 throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
2709             }
2710 
2711 
2712         } else {
2713             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2714 
2715 
2716             oleLoanDocument.setBibUuid(item.getHolding().getBib().getId());
2717             oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
2718             oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
2719 
2720             oleLoanDocument.setInstanceUuid(item.getHolding().getId());
2721             oleLoanDocument.setItemUuid(item.getId());
2722             oleLoanDocument.setItemLocation(item.getLocation());
2723         }
2724 
2725 
2726         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = null;
2727         String itemXml = null;
2728         if(item.getContent()==null){
2729             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2730         }
2731         itemXml = item.getContent()!=null ? item.getContent() : getItemXML(oleLoanDocument.getItemUuid());
2732 
2733         oleItem = getItemPojo(itemXml);
2734         OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
2735         boolean itemValidation = itemValidation(oleItem);
2736         if (!itemValidation)
2737             throw new Exception(OLEConstants.INVAL_ITEM);
2738         oleLoanDocument.setOleItem(oleItem);
2739         try {
2740             if(oleItem.getCallNumber()!=null && !StringUtils.isEmpty(oleItem.getCallNumber().getNumber())){
2741                 oleLoanDocument.setItemCallNumber(oleItem.getCallNumber().getNumber());
2742             }else {
2743                 oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
2744             }
2745             getCopyNumber(oleItem,oleHoldings,oleLoanDocument);
2746             oleLoanDocument.setEnumeration(oleItem.getEnumeration());
2747             oleLoanDocument.setChronology(oleItem.getChronology());
2748             String status = oleItem.getItemStatus().getCodeValue();
2749             oleLoanDocument.setItemLoanStatus(status);
2750             oleLoanDocument.setItemPrice(new BigDecimal(oleItem.getPrice() != null && !oleItem.getPrice().isEmpty() ? oleItem.getPrice() : OLEConstants.ZERO));
2751         } catch (Exception e) {
2752             LOG.error("Exception", e);
2753             if (oleLoanDocument.isRenewalItemFlag()) {
2754                 oleLoanDocument.setErrorMessage(OLEConstants.ITM_STS_NT_AVAL);
2755                 return oleLoanDocument;
2756             } else
2757                 throw new Exception(OLEConstants.ITM_STS_NT_AVAL);
2758         }
2759         /*if(oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.NOT_CHECK_OUT_STATUS)){
2760             throw new Exception(OLEConstants.ITM_CHECKIN_MSG);
2761         }*/
2762         oleLoanDocument.setItemId(itemBarcode);
2763         if (oleItem.getTemporaryItemType() != null && oleItem.getTemporaryItemType().getCodeValue() != "") {
2764             OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(oleItem.getTemporaryItemType().getCodeValue());
2765             oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
2766             oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2767         }
2768         else if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
2769             OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
2770             oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
2771             oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2772         }
2773         getLocation(oleItem, oleLoanDocument,item);
2774         if (oleLoanDocument.getLocation() == null || (oleLoanDocument.getLocation() != null && oleLoanDocument.getLocation().equalsIgnoreCase(""))) {
2775             getDefaultHoldingLocation(oleLoanDocument);
2776         }
2777         if (oleLoanDocument.getOleLocation() != null && oleLoanDocument.getOleLocation().getLocationId() != null) {
2778             Map<String, String> map = new HashMap<String, String>();
2779             map.put("parentLocationId", oleLoanDocument.getOleLocation().getLocationId());
2780             map.put("locationCode", oleLoanDocument.getItemLocation());
2781             List<OleLocation> oleLocations = (List<OleLocation>) getBusinessObjectService().findMatching(OleLocation.class, map);
2782             oleLoanDocument.setLocationId(oleLocations != null && oleLocations.size() > 0 ? oleLocations.get(0).getLocationId() : oleLoanDocument.getOleLocation().getLocationId());
2783         }
2784         OleCirculationDesk oleCirculationDesk = null;
2785         if (oleLoanDocument.getCirculationLocationId() != null) {
2786             oleCirculationDesk = getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2787             oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
2788         }
2789         OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
2790         /*Removed for the jira -4139 Damaged Checkin option from return view screen */
2791         /*if (oleLoanDocument.isDamagedCheckInOption()) {
2792             updateItemStatus(oleItem, OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2793             OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2794             oleLoanDocument.setItemStatus(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusName() : null);
2795             oleLoanDocument.setItemStatusCode(OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2796             oleLoanDocument.setRouteToLocation(getCirculationDeskDefaultValue(oleLoanDocument.getLocationId()));
2797             oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo != null ? oleDeliverRequestBo : null);
2798             return oleLoanDocument;
2799         }*/
2800         oleLoanDocument.setItemDamagedStatus(oleItem.isItemDamagedStatus());
2801         if (!oleLoanDocument.isSkipDamagedCheckIn()) {
2802             if (oleLoanDocument.isItemDamagedStatus()) {
2803                 return oleLoanDocument;
2804             }
2805         }
2806         List<OleLocation> oleLocations = new ArrayList<OleLocation>();
2807         if (oleCirculationDesk.getOleCirculationDeskLocations() != null) {
2808             for (OleCirculationDeskLocation oleCirculationDeskLocation : oleCirculationDesk.getOleCirculationDeskLocations()) {
2809                 oleLocations.add(oleCirculationDeskLocation.getLocation());
2810             }
2811         } else {
2812             throw new Exception(OLEConstants.NO_LOC_CIR_DESK);
2813         }
2814         StringBuffer location = new StringBuffer();
2815         for (OleLocation oleLocation : oleLocations) {
2816             String operatorsCirculationLocation = getFullPathLocation(oleLocation);
2817             location.append(operatorsCirculationLocation).append(OLEConstants.DELIMITER_HASH);
2818         }
2819         String operatorsCirculationLocation = location.toString();
2820         if (LOG.isDebugEnabled()){
2821             LOG.debug("operatorsCirculationLocation---->" + operatorsCirculationLocation);
2822         }
2823         String shelvingLagTime = oleCirculationDesk.getShelvingLagTime() != null ? oleCirculationDesk.getShelvingLagTime() : getParameter(OLEConstants.SHELVING_LAG_TIME);
2824         Integer shelvingLagTimInt = new Integer(shelvingLagTime.isEmpty() ? OLEConstants.ZERO : shelvingLagTime);
2825         oleLoanDocument.setOperatorsCirculationLocation(operatorsCirculationLocation);
2826         String digitRoutine = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE);
2827         String pattern = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE_PATTERN);
2828         String agendaName = OLEConstants.CHECK_IN_AGENDA_NM;
2829         HashMap<String, Object> termValues = new HashMap<String, Object>();
2830         termValues.put(OLEConstants.SHEL_LAG_TIME, shelvingLagTimInt);
2831         StringBuffer failures = new StringBuffer();
2832         EngineResults engineResults = null;
2833         String requestType = null;
2834         OlePatronDocument oleRequestPatron = null;
2835 
2836         if (oleDeliverRequestBo != null) {
2837             oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo);
2838             requestType = oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode();
2839             oleRequestPatron = getOlePatronDocument(oleDeliverRequestBo.getBorrowerId());
2840             OleCirculationDesk pickUpCircDesk = oleDeliverRequestBo.getPickUpLocationId() != null ? getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId()) : null;
2841             String pickUpLocationFullPath = circulationDeskLocations(pickUpCircDesk);
2842             OleCirculationDesk destinationCircDesk = oleDeliverRequestBo.getCirculationLocationId() != null ? getOleCirculationDesk(oleDeliverRequestBo.getCirculationLocationId()) : null;
2843             String destinationLocationFullPath = circulationDeskLocations(destinationCircDesk);
2844             termValues.put(OLEConstants.ITEM_PICKUP_LOCATION, pickUpLocationFullPath);
2845             termValues.put(OLEConstants.DESTINATION_LOCATION, destinationLocationFullPath);
2846             termValues.put(OLEConstants.REQUEST_TYPE, requestType);
2847             if (pickUpCircDesk != null) {
2848                 oleLoanDocument.setRouteToLocation(pickUpCircDesk.getCirculationDeskCode());
2849                 oleLoanDocument.setRouteToLocationName(pickUpCircDesk.getCirculationDeskPublicName());
2850             } else if (destinationCircDesk != null) {
2851                 oleLoanDocument.setRouteToLocation(destinationCircDesk.getCirculationDeskCode());
2852                 oleLoanDocument.setRouteToLocationName(destinationCircDesk.getCirculationDeskPublicName());
2853             } else {
2854                 // oleLoanDocument.setRouteToLocation(oleCirculationDesk!=null?oleCirculationDesk.getCirculationDeskCode():null);
2855                 oleLoanDocument.setRouteToLocation(oleLoanDocument.getLocationCode());
2856             }
2857             oleLoanDocument.setOleRequestPatron(oleRequestPatron);
2858         } else {
2859             //oleLoanDocument.setRouteToLocation(oleCirculationDesk!=null?oleCirculationDesk.getCirculationDeskCode():null);
2860             oleLoanDocument.setRouteToLocation(oleLoanDocument.getLocationCode());
2861         }
2862         termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
2863         termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
2864         termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
2865         termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
2866         termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
2867         termValues.put(OLEConstants.OleDeliverRequest.CLAIMS_RETURNED_FLAG, oleItem.isClaimsReturnedFlag());
2868         termValues.put(OLEConstants.REPLACEMENT_FEE_EXIST, oleLoanDocument.isReplacementFeeExist());
2869         String itemFullPathLocation = getFullPathLocation(getLocationByLocationCode(oleLoanDocument.getItemLocation()));
2870         oleLoanDocument.setItemFullPathLocation(itemFullPathLocation);
2871         String patronId = oleLoanDocument.getPatronId()!=null ?  oleLoanDocument.getPatronId() : "";
2872         String itemId = oleLoanDocument.getItemId()!=null ?  oleLoanDocument.getItemId() : "";
2873         termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
2874         termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
2875         if (oleLoanDocument.getOlePatron() == null) {
2876             getDataCarrierService().addData(patronId+itemId, true);
2877             termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
2878             termValues.put(OLEConstants.ITEM_LOCATION, itemFullPathLocation);
2879             termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
2880             termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());
2881             termValues.put(OLEConstants.IS_ITEM_PRICE, oleLoanDocument.getItemPrice().compareTo(OLEConstants.BIGDECIMAL_DEF_VALUE) <= 0 ? OLEConstants.TRUE : OLEConstants.FALSE);
2882             termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
2883             termValues.put(OLEConstants.PATTERN, pattern);
2884             engineResults = getEngineResults(agendaName, termValues);
2885         } else {
2886             getDataCarrierService().removeData(patronId+itemId);
2887             getDataCarrierService().addData(OLEConstants.HOURS_DIFF, getOleCirculationPolicyService().getHoursDiff(oleLoanDocument.getLoanDueDate(), oleLoanDocument.getCheckInDate()));
2888             getDataCarrierService().addData("DUEDATE", oleLoanDocument.getLoanDueDate());
2889             getDataCarrierService().addData("CHECKINDATE", oleLoanDocument.getCheckInDate());
2890             termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
2891             termValues.put(OLEConstants.BORROWER_TYPE, oleLoanDocument.getBorrowerTypeCode());
2892             termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemTypeName());
2893             termValues.put(OLEConstants.ITEM_LOCATION, itemFullPathLocation);
2894             termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
2895             termValues.put(OLEConstants.ITEMS_DUE_DATE, oleLoanDocument.getLoanDueDate());
2896             termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());
2897             termValues.put(OLEConstants.DELIVERY_PRIVILEGES, oleLoanDocument.getOlePatron().isDeliveryPrivilege() ? OLEConstants.TRUE : OLEConstants.FALSE);
2898             termValues.put(OLEConstants.IS_ITEM_PRICE, oleLoanDocument.getItemPrice().compareTo(OLEConstants.BIGDECIMAL_DEF_VALUE) <= 0 ? OLEConstants.TRUE : OLEConstants.FALSE);
2899             termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
2900             termValues.put(OLEConstants.PATTERN, pattern);
2901             engineResults = getEngineResults(agendaName, termValues);
2902             BigDecimal fineRate = (BigDecimal) engineResults.getAttribute(OLEConstants.FINE_RATE);
2903             Boolean checkOut = (Boolean) engineResults.getAttribute(OLEConstants.CHECKOUT);
2904             BigDecimal maxFine = (BigDecimal) engineResults.getAttribute(OLEConstants.MAX_FINE);
2905             oleLoanDocument.setFineRate(maxFine != null ? maxFine : fineRate);
2906             oleLoanDocument.setCheckOut(checkOut != null ? checkOut : false);
2907         }
2908         getDataCarrierService().removeData(patronId+itemId);
2909         HashMap<String, String> errorsAndPermission = new HashMap<>();
2910         errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
2911         PermissionService service = KimApiServiceLocator.getPermissionService();
2912         int i = 1;
2913         if (errorsAndPermission != null) {
2914             Set<String> errorMessage = errorsAndPermission.keySet();
2915             if (errorMessage != null && errorMessage.size() > 0) {
2916                 for (String errMsg : errorMessage) {
2917                     if (StringUtils.isNotEmpty(errMsg)) {
2918                         oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
2919                         if (errorMessage != null && errorMessage.size() > 0) {
2920                             for (String errorMsg : errorMessage) {
2921                                 failures.append(i++ + ". " + errorMsg + OLEConstants.BREAK);
2922                             }
2923                         }
2924                     }
2925                 }
2926             }
2927             errorsAndPermission.clear();
2928         }
2929         List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
2930         String itemStatusCode = (String) engineResults.getAttribute(OLEConstants.ITEM_STATUS);
2931         BigDecimal replacementBill = (BigDecimal) engineResults.getAttribute(OLEConstants.REPLACEMENT_BILL);
2932         oleLoanDocument.setReplacementBill(replacementBill);
2933         if (itemStatusCode != null) {
2934             oleLoanDocument.setItemStatusCode(itemStatusCode);
2935         }
2936         if (errorMessage != null && errorMessage.size() > 0) {
2937             for (String errMsg : errorMessage) {
2938                 failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
2939             }
2940         }
2941         getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
2942         getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
2943         boolean returnLoan = false;
2944         if (!failures.toString().isEmpty()) {
2945             oleLoanDocument.setErrorMessage(failures.toString());
2946             returnLoan = true;
2947         }
2948         if (requestType != null && requestType.equalsIgnoreCase(OLEConstants.COPY_REQUEST)) {
2949             oleLoanDocument.setCopyRequest(true);
2950             returnLoan = true;
2951         }
2952         if (returnLoan) {
2953             return oleLoanDocument;
2954 
2955         }
2956         oleLoanDocument = returnLoan(oleLoanDocument);
2957         long end = System.currentTimeMillis();
2958         long total = end - begin;
2959         LOG.info("Time taken Inside returnloan"+total);
2960         return oleLoanDocument;
2961     }
2962 
2963     public OleDeliverRequestBo getPrioritizedRequest(String itemUuid) {
2964         LOG.debug("Inside the getPrioritizedRequest method");
2965         Map requestMap = new HashMap();
2966         requestMap.put("itemUuid", itemUuid);
2967         requestMap.put("borrowerQueuePosition", 1);
2968         List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2969         return oleDeliverRequestBos != null && oleDeliverRequestBos.size() > 0 ? oleDeliverRequestBos.get(0) : null;
2970     }
2971 
2972     public OleDeliverRequestBo getCurrentQueue(String patronid, String itemUuid) throws Exception {
2973         LOG.debug("Inside the getCurrentQueue method");
2974         Map requestMap = new HashMap();
2975         requestMap.put("borrowerId", patronid);
2976         requestMap.put("itemUuid", itemUuid);
2977         List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2978         return oleDeliverRequestBos != null && oleDeliverRequestBos.size() > 0 ? oleDeliverRequestBos.get(0) : null;
2979     }
2980 
2981     public OleCirculationDesk getOleCirculationDesk(String id) {
2982         LOG.debug("Inside the getOleCirculationDesk method");
2983         OleCirculationDesk oleCirculationDesk = getBusinessObjectService().findBySinglePrimaryKey(OleCirculationDesk.class, id);
2984         return oleCirculationDesk;
2985     }
2986 
2987     public String generatePatronBillPayment(OleLoanDocument oleLoanDocument, String feeTypeName, BigDecimal fineAmount) {
2988         long begin = System.currentTimeMillis();
2989         StringBuffer contentForSendMail = new StringBuffer();
2990         LOG.debug("Inside the generatePatronBillPayment method");
2991         // OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
2992         //   EntityNameBo nameBo = olePatronDocument.getEntity().getNames().get(0);
2993         PatronBillPayment patronBillPayment;
2994         OlePaymentStatus olePaymentStatus = getPaymentStatus();
2995         FeeType feeType = new FeeType();
2996         feeType.setFeeType(getFeeTypeId(feeTypeName));
2997         feeType.setFeeAmount(new KualiDecimal(fineAmount));
2998         feeType.setItemBarcode(oleLoanDocument.getItemId());
2999         feeType.setItemType(oleLoanDocument.getItemTypeName());
3000         feeType.setItemTitle(oleLoanDocument.getTitle());
3001         feeType.setItemUuid(oleLoanDocument.getItemUuid());
3002         feeType.setPaymentStatus(olePaymentStatus.getPaymentStatusId());
3003         feeType.setBalFeeAmount(new KualiDecimal(fineAmount));
3004         feeType.setFeeSource(OLEConstants.SYSTEM);
3005         feeType.setDueDate(oleLoanDocument.getLoanDueDate());
3006         feeType.setCheckInDate(oleLoanDocument.getCheckInDate());
3007         feeType.setCheckOutDate(oleLoanDocument.getCreateDate());
3008         List<FeeType> feeTypes = new ArrayList<FeeType>();
3009         feeTypes.add(feeType);
3010         Date billdate = new Date();
3011        /* patronBillPayment = getPatronBillPayment(oleLoanDocument.getPatronId());
3012         if (patronBillPayment != null) {
3013             feeTypes.addAll(patronBillPayment.getFeeType());
3014             patronBillPayment.setFeeType(feeTypes);
3015             patronBillPayment.setBillDate(oleLoanDocument.getCheckInDate() != null ? new java.sql.Date(oleLoanDocument.getCheckInDate().getTime()) : new java.sql.Date(billdate.getTime()));
3016             patronBillPayment.setTotalAmount(patronBillPayment.getTotalAmount().add(fineAmount));
3017             patronBillPayment.setUnPaidBalance(patronBillPayment.getUnPaidBalance().add(fineAmount));
3018             patronBillPayment.setOlePatron(null);  // Set null to resolve  org.kuali.rice.core.api.util.cache.CacheException: unable to complete deepCopy from src 'org.kuali.ole.deliver.bo.PatronBillPayment' JIRA OLE-4364
3019 
3020 
3021         } else {*/
3022         patronBillPayment = new PatronBillPayment();
3023         patronBillPayment.setBillDate(oleLoanDocument.getCheckInDate() != null ? new java.sql.Date(oleLoanDocument.getCheckInDate().getTime()) : new java.sql.Date(billdate.getTime()));
3024         patronBillPayment.setFeeType(feeTypes);
3025         //patronBillPayment.setMachineId(oleLoanDocument.getMachineId());  //commented for jira OLE-5675
3026         patronBillPayment.setPatronId(oleLoanDocument.getPatronId());
3027         patronBillPayment.setProxyPatronId(oleLoanDocument.getProxyPatronId());
3028         patronBillPayment.setTotalAmount(new KualiDecimal(fineAmount));
3029         patronBillPayment.setUnPaidBalance(new KualiDecimal(fineAmount));
3030 
3031        /* }*/
3032 
3033         PatronBillPayment patronBillPayments = getBusinessObjectService().save(patronBillPayment);
3034 
3035         Map<String, String> patronMap = new HashMap<String, String>();
3036         BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
3037         patronMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
3038         List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
3039         OlePatronDocument olePatronDocument = olePatronDocumentList.get(0);
3040         String patronMail = "";
3041         try {
3042             patronMail = getOleDeliverRequestDocumentHelperService().getPatronHomeEmailId(olePatronDocument.getEntity().getEntityTypeContactInfos().get(0));
3043         } catch (Exception e) {
3044             LOG.error("Ecxeption while getting patron home mail id", e);
3045         }
3046         OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
3047         contentForSendMail.append(oleDeliverBatchService.generateMailContentFromPatronBill(oleLoanDocument, olePatronDocument, feeTypeName, String.valueOf(fineAmount), patronBillPayment));
3048         OleMailer oleMail = GlobalResourceLoader.getService("oleMailer");
3049         oleMail.sendEmail(new EmailFrom(getParameter(OLEParameterConstants.NOTICE_FROM_MAIL)), new EmailTo(patronMail), new EmailSubject(feeTypeName), new EmailBody(contentForSendMail.toString()), true);
3050         if (LOG.isInfoEnabled()){
3051             LOG.info("Mail send successfully to " + patronMail);
3052         }
3053         String billNumber = patronBillPayments.getBillNumber();
3054         long end = System.currentTimeMillis();
3055         long total = end - begin;
3056         LOG.info("Time taken Inside generatePatronBillPayment"+total);
3057         return billNumber;
3058     }
3059 
3060     private PatronBillPayment getPatronBillPayment(String patronId) {
3061         LOG.debug("Inside the getPatronBillPayment method");
3062         Map billMap = new HashMap();
3063         billMap.put("patronId", patronId);
3064         List<PatronBillPayment> patronBillPaymentList = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, billMap);
3065         return patronBillPaymentList != null && patronBillPaymentList.size() > 0 ? patronBillPaymentList.get(0) : null;
3066     }
3067 
3068     private OlePaymentStatus getPaymentStatus() {
3069         LOG.debug("Inside the getPaymentStatus method");
3070         Map statusMap = new HashMap();
3071         statusMap.put("paymentStatusName", OLEConstants.PAYMENT_STATUS_OUTSTANDING);
3072         List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
3073         return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
3074     }
3075 
3076     private String getFeeTypeId(String feeTypeName) {
3077         LOG.debug("Inside the getOverdueFeeTypeId method");
3078         Map feeMap = new HashMap();
3079         feeMap.put("feeTypeName", feeTypeName);
3080         List<OleFeeType> oleFeeTypes = (List<OleFeeType>) getBusinessObjectService().findMatching(OleFeeType.class, feeMap);
3081         return oleFeeTypes != null && oleFeeTypes.size() > 0 ? oleFeeTypes.get(0).getFeeTypeId() : null;
3082     }
3083 
3084     public OleLoanDocument returnLoan(OleLoanDocument oleLoanDocument) throws Exception {
3085         LOG.debug("Inside the returnLoan method");
3086         long begin = System.currentTimeMillis();
3087         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = oleLoanDocument.getOleItem();
3088         OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
3089         OlePatronDocument oleRequestPatron = oleLoanDocument.getOleRequestPatron();
3090         String circulationLocationId = oleLoanDocument.getCirculationLocationId();
3091         Integer numberOfPieces = Integer.parseInt(oleItem != null && oleItem.getNumberOfPieces() != null && !oleItem.getNumberOfPieces().isEmpty() ? oleItem.getNumberOfPieces() : "0");
3092         if (!oleLoanDocument.isContinueCheckIn() && numberOfPieces > 1) {
3093             oleLoanDocument.setItemNumberOfPieces(numberOfPieces);
3094             oleLoanDocument.setNumberOfPieces(true);
3095             return oleLoanDocument;
3096         }
3097         if (oleLoanDocument.getFineRate() != null && oleLoanDocument.getFineRate().compareTo(BigDecimal.ZERO) > 0) {
3098             generatePatronBillPayment(oleLoanDocument, OLEConstants.OVERDUE_FINE, oleLoanDocument.getFineRate());
3099             oleLoanDocument.setBillName(oleLoanDocument.getFineRate().toString());
3100             updateReplacementFeeBill(oleLoanDocument);
3101         }
3102         if (oleLoanDocument.getReplacementBill() != null && oleLoanDocument.getFineRate() != null && oleLoanDocument.getFineRate().compareTo(BigDecimal.ZERO) > 0) {
3103             generatePatronBillPayment(oleLoanDocument, OLEConstants.REPLACEMENT_FEE, oleLoanDocument.getReplacementBill());
3104             BigDecimal fineRate = oleLoanDocument.getFineRate() != null ? oleLoanDocument.getFineRate() : OLEConstants.BIGDECIMAL_DEF_VALUE;
3105             oleLoanDocument.setBillName(oleLoanDocument.getReplacementBill().add(fineRate).toString());
3106             if (oleItem.isStaffOnlyFlag()) {
3107                 oleItem.setStaffOnlyFlag(false);
3108             }
3109         }
3110         if (oleLoanDocument.getRepaymentFeePatronBillId() != null) {
3111             if (oleItem.isStaffOnlyFlag()) {
3112                 oleItem.setStaffOnlyFlag(false);
3113             }
3114             oleLoanDocument.setBillName(OLEConstants.REPLACEMENT_FEE);
3115         }
3116         if (oleLoanDocument.getItemStatusCode() != null) {
3117             incrementNumberOfCirculations(oleLoanDocument);
3118             oleItem.setCurrentBorrower(null);
3119             oleItem.setDueDateTime(null);
3120             oleItem.setCheckOutDateTime(null);
3121             updateItemStatus(oleItem, oleLoanDocument.getItemStatusCode());
3122             //updateMissingPiecesItemInfo(oleLoanDocument);
3123             OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(oleLoanDocument.getItemStatusCode());
3124             oleLoanDocument.setItemStatus(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusName() : null);
3125         }
3126         if (olePatronDocument != null) {
3127             createCirculationHistoryAndTemporaryHistoryRecords(oleLoanDocument);
3128             getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
3129             getBusinessObjectService().delete(oleLoanDocument);
3130         }
3131         OleDeliverRequestBo oleDeliverRequestBo = oleLoanDocument.getOleDeliverRequestBo();
3132         OleLoanDocument checkOutLoanDocument;
3133         if (oleLoanDocument.isCheckOut()) {
3134             checkOutLoanDocument = checkOutItem(oleRequestPatron, oleItem, circulationLocationId, oleLoanDocument.getCheckInDate(), oleDeliverRequestBo);
3135             checkOutLoanDocument.setCheckOut(true);
3136             checkOutLoanDocument.setBackGroundCheckOut(true);
3137             checkOutLoanDocument.setRouteToLocation(oleLoanDocument.getRouteToLocation());
3138             checkOutLoanDocument.setOleCirculationDesk(oleLoanDocument.getOleCirculationDesk());
3139             return checkOutLoanDocument;
3140         }
3141         if (oleLoanDocument.getItemStatusCode() != null && oleLoanDocument.getItemStatusCode().equalsIgnoreCase(OLEConstants.RECENTLY_RETURNED)) {
3142             createOrUpdateRecentlyReturnedRecord(oleLoanDocument.getItemUuid(), oleLoanDocument.getOleCirculationDesk().getCirculationDeskId());
3143         }
3144         long end = System.currentTimeMillis();
3145         long total = end - begin;
3146         LOG.info("Time taken Inside inner returnloan"+total);
3147         return oleLoanDocument;
3148     }
3149 
3150     private void createOrUpdateRecentlyReturnedRecord(String itemUUID, String circulationDeskId) {
3151         HashMap<String, String> map = new HashMap<String, String>();
3152         map.put("itemUuid", itemUUID);
3153         OleRecentlyReturned oleRecentlyReturned = getBusinessObjectService().findByPrimaryKey(OleRecentlyReturned.class, map);
3154         if (oleRecentlyReturned != null) {
3155             oleRecentlyReturned.setCirculationDeskId(circulationDeskId);
3156         } else {
3157             oleRecentlyReturned = new OleRecentlyReturned();
3158             oleRecentlyReturned.setCirculationDeskId(circulationDeskId);
3159             oleRecentlyReturned.setItemUuid(itemUUID);
3160         }
3161         getBusinessObjectService().save(oleRecentlyReturned);
3162     }
3163 
3164     public void incrementNumberOfCirculations(OleLoanDocument oleLoanDocument) {
3165         org.kuali.ole.docstore.common.document.content.instance.Item item = oleLoanDocument.getOleItem();
3166         NumberOfCirculations numberOfCirculations = item.getNumberOfCirculations();
3167         if (numberOfCirculations == null) {
3168             numberOfCirculations = new NumberOfCirculations();
3169             numberOfCirculations.setCheckInLocation(new ArrayList<CheckInLocation>());
3170         }
3171         List<CheckInLocation> checkInLocations = numberOfCirculations.getCheckInLocation();
3172         CheckInLocation checkInLocation = null;
3173         int count = 1;
3174         for (CheckInLocation checkInLoc : checkInLocations) {
3175             if (checkInLoc.getName().equals(oleLoanDocument.getItemFullPathLocation())) {
3176                 if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty()) {
3177                     if (checkInLoc.getInHouseCount() != null) {
3178                         if (oleLoanDocument.getItemStatusCode().equals("INTRANSIT") || oleLoanDocument.getItemStatusCode().equals("INTRANSIT-FOR-HOLD") || oleLoanDocument.getItemStatusCode().equals("INTRANSIT-PER-STAFF-REQUEST")) {
3179                             count = checkInLoc.getInHouseCount();
3180                         } else {
3181                             count = checkInLoc.getInHouseCount() + 1;
3182                         }
3183                     }
3184                 } else {
3185                     if (checkInLoc.getCount() != null) {
3186                         count = checkInLoc.getCount() + 1;
3187                     }
3188                 }
3189                 checkInLocation = checkInLoc;
3190                 break;
3191             }
3192         }
3193         if (checkInLocation == null) {
3194             checkInLocation = new CheckInLocation();
3195             checkInLocation.setName(oleLoanDocument.getItemFullPathLocation());
3196             if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty())
3197                 checkInLocation.setInHouseCount(count);
3198             else
3199                 checkInLocation.setCount(count);
3200             checkInLocations.add(checkInLocation);
3201         } else {
3202             if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty())
3203                 checkInLocation.setInHouseCount(count);
3204             else
3205                 checkInLocation.setCount(count);
3206         }
3207         if (item.getNumberOfCirculations() != null) {
3208             oleLoanDocument.getOleItem().getNumberOfCirculations().setCheckInLocation(checkInLocations);
3209         } else {
3210             numberOfCirculations.setCheckInLocation(checkInLocations);
3211             oleLoanDocument.getOleItem().setNumberOfCirculations(numberOfCirculations);
3212         }
3213 
3214     }
3215 
3216     private OleLoanDocument checkOutItem(OlePatronDocument olePatronDocument, org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String circulationLocationId, Timestamp checkInDate, OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
3217         long begin = System.currentTimeMillis();
3218         LOG.debug("Inside the checkOutItem method");
3219         OleLoanDocument oleLoanDocument = new OleLoanDocument();
3220         oleLoanDocument.setOlePatron(olePatronDocument);
3221         oleLoanDocument.setPatronId(olePatronDocument.getOlePatronId());
3222         oleLoanDocument.setCirculationLocationId(circulationLocationId);
3223         oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3224         oleLoanDocument.setBorrowerTypeName(olePatronDocument.getBorrowerTypeName());
3225         oleLoanDocument.setBorrowerTypeCode(olePatronDocument.getBorrowerTypeCode());
3226         addLoan(olePatronDocument.getBarcode(), oleItem.getAccessInformation().getBarcode(), oleLoanDocument,null);
3227         //  deleteRequestRecord(oleDeliverRequestBo);
3228         OleItemAvailableStatus oleItemAvailableStatus = validateAndGetItemStatus(oleLoanDocument.getOleItem().getItemStatus().getCodeValue());
3229         oleLoanDocument.setItemStatus(oleItemAvailableStatus != null ? oleItemAvailableStatus.getItemAvailableStatusName() : null);
3230         oleLoanDocument.setItemStatusCode(oleLoanDocument.getOleItem().getItemStatus().getCodeValue());
3231         oleLoanDocument.setCheckInDate(checkInDate);
3232         long end = System.currentTimeMillis();
3233         long total = end - begin;
3234         LOG.info("Time taken Inside checkOutItem"+total);
3235         return oleLoanDocument;
3236     }
3237 
3238     public void deleteRequestRecord(OleDeliverRequestBo oleDeliverRequestBo) {
3239         getOleDeliverRequestDocumentHelperService().cancelDocument(oleDeliverRequestBo);
3240     }
3241 
3242     public void createCirculationHistoryAndTemporaryHistoryRecords(OleLoanDocument oleLoanDocument) {
3243         LOG.debug("Inside the createCirculationHistoryAndTemporaryHistoryRecords method");
3244         OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
3245         OleCirculationHistory oleCirculationHistory = new OleCirculationHistory();
3246         oleCirculationHistory.setLoanId(oleLoanDocument.getLoanId());
3247         oleCirculationHistory.setCirculationPolicyId(oleLoanDocument.getCirculationPolicyId());
3248         oleCirculationHistory.setBibAuthor(oleLoanDocument.getAuthor());
3249         oleCirculationHistory.setBibTitle(oleLoanDocument.getTitle());
3250         oleCirculationHistory.setCheckInDate(oleLoanDocument.getCheckInDate() != null ? oleLoanDocument.getCheckInDate() : new Timestamp(System.currentTimeMillis()));
3251         //oleCirculationHistory.setCheckInMachineId(oleLoanDocument.getMachineId());  //commented for jira OLE-5675
3252         oleCirculationHistory.setCreateDate(oleLoanDocument.getCreateDate());
3253         oleCirculationHistory.setCirculationLocationId(oleLoanDocument.getCirculationLocationId());
3254         oleCirculationHistory.setDueDate(oleLoanDocument.getLoanDueDate());
3255         oleCirculationHistory.setItemId(oleLoanDocument.getItemId());
3256         //oleCirculationHistory.setMachineId(oleLoanDocument.getMachineId());      //commented for jira OLE-5675
3257         oleCirculationHistory.setNumberOfOverdueNoticesSent(oleLoanDocument.getNumberOfOverdueNoticesSent());
3258         oleCirculationHistory.setNumberOfRenewals(oleLoanDocument.getNumberOfRenewals());
3259         oleCirculationHistory.setStatisticalCategory(olePatronDocument.getStatisticalCategory());
3260         oleCirculationHistory.setRepaymentFeePatronBillId(oleLoanDocument.getRepaymentFeePatronBillId());
3261         oleCirculationHistory.setProxyPatronId(olePatronDocument.getProxyPatronId());
3262         oleCirculationHistory.setPatronTypeId(oleLoanDocument.getBorrowerTypeId());
3263         oleCirculationHistory.setPatronId(oleLoanDocument.getPatronId());
3264         oleCirculationHistory.setPastDueDate(oleLoanDocument.getPastDueDate());
3265         oleCirculationHistory.setOverdueNoticeDate(oleLoanDocument.getOverDueNoticeDate());
3266         oleCirculationHistory.setOleRequestId(oleLoanDocument.getOleRequestId());
3267         oleCirculationHistory.setItemUuid(oleLoanDocument.getItemUuid());
3268         getBusinessObjectService().save(oleCirculationHistory);
3269 
3270         OleTemporaryCirculationHistory oleTemporaryCirculationHistory = new OleTemporaryCirculationHistory();
3271         oleTemporaryCirculationHistory.setCirculationLocationId(oleLoanDocument.getCirculationLocationId());
3272         oleTemporaryCirculationHistory.setOlePatronId(oleLoanDocument.getPatronId());
3273         oleTemporaryCirculationHistory.setItemId(oleLoanDocument.getItemId());
3274         oleTemporaryCirculationHistory.setCheckInDate(oleLoanDocument.getCheckInDate() != null ? oleLoanDocument.getCheckInDate() : new Timestamp(System.currentTimeMillis()));
3275         oleTemporaryCirculationHistory.setItemUuid(oleLoanDocument.getItemUuid());
3276         oleTemporaryCirculationHistory.setDueDate(oleLoanDocument.getLoanDueDate());
3277         oleTemporaryCirculationHistory.setCheckOutDate(oleLoanDocument.getCreateDate());
3278         getBusinessObjectService().save(oleTemporaryCirculationHistory);
3279 
3280     }
3281 
3282     /**
3283      * This method invokes docStore to store item and returns itemRecordUpdateResponse.
3284      *
3285      * @param oleItem
3286      * @param itemStatus
3287      * @throws Exception
3288      */
3289     public void updateItemStatus(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatus) throws Exception {
3290         LOG.debug("Inside the updateItemStatus method");
3291         try {
3292             String itemUuid = oleItem.getItemIdentifier();
3293             String itemXmlContent = buildItemContentWithItemStatus(oleItem, itemStatus);
3294             if (LOG.isDebugEnabled()){
3295                 LOG.debug("itemXmlContent" + itemXmlContent);
3296             }
3297             Item item = new ItemOleml();
3298             item.setId(itemUuid);
3299             item.setContent(itemXmlContent);
3300             item.setCategory(OLEConstants.WORK_CATEGORY);
3301             item.setType(DocType.ITEM.getCode());
3302             item.setFormat(OLEConstants.OLEML_FORMAT);
3303             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
3304         } catch (Exception e) {
3305             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
3306             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
3307         }
3308     }
3309 
3310     /**
3311      * This method invokes docStore to remove check in note and store item.
3312      *
3313      * @param oleItem
3314      * @throws Exception
3315      */
3316     public void removeCheckInNote(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
3317         LOG.debug("Inside the removeCheckInNote method");
3318         try {
3319             String itemUuid = oleItem.getItemIdentifier();
3320             oleItem.setCheckinNote("");
3321             String itemXmlContent = getItemOlemlRecordProcessor().toXML(oleItem);
3322             Item item = new ItemOleml();
3323             item.setId(itemUuid);
3324             item.setContent(itemXmlContent);
3325             item.setCategory(OLEConstants.WORK_CATEGORY);
3326             item.setType(DocType.ITEM.getCode());
3327             item.setFormat(OLEConstants.OLEML_FORMAT);
3328             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
3329         } catch (Exception e) {
3330             LOG.error("removeCheckInNote" + e, e);
3331             throw new Exception("Exception in removeCheckInNote method" + e);
3332         }
3333     }
3334 
3335     /**
3336      * This method creates and return itemContent using OleItem
3337      *
3338      * @param oleItem
3339      * @param itemStatus
3340      * @return String
3341      * @throws Exception
3342      */
3343     public String buildItemContentWithItemStatus(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatus) throws Exception {
3344         LOG.debug("Inside the buildItemContentWithItemStatus method");
3345         ItemStatus itemStatus1 = new ItemStatus();
3346         itemStatus1.setCodeValue(itemStatus);
3347         itemStatus1.setFullValue(itemStatus);
3348         oleItem.setItemStatus(itemStatus1);
3349         oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
3350         String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
3351         return itemContent;
3352     }
3353 
3354     public OleLoanDocument getOleLoanDocumentUsingItemUUID(String itemUuid) {
3355         LOG.debug("Inside the getOleLoanDocumentUsingItemBarcode method");
3356         OleLoanDocument oleLoanDocument = null;
3357         Map barMap = new HashMap();
3358         barMap.put(OLEConstants.ITEM_UUID, itemUuid);
3359         List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
3360         if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3361             oleLoanDocument = oleLoanDocuments.get(0);
3362             barMap = new HashMap();
3363             barMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
3364             OlePatronDocument olePatronDocument = getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, barMap);
3365             oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3366             OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
3367             oleLoanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
3368             oleLoanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
3369             oleLoanDocument.setOlePatron(olePatronDocument);
3370         }
3371         return oleLoanDocument;
3372     }
3373 
3374     public OleLoanDocument getOleLoanDocumentUsingItemBarcode(String itemBarcode) {
3375         LOG.debug("Inside the getOleLoanDocumentUsingItemBarcode method");
3376         OleLoanDocument oleLoanDocument = null;
3377         Map barMap = new HashMap();
3378         barMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemBarcode);
3379         List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
3380         if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3381             oleLoanDocument = oleLoanDocuments.get(0);
3382            /* barMap = new HashMap();
3383             barMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());*/
3384             OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
3385             oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3386             OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
3387             oleLoanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
3388             oleLoanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
3389             oleLoanDocument.setOlePatron(olePatronDocument);
3390         }
3391         return oleLoanDocument;
3392     }
3393 
3394     public OlePatronDocument getOlePatronDocument(String patronId) {
3395         LOG.debug("Inside the getOlePatronDocument method");
3396         Map barMap = new HashMap();
3397         barMap = new HashMap();
3398         barMap.put(OLEConstants.OlePatron.PATRON_ID, patronId);
3399         List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
3400         return olePatronDocumentList != null && olePatronDocumentList.size() > 0 ? olePatronDocumentList.get(0) : null;
3401     }
3402 
3403     public void updateItemStatusWithMissingItem(OleLoanDocument oleLoanDocument) throws Exception {
3404         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = oleLoanDocument.getOleItem();
3405         oleItem.setCheckinNote(oleLoanDocument.getDescription());
3406         updateItemStatus(oleItem, OLEConstants.ITEM_STATUS_RETURNED_MISSING);
3407         OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(OLEConstants.ITEM_STATUS_RETURNED_MISSING);
3408         oleLoanDocument.setItemStatus(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusName() : null);
3409         oleLoanDocument.setItemStatusCode(OLEConstants.ITEM_STATUS_RETURNED_MISSING);
3410     }
3411 
3412     /**
3413      * This method returns PatronLoanedItem using itemId
3414      *
3415      * @param itemId
3416      * @return List
3417      * @throws Exception
3418      */
3419     public OleLoanDocument getPatronRenewalItem(String itemId) throws Exception {
3420         LOG.debug("Inside the getPatronRenewalItem method");
3421         Map itemBarMap = new HashMap();
3422         itemBarMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemId);
3423         List<OleLoanDocument> matchingLoan = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, itemBarMap);
3424         OleLoanDocument oleLoanDocument = matchingLoan.get(0);
3425         setBibInfo(oleLoanDocument);
3426         Map map = new HashMap();
3427         map.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
3428         OlePatronDocument olePatronDocument = (OlePatronDocument) getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, map);
3429         oleLoanDocument.setBorrowerTypeId(olePatronDocument.getOleBorrowerType().getBorrowerTypeId());
3430         oleLoanDocument.setBorrowerTypeName(olePatronDocument.getOleBorrowerType().getBorrowerTypeName());
3431         oleLoanDocument.setBorrowerTypeCode(olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
3432         return oleLoanDocument;
3433     }
3434 
3435     public void setBibInfo(OleLoanDocument oleLoanDocument) throws Exception {
3436         LOG.debug("Inside the setBibInfo method");
3437         String itemUuid = oleLoanDocument.getItemId();
3438         org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
3439         oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
3440         oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
3441         oleLoanDocument.setInstanceUuid(item.getHolding().getId());
3442         oleLoanDocument.setItemUuid(item.getId());
3443         String itemXml = item.getContent()!=null ? item.getContent() : getItemXML(item.getId());
3444         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXml);
3445         OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
3446         if(oleItem.getCallNumber()!=null && !StringUtils.isEmpty(oleItem.getCallNumber().getNumber())){
3447             oleLoanDocument.setItemCallNumber(oleItem.getCallNumber().getNumber());
3448         }else {
3449             oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
3450         }
3451         getLocation(oleItem, oleLoanDocument,item);
3452 
3453     }
3454 
3455     public void updateClaimsReturnedInLoanDocument(OleLoanDocument oleLoanDocument, boolean claimsReturned) {
3456         LOG.debug("Inside the updateClaimsReturnedInLoanDocument method");
3457         oleLoanDocument.setClaimsReturnedIndicator(claimsReturned);
3458         getBusinessObjectService().save(oleLoanDocument);
3459     }
3460 
3461     /**
3462      * This method will return url for view link in patron record.
3463      *
3464      * @return Url
3465      */
3466 
3467     public String getUrl(String patronId) {
3468         String url = "patronbill?viewId=BillView&amp;methodToCall=start&amp;patronId=" + patronId;
3469         return url;
3470     }
3471 
3472     public boolean checkPendingRequestforItem(String itemUUID) {
3473         if (getOleDeliverRequestDocumentHelperService().getOleDeliverRequestBo(itemUUID) != null)
3474             return true;
3475         return false;
3476     }
3477 
3478     public String getParameter(String name) {
3479         ParameterKey parameterKey = ParameterKey.create(OLEConstants.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,name);
3480         Parameter parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
3481         if(parameter==null){
3482             parameterKey = ParameterKey.create(OLEConstants.APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,name);
3483             parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
3484         }
3485         return parameter!=null?parameter.getValue():null;
3486     }
3487 
3488     public OleLoanDocument overrideSaveLoanForRenewal(OleLoanDocument oleLoanDocument) throws Exception {
3489         Date pastDueDate = oleLoanDocument.getLoanDueDate();
3490         oleLoanDocument.setLoanDueDate(oleLoanDocument.getRenewalLoanDueDate());
3491         compareExpirationDateWithDueDate(oleLoanDocument);
3492         if (oleLoanDocument.isRenewalItemFlag()) {
3493             if (oleLoanDocument.getNumberOfRenewals() == null)
3494                 oleLoanDocument.setNumberOfRenewals("0");
3495             String noOfRenewal = "" + (Integer.parseInt(oleLoanDocument.getNumberOfRenewals()) + 1);
3496             if(noOfRenewal!=null && !noOfRenewal.isEmpty()){
3497                 oleLoanDocument.setNumberOfOverdueNoticesSent("0");
3498             }
3499             oleLoanDocument.setNumberOfRenewals(noOfRenewal);
3500             oleLoanDocument.setPastDueDate(pastDueDate);
3501             oleLoanDocument.setRenewalItemFlag(false);
3502             saveLoan(oleLoanDocument);
3503         }
3504         return oleLoanDocument;
3505     }
3506 
3507     /**
3508      * This method returns DefaultCirculationDesk using principleId
3509      *
3510      * @param principleId
3511      * @return OleCirculationDeskDetail
3512      */
3513     public OleCirculationDeskDetail getDefaultCirculationDesk(String principleId) {
3514         LOG.debug("Inside the getDefaultCirculationDesk method");
3515         Map barMap = new HashMap();
3516         barMap.put(OLEConstants.OPTR_ID, principleId);
3517         List<OleCirculationDeskDetail> oleCirculationDeskDetails = (List<OleCirculationDeskDetail>) getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, barMap);
3518         for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3519             if (oleCirculationDeskDetail.isDefaultLocation()) {
3520                 return oleCirculationDeskDetail;
3521             }
3522         }
3523         return null;
3524     }
3525 
3526     public boolean isValidCirculationDesk() {
3527         String value = getCircDesk();
3528         if (value==null) {
3529             return false;
3530         }
3531         circDeskId = value;
3532         return true;
3533     }
3534 
3535     public boolean isAuthorized(String principalId) {
3536         Map<String, String> userMap = new HashMap<String, String>();
3537         userMap.put("operatorId", principalId);
3538         Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalId);
3539         return principal != null;
3540     }
3541 
3542     public List<String> getCircDeskList() {
3543         List<String> circkDesk = new ArrayList<String>();
3544         Map<String, String> userMap = new HashMap<String, String>();
3545         userMap.put("operatorId", GlobalVariables.getUserSession().getPrincipalId());
3546         Collection<OleCirculationDeskDetail> oleCirculationDeskDetails = KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, userMap);
3547 
3548         for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3549             if (oleCirculationDeskDetail.isDefaultLocation() && oleCirculationDeskDetail.getOleCirculationDesk().isActive()) {
3550                 circkDesk.add(oleCirculationDeskDetail.getOleCirculationDesk().getCirculationDeskId());
3551             }
3552         }
3553         for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3554             if (!oleCirculationDeskDetail.isDefaultLocation() && oleCirculationDeskDetail.getOleCirculationDesk().isActive()) {
3555                 circkDesk.add(oleCirculationDeskDetail.getOleCirculationDesk().getCirculationDeskId());
3556             }
3557         }
3558         return circkDesk;
3559     }
3560 
3561     /*public String getErrorMessage() {
3562         String errorMessage = "";
3563         if (getPermissionService().hasPermission(GlobalVariables.getUserSession().getPrincipalId(), OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_OVERRIDE_LOAN) || getPermissionService().hasPermission(GlobalVariables.getUserSession().getPrincipalId(), OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN)) {
3564             errorMessage = GlobalVariables.getUserSession().getPrincipalName() + " " + OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_VALIDATIONS;
3565         } else {
3566             errorMessage = GlobalVariables.getUserSession().getPrincipalName() + " " + OLEConstants.UNAUTHORIZED_LOAN_USER;
3567         }
3568         return errorMessage;
3569     }*/
3570 
3571     public CallNumber getCallNumber(OleLoanFastAdd oleLoanFastAdd) {
3572         CallNumber callNumber = new CallNumber();
3573         callNumber.setNumber(oleLoanFastAdd.getCallNumber());
3574         ShelvingScheme shelvingScheme = new ShelvingScheme();
3575         shelvingScheme.setCodeValue(oleLoanFastAdd.getCallNumberType());
3576         callNumber.setShelvingScheme(shelvingScheme);
3577         return callNumber;
3578     }
3579 
3580     public OleCirculationDesk getCirculationDeskByLocationId(String locationId) {
3581         OleCirculationDeskLocation oleCirculationDeskLocation = getOleCirculationDeskLocationByLocationId(locationId);
3582         if (oleCirculationDeskLocation != null) {
3583             Map<String, String> userMap = new HashMap<String, String>();
3584             userMap.put("circulationDeskId", oleCirculationDeskLocation.getCirculationDeskId());
3585             List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, userMap);
3586             return oleCirculationDesks != null && oleCirculationDesks.size() > 0 ? oleCirculationDesks.get(0) : null;
3587         }
3588         return null;
3589     }
3590 
3591     public OleCirculationDeskLocation getOleCirculationDeskLocationByLocationId(String locationId) {
3592         Map<String, String> locationMap = new HashMap<String, String>();
3593         locationMap.put("circulationDeskLocation", locationId);
3594         List<OleCirculationDeskLocation> oleCirculationDeskLocations = (List<OleCirculationDeskLocation>) getBusinessObjectService().findMatching(OleCirculationDeskLocation.class, locationMap);
3595         return oleCirculationDeskLocations != null && oleCirculationDeskLocations.size() > 0 ? oleCirculationDeskLocations.get(0) : null;
3596     }
3597 
3598     public boolean checkPermissionForRemoveNote(String principalId) {
3599         PermissionService service = KimApiServiceLocator.getPermissionService();
3600         return service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.CAN_REMOVE_NOTE);
3601     }
3602 
3603     public OleNoticeBo getNotice(OleLoanDocument oleLoanDocument) {
3604 
3605         OleLocation oleLocation = null;
3606         OleLoanDocument newLoanDocument;
3607         OleCirculationDesk oleCirculationDesk = null;
3608         Map<String, String> patronMap = new HashMap<String, String>();
3609         patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleLoanDocument.getPatronId());
3610         List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
3611         if (patronDocumentList.size() == 0) {
3612             return null;
3613         }
3614         OlePatronDocument olePatronDocument = patronDocumentList.get(0);
3615         EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
3616 
3617         if (oleLoanDocument.getCirculationLocationId() != null) {
3618             oleCirculationDesk = this.getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
3619             oleLocation = oleCirculationDesk != null ? oleCirculationDesk.getOleCirculationDeskLocations().get(0).getLocation() : null;
3620         }
3621         String locationName = oleLocation != null ? oleLocation.getLocationName() : null;
3622         OleNoticeBo oleNoticeBo = new OleNoticeBo();
3623         oleNoticeBo.setTitle(oleLoanDocument.getTitle() != null ? oleLoanDocument.getTitle() : "");
3624         oleNoticeBo.setAuthor(oleLoanDocument.getAuthor() != null ? oleLoanDocument.getAuthor() : "");
3625         oleNoticeBo.setItemId(oleLoanDocument.getItemId() != null ? oleLoanDocument.getItemId() : "");
3626         oleNoticeBo.setNoticeName("Return With Missing Piece Notice");
3627         oleNoticeBo.setNoticeSpecificContent("The following item(s) returned by you is missing one or more of its pieces.Please return the missing piece(s) to the library shown above or contact the library about this matter to avoid incurring any penalties.");
3628         oleNoticeBo.setCirculationDeskAddress("");
3629         oleNoticeBo.setCirculationDeskEmailAddress("");
3630         if (oleCirculationDesk != null)
3631             oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
3632         oleNoticeBo.setCirculationDeskPhoneNumber("");
3633         oleNoticeBo.setItemCallNumber(oleLoanDocument.getItemCallNumber() != null ? oleLoanDocument.getItemCallNumber() : "");
3634         oleNoticeBo.setItemShelvingLocation(oleLoanDocument.getItemLocation() != null ? oleLoanDocument.getItemLocation() : "");
3635         oleNoticeBo.setVolumeNumber(oleLoanDocument.getItemVolumeNumber() != null ? oleLoanDocument.getItemVolumeNumber() : "");
3636         oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + "  " + olePatronDocument.getEntity().getNames().get(0).getLastName());
3637         oleNoticeBo.setOleItem(oleLoanDocument.getOleItem());
3638         try {
3639             newLoanDocument = this.getPatronPreferredAddress(entityTypeContactInfoBo, oleLoanDocument);
3640             newLoanDocument = this.getPatronHomeEmailId(entityTypeContactInfoBo, oleLoanDocument);
3641             newLoanDocument = this.getPatronHomePhoneNumber(entityTypeContactInfoBo, oleLoanDocument);
3642             oleNoticeBo.setPatronAddress(newLoanDocument.getPreferredAddress() != null ? newLoanDocument.getPreferredAddress() : "");
3643             oleNoticeBo.setPatronEmailAddress(newLoanDocument.getEmail() != null ? newLoanDocument.getEmail() : "");
3644             oleNoticeBo.setPatronPhoneNumber(newLoanDocument.getPhoneNumber() != null ? newLoanDocument.getPhoneNumber() : "");
3645         } catch (Exception e) {
3646             LOG.error("Exception occured while setting patron Details" + e, e);
3647         }
3648 
3649         return oleNoticeBo;
3650 
3651     }
3652 
3653     public String getCircDeskId() {
3654         return circDeskId;
3655     }
3656 
3657     public void setCircDeskId(String circDeskId) {
3658         this.circDeskId = circDeskId;
3659     }
3660 
3661     public List<String> getLoanUserList(List<String> loginUserList, StringBuffer buffer) {
3662         int count = loginUserList.size() - 1;
3663         String user = loginUserList.size() > 0 ? loginUserList.get(count) : "";
3664         if (!user.equalsIgnoreCase(buffer.toString())) {
3665             loginUserList.add(buffer.toString());
3666         }
3667         return loginUserList;
3668     }
3669 
3670     public void setErrorFlagForItem(OleLoanDocument oleLoanDocument, OleLoanForm oleLoanForm) {
3671         boolean hasRole = false;
3672         Role role;
3673         RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
3674         List<String> roles = new ArrayList<>();
3675         role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_ONE);
3676         roles.add(role.getId());
3677         role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_TWO);
3678         roles.add(role.getId());
3679 
3680         hasRole = roleServiceImpl.principalHasRole(GlobalVariables.getUserSession().getPrincipalId(), roles, null);
3681         if (StringUtils.isNotEmpty(oleLoanForm.getRoleName())) {
3682             if (oleLoanDocument.isBlockCheckinItem()) {
3683                 oleLoanForm.setBlockItem(true);
3684                 oleLoanForm.setBlockPatron(false);
3685             }
3686         } else if (StringUtils.isEmpty(oleLoanForm.getRoleName()) && !hasRole) {
3687             oleLoanForm.setBlockItem(true);
3688             oleLoanForm.setBlockPatron(false);
3689         } else {
3690             oleLoanForm.setBlockItem(true);
3691             oleLoanForm.setBlockPatron(true);
3692         }
3693     }
3694 
3695     public void setErrorFlagForPatron(OleLoanDocument oleLoanDocument, OleLoanForm oleLoanForm) {
3696         boolean hasRole = false;
3697         RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
3698         List<String> roles = new ArrayList<>();
3699 
3700         if (StringUtils.isEmpty(oleLoanForm.getRoleName()) && oleLoanForm.getRoleName() == null) {
3701             Role role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_ONE);
3702             roles.add(role.getId());
3703             hasRole = roleServiceImpl.principalHasRole(GlobalVariables.getUserSession().getPrincipalId(), roles, null);
3704         }
3705         if (hasRole) {
3706             oleLoanForm.setBlockItem(true);
3707             oleLoanForm.setBlockPatron(true);
3708         } else {
3709             oleLoanForm.setBlockItem(false);
3710             oleLoanForm.setBlockPatron(true);
3711         }
3712     }
3713 
3714 
3715     public String getCircDesk() {
3716         String circkDesk = null;
3717         Map<String, String> userMap = new HashMap<String, String>();
3718         userMap.put("operatorId", GlobalVariables.getUserSession().getPrincipalId());
3719         Collection<OleCirculationDeskDetail> oleCirculationDeskDetails = KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, userMap);
3720 
3721         for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3722             if (oleCirculationDeskDetail.isDefaultLocation() && oleCirculationDeskDetail.getOleCirculationDesk().isActive()) {
3723                 circkDesk = (oleCirculationDeskDetail.getOleCirculationDesk().getCirculationDeskId());
3724                 break;
3725             }
3726         }
3727         return circkDesk;
3728     }
3729 
3730     public void checkReplacementFineExist(OleLoanDocument oleLoanDocument) {
3731         Map<String, String> map = new HashMap<String, String>();
3732         map.put(OLEConstants.ITEM_BARCODE, oleLoanDocument.getItemId());
3733         map.put(OLEConstants.FEE_TYPE_FIELD, getOleFeeTypeCode(OLEConstants.FEE_TYPE_CODE_REPL_FEE));
3734         List<FeeType> feeTypes = (List<FeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(FeeType.class, map);
3735         if (feeTypes != null && feeTypes.size() > 0) {
3736             oleLoanDocument.setReplacementFeeExist(true);
3737            /* for(FeeType feeType:feeTypes){
3738                 if(feeType.getBalFeeAmount().compareTo(OLEConstants.BIGDECIMAL_DEF_VALUE)!=0){
3739                     oleLoanDocument.setReplacementFeePaidStatus(false);
3740                     break;
3741                 }
3742             }*/
3743         }
3744 
3745     }
3746 
3747     public void checkOverdueExist(OleLoanDocument oleLoanDocument) {
3748         Map<String, String> map = new HashMap<String, String>();
3749         map.put(OLEConstants.ITEM_BARCODE, oleLoanDocument.getItemId());
3750         map.put(OLEConstants.FEE_TYPE_FIELD, getOleFeeTypeCode(OLEConstants.FEE_TYPE_CODE_OVERDUE));
3751         List<FeeType> feeTypes = (List<FeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(FeeType.class, map);
3752         if (feeTypes != null && feeTypes.size() > 0) {
3753             for (FeeType feeType : feeTypes) {
3754                 if (feeType.getBalFeeAmount().compareTo(OLEConstants.KUALI_BIGDECIMAL_DEF_VALUE) != 0) {
3755                     oleLoanDocument.setOverdueFineExist(true);
3756                     break;
3757                 }
3758             }
3759         }
3760 
3761     }
3762 
3763     public String getOleFeeTypeCode(String typeCode){
3764         Map<String, String> map = new HashMap<String, String>();
3765         map.put(OLEConstants.FEE_TYPE_CODE, typeCode);
3766         List<OleFeeType> feeTypes = (List<OleFeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(OleFeeType.class, map);
3767         if(CollectionUtils.isNotEmpty(feeTypes)){
3768             return feeTypes.get(0).getFeeTypeId();
3769         }
3770         return "";
3771     }
3772 
3773     public void isItemLoanedByDifferentPatron(OleLoanDocument oleLoanDocument) {
3774         Map<String, String> map = new HashMap<String, String>();
3775         map.put(OLEConstants.OleDeliverRequest.ITEM_ID, oleLoanDocument.getItemId());
3776         List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class, map);
3777         if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3778             for (OleLoanDocument loanDocument : oleLoanDocuments) {
3779                 if (loanDocument.getItemId().equalsIgnoreCase(oleLoanDocument.getItemId()) && (oleLoanDocument.getPatronId() != loanDocument.getPatronId())) {
3780                     oleLoanDocument.setDifferentPatron(true);
3781                     break;
3782                 }
3783             }
3784         }
3785     }
3786 
3787     public void checkItemDamagedStatus(OleLoanDocument oleLoanDocument) {
3788         if (oleLoanDocument.getOleItem().isItemDamagedStatus()) {
3789             oleLoanDocument.setItemDamagedStatus(true);
3790         }
3791     }
3792 
3793     public void isMissingPieceFlagActive(OleLoanDocument oleLoanDocument) {
3794         if (oleLoanDocument.getOleItem().isMissingPieceFlag()) {
3795             oleLoanDocument.setMissingPieceFlag(true);
3796         }
3797     }
3798 
3799     public boolean isClaimsReturnedItem(String itemBarcode, OleLoanDocument oleLoanDocument) throws Exception {
3800        /* Map itemUuid = QueryServiceImpl.getInstance().getItemDetails(itemBarcode, oleLoanDocument.getItemUuid());
3801         oleLoanDocument.setInstanceUuid((String) itemUuid.get(OLEConstants.INSTANCE_UUID));
3802         oleLoanDocument.setItemUuid((String) itemUuid.get(OLEConstants.ITEM_UUID));
3803         oleLoanDocument.setBibUuid((String) itemUuid.get(OLEConstants.BIB_UUID));*/
3804         LOG.debug("Inside the addLoan method");
3805         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
3806         org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
3807         SearchResponse searchResponse = null;
3808         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, itemBarcode), ""));
3809         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "ItemIdentifier_display"));
3810         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.HOLDINGSIDENTIFIER));
3811         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
3812         if (itemBarcode != null && !itemBarcode.isEmpty()) {
3813             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
3814             if (searchResponse.getSearchResults() != null && searchResponse.getSearchResults().size() > 0) {
3815                 for (SearchResult searchResult : searchResponse.getSearchResults()) {
3816                     for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
3817                         String fieldName = searchResultField.getFieldName();
3818                         String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
3819 
3820                         if (fieldName.equalsIgnoreCase( Holdings.HOLDINGSIDENTIFIER) && !fieldValue.isEmpty()) {
3821                             oleLoanDocument.setInstanceUuid(fieldValue);
3822                         } else if (fieldName.equalsIgnoreCase( Bib.BIBIDENTIFIER) && !fieldValue.isEmpty()) {
3823                             oleLoanDocument.setBibUuid(fieldValue);
3824                         } else {
3825                             oleLoanDocument.setItemUuid(fieldValue);
3826                         }
3827 
3828                     }
3829                 }
3830             } else {
3831                 throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
3832             }
3833 
3834 
3835         } else {
3836 
3837             item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
3838 
3839 
3840             oleLoanDocument.setInstanceUuid(item.getHolding().getId());
3841             oleLoanDocument.setItemUuid(item.getId());
3842             oleLoanDocument.setBibUuid(item.getHolding().getBib().getId());
3843         }
3844         String itemXml = getItemXML(oleLoanDocument.getItemUuid());
3845         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXml);
3846 
3847         org.kuali.ole.docstore.common.document.Item itemXML = new ItemOleml();
3848         itemXML.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
3849         if (oleItem.isClaimsReturnedFlag()) {
3850             return true;
3851         }
3852         return false;
3853     }
3854 
3855     public OleLoanForm processLoan(OleLoanForm oleLoanForm, OleLoanDocument oleLoanDocument) throws Exception {
3856         oleLoanDocument.setPatronId(oleLoanForm.getPatronId());
3857         oleLoanDocument.setProxyPatronId(oleLoanForm.getProxyPatronId());
3858         oleLoanDocument.setRealPatronBarcode(oleLoanForm.getRealPatronBarcode());
3859         oleLoanDocument.setRealPatronType(oleLoanForm.getRealPatronType());
3860         oleLoanDocument.setCirculationLocationId(oleLoanForm.getCirculationDesk());
3861         oleLoanDocument.setBorrowerTypeId(oleLoanForm.getBorrowerTypeId());
3862         oleLoanDocument.setBorrowerTypeName(oleLoanForm.getBorrowerType());
3863         oleLoanDocument.setBorrowerTypeCode(oleLoanForm.getBorrowerCode());
3864         List<OleLoanDocument> existingItemList = new ArrayList<OleLoanDocument>();
3865         oleLoanDocument = addLoan(oleLoanForm.getPatronBarcode(), oleLoanForm.getItem(), oleLoanDocument,null);
3866         oleLoanForm.setItemUuid(oleLoanDocument.getItemUuid());
3867         oleLoanForm.setNonCirculatingFlag(oleLoanDocument.isNonCirculatingItem());
3868         oleLoanForm.setInstanceUuid(oleLoanDocument.getInstanceUuid());
3869         oleLoanForm.setOleItem(oleLoanDocument.getOleItem());
3870         oleLoanForm.setDueDateMap(oleLoanDocument.getLoanDueDate());
3871         oleLoanForm.setMessage(oleLoanDocument.getErrorMessage());
3872         oleLoanForm.setRoleName(oleLoanDocument.getRoleName());
3873         oleLoanForm.getErrorsAndPermission().putAll(oleLoanDocument.getErrorsAndPermission());
3874         if (oleLoanForm.getPatronName() == null) {
3875             oleLoanForm.setPatronName(oleLoanDocument.getPatronName());
3876         }
3877         if(oleLoanForm.getRealPatronName()!=null){
3878             oleLoanDocument.setRealPatronName(oleLoanForm.getRealPatronName());
3879         }
3880         if (oleLoanDocument.getErrorMessage() == null) {
3881             existingItemList.add(oleLoanDocument);
3882             oleLoanForm.setBlockItem(false);
3883             oleLoanForm.setBlockPatron(false);
3884             oleLoanForm.setItem("");
3885             oleLoanForm.setInformation("");
3886         } else {
3887             oleLoanForm.setDueDateEmpty(oleLoanDocument.isDueDateEmpty());
3888             oleLoanForm.setDummyLoan(oleLoanDocument);
3889             oleLoanForm.setSuccess(false);
3890             if (oleLoanDocument.getOleItem() != null) {
3891                 oleLoanForm.setDescription(oleLoanDocument.getOleItem().getCheckinNote());
3892             }
3893             oleLoanForm.setInformation("");
3894             setErrorFlagForItem(oleLoanDocument, oleLoanForm);
3895         }
3896         if (oleLoanForm.getLoanList() != null && !oleLoanForm.getLoanList().isEmpty()) {
3897             existingItemList.addAll(oleLoanForm.getLoanList());
3898         }
3899         if (oleLoanDocument.getItemLoanStatus() != null && oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.ITEM_STATUS_LOST) || oleLoanDocument.isReplacementFeeExist()) {
3900             oleLoanForm.setBlockUser(true);
3901         }
3902         else if (oleLoanDocument.isOverdueFineExist() && oleLoanDocument.isDifferentPatron()) {
3903             oleLoanForm.setBlockUser(true);
3904         }else {
3905             oleLoanForm.setBlockUser(false);
3906         }
3907         oleLoanForm.setLoanList(existingItemList);
3908         List<OleLoanDocument> oleLoanDocumentList = new ArrayList<OleLoanDocument>();
3909         oleLoanDocumentList.add(oleLoanDocument);
3910 
3911         if (getParameter(OLEConstants.PRINT_DUE_DATE_PER_TRANSACTION).equalsIgnoreCase("Yes")) {
3912             oleLoanForm.setDueDateSlip(true);
3913         }
3914         oleLoanForm.setItemFocus(true);
3915         oleLoanForm.setPatronFocus(false);
3916         String audioOption = getParameter(OLEConstants.AUDIO_OPTION);
3917         oleLoanForm.setAudioEnable(audioOption != null && !audioOption.isEmpty() && audioOption.equalsIgnoreCase(OLEConstants.TRUE));
3918         oleLoanForm.setItemUuid(null);
3919         oleLoanForm.setInstanceUuid(null);
3920         oleLoanForm.setSuccessMessage(oleLoanDocument.getSuccessMessage());
3921         return oleLoanForm;
3922     }
3923 
3924     public void updateMissingPiecesItemInfo(OleLoanDocument oleLoanDocument) throws Exception {
3925         LOG.debug("Inside the updateItemStatus method for missing pieces");
3926         try {
3927             String itemXmlContent = getItemXML(oleLoanDocument.getItemUuid());
3928             org.kuali.ole.docstore.common.document.content.instance.Item item = getItemPojo(itemXmlContent);
3929             item.setMissingPieceFlag(true);
3930             SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
3931             String parsedDate = df.format((new Date()));
3932             item.setMissingPieceEffectiveDate(parsedDate);
3933             if (oleLoanDocument.getMissingPieceNote() != null && !oleLoanDocument.getMissingPieceNote().isEmpty()) {
3934                 item.setMissingPieceFlagNote(oleLoanDocument.getMissingPieceNote());
3935             }
3936             int newMissingPieceCount = 0;
3937             if (oleLoanDocument.getMissingPiecesCount() != null && !oleLoanDocument.getMissingPiecesCount().equalsIgnoreCase("")) {
3938                 newMissingPieceCount = Integer.parseInt(oleLoanDocument.getMissingPiecesCount());
3939             }
3940             if (newMissingPieceCount == 0) {
3941                 item.setMissingPiecesCount(item.getMissingPiecesCount());
3942             } else {
3943                 if (oleLoanDocument.getOleItem() != null && oleLoanDocument.getOleItem().getMissingPiecesCount() != null && (!oleLoanDocument.getOleItem().getMissingPiecesCount().equalsIgnoreCase(""))) {
3944                     int oldMissingPieceCount = Integer.parseInt(item.getMissingPiecesCount());
3945                     item.setMissingPiecesCount(oldMissingPieceCount + newMissingPieceCount + "");
3946                 } else {
3947                     item.setMissingPiecesCount(newMissingPieceCount + "");
3948                 }
3949             }
3950             oleLoanDocument.setOleItem(item);
3951             itemXmlContent = getItemOlemlRecordProcessor().toXML(item);
3952             if (LOG.isDebugEnabled()){
3953                 LOG.debug("itemXmlContent" + itemXmlContent);
3954             }
3955             Item oleItem = new ItemOleml();
3956             oleItem.setContent(itemXmlContent);
3957             oleItem.setCategory(OLEConstants.WORK_CATEGORY);
3958             oleItem.setType(DocType.ITEM.getCode());
3959             oleItem.setFormat(OLEConstants.OLEML_FORMAT);
3960             oleItem.setId(oleLoanDocument.getItemUuid());
3961             getDocstoreClientLocator().getDocstoreClient().updateItem(oleItem);
3962         } catch (Exception e) {
3963             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
3964             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
3965         }
3966     }
3967 
3968 
3969     public HashMap<String,Integer> getItemTypeMap(List<OleLoanDocument> oleLoanDocuments,OleLoanDocument currentLoan){
3970         Long begin = System.currentTimeMillis();
3971         HashMap<String,Integer> itemTypeMap = new HashMap<>();
3972         for(OleLoanDocument oleLoanDocument : oleLoanDocuments){
3973             if(itemTypeMap.containsKey(oleLoanDocument.getItemType())){
3974                 Integer count = itemTypeMap.get(oleLoanDocument.getItemType());
3975                 count++;
3976                 itemTypeMap.put(oleLoanDocument.getItemType(),count);
3977             }else{
3978                 itemTypeMap.put(oleLoanDocument.getItemType(),1);
3979             }
3980         }
3981         if(itemTypeMap.containsKey(currentLoan.getItemType())){
3982             Integer count = itemTypeMap.get(currentLoan.getItemType());
3983             count++;
3984             itemTypeMap.put(currentLoan.getItemType(),count);
3985         }else{
3986             itemTypeMap.put(currentLoan.getItemType(),1);
3987         }
3988         Long end = System.currentTimeMillis();
3989         Long timeTaken = end - begin;
3990         LOG.info("The Time Taken for getItemTypeMap in Add Item"+timeTaken);
3991         return itemTypeMap;
3992     }
3993 
3994 
3995     public HashMap<String,Integer> getItemTypeFromCurrentLoan(HashMap<String,Integer> itemTypeMap,OleLoanDocument currentLoan){
3996         if(itemTypeMap!=null){
3997             if(itemTypeMap.containsKey(currentLoan.getItemType())){
3998                 Integer count = itemTypeMap.get(currentLoan.getItemType());
3999                 count++;
4000                 itemTypeMap.put(currentLoan.getItemType(),count);
4001             }else{
4002                 itemTypeMap.put(currentLoan.getItemType(),1);
4003             }
4004         }
4005         return itemTypeMap;
4006     }
4007 
4008     private String getPaymentStatusId(String paymentStatusCode) throws Exception{
4009         Map<String,String> mapPayStatus = new HashMap();
4010         mapPayStatus.put(OLEConstants.PAY_STATUS_CODE,paymentStatusCode);
4011         List<OlePaymentStatus> patronBillPayments = (List<OlePaymentStatus>)getBusinessObjectService().findMatching(OlePaymentStatus.class, mapPayStatus);
4012         return CollectionUtils.isNotEmpty(patronBillPayments)?patronBillPayments.get(0).getPaymentStatusId():"";
4013     }
4014 
4015     public boolean checkPatronBill(String patronId)throws Exception{
4016         Map map = new HashMap();
4017         map.put(OLEConstants.PTRN_ID, patronId);
4018         map.put(OLEConstants.FEE_TYPE_PAY_STATUS, getPaymentStatusId(OLEConstants.PAY_STATUS_OUTSTANDING_CODE));
4019         List<PatronBillPayment> patronBillPayments = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, map);
4020         if (patronBillPayments != null && patronBillPayments.size() > 0) {
4021             return true;
4022         } else {
4023             map.clear();
4024             map.put(OLEConstants.PTRN_ID, patronId);
4025             map.put(OLEConstants.FEE_TYPE_PAY_STATUS, getPaymentStatusId(OLEConstants.PAY_STATUS_PART_CODE));
4026             List<PatronBillPayment> payments = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, map);
4027             if (payments != null && payments.size() > 0) {
4028                 return true;
4029             }
4030         }
4031         return false;
4032     }
4033 
4034     public String getItemStatus() {
4035         return itemStatus;
4036     }
4037 
4038     public void setItemStatus(String itemStatus) {
4039         this.itemStatus = itemStatus;
4040     }
4041 
4042     public OleCirculationDesk getCirculationDeskByLocationCode(String locationCode) {
4043         Map<String, String> userMap = new HashMap<String, String>();
4044         userMap.put(OLEConstants.OleCirculationDesk.OLE_CIRCULATION_DESK_CD, locationCode);
4045         List<OleCirculationDesk> oleCirculationDesks = (List<OleCirculationDesk>) getBusinessObjectService().findMatching(OleCirculationDesk.class, userMap);
4046         return oleCirculationDesks != null && oleCirculationDesks.size() > 0 ? oleCirculationDesks.get(0) : null;
4047     }
4048 
4049     public void buildSearchParams(SearchParams searchParams){
4050         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemBarcode_display"));
4051         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "id"));
4052         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "bibIdentifier"));
4053         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Title_display"));
4054         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Author_display"));
4055         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "LocalId_display"));
4056         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "holdingsIdentifier"));
4057         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ClaimsReturnedFlag_display"));
4058         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedFlagCreateDate"));
4059         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "claimsReturnedNote"));
4060         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumber_display"));
4061         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "TemporaryItemTypeFullValue_search"));
4062         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemTypeFullValue_display"));
4063         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Enumeration_display"));
4064         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Chronology_display"));
4065         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemStatus_display"));
4066         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "ItemDamagedStatus_display"));
4067         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "DamagedItemNote_search"));
4068         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceFlagNote_search"));
4069         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "Location_display"));
4070         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCopyNumber_search"));
4071         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsCallNumber_search"));
4072         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "HoldingsLocation_search"));
4073         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "MissingPieceCount_search"));
4074         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfPieces_search"));
4075         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CallNumberPrefix_display"));
4076         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "CopyNumber_search"));
4077         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "proxyBorrower"));
4078         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "VolumeNumberLabel_display"));
4079         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "dueDateTime"));
4080         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item", "NumberOfRenew_display"));
4081         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item" , "checkOutDateTime"));
4082         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item","ClaimsReturnedFlag_search"));
4083         searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("item","itemStatusEffectiveDate"));
4084     }
4085 
4086 
4087     public void getLocationBySolr(SearchResultField searchResultField,OleLoanDocument oleLoanDocument)throws Exception{
4088         String locationCode = searchResultField.getFieldValue().split("/")[searchResultField.getFieldValue().split("/").length-1];
4089         String levelFullName = "";
4090         if(locationName.containsKey(locationCode)) {
4091             levelFullName = locationName.get(locationCode);
4092         }
4093         else {
4094             OleLocation oleLocation = getLocationByLocationCode(locationCode);
4095             levelFullName = getFullPathLocationByName(oleLocation);
4096             locationName.put(locationCode,levelFullName);
4097         }
4098 
4099         oleLoanDocument.setItemLocation(levelFullName);
4100         oleLoanDocument.setLocation(levelFullName);
4101     }
4102 
4103     public List<OleLoanDocument> buildSearchResultsFields(SearchResponse searchResponse,HashMap<String,Object> loanMap)throws Exception{
4104         int count = 0;
4105         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
4106         List<OleLoanDocument> oleLoanDocuments = new ArrayList<>();
4107         if(searchResponse!=null){
4108             for (SearchResult searchResult : searchResponse.getSearchResults()) {
4109                 OleLoanDocument oleLoanDocument = null;
4110                 for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
4111 
4112                     if(searchResultField.getFieldValue()!=null){
4113 
4114                         if(searchResultField.getFieldName().equalsIgnoreCase("ItemBarcode_display")) {
4115                             oleLoanDocument = new OleLoanDocument();
4116                             oleLoanDocument.setItemId(searchResultField.getFieldValue());
4117                         }
4118                         if (searchResultField.getFieldName().equalsIgnoreCase("id")) {
4119                            //(OleLoanDocument)loanMap.get((searchResultField.getFieldValue()));
4120                             if (null == oleLoanDocument) {
4121                                 oleLoanDocument = new OleLoanDocument();
4122                             }
4123                             oleLoanDocument.setItemUuid(searchResultField.getFieldValue());
4124                         }
4125                         else if (searchResultField.getFieldName().equalsIgnoreCase("bibIdentifier")) {
4126                             oleLoanDocument.setBibUuid(searchResultField.getFieldValue());
4127                         }
4128                         else if (searchResultField.getFieldName().equalsIgnoreCase("Title_display")) {
4129                             oleLoanDocument.setTitle(searchResultField.getFieldValue());
4130                         }
4131                         else if (searchResultField.getFieldName().equalsIgnoreCase("Author_display")) {
4132                             oleLoanDocument.setAuthor(searchResultField.getFieldValue());
4133                         }
4134                         else if (searchResultField.getFieldName().equalsIgnoreCase("holdingsIdentifier")) {
4135                             oleLoanDocument.setInstanceUuid(searchResultField.getFieldValue());
4136                         }
4137                         else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedNote")) {
4138                             oleLoanDocument.setClaimsReturnNote(searchResultField.getFieldValue());
4139                             //  count++;
4140                         }
4141 
4142                         else if (searchResultField.getFieldName().equalsIgnoreCase("ClaimsReturnedFlag_display") && searchResultField.getFieldValue().equalsIgnoreCase("true")) {
4143                             oleLoanDocument.setClaimsReturnedIndicator(true);
4144                             count++;
4145                         }
4146                         else  if (searchResultField.getFieldName().equalsIgnoreCase("Location_display")) {
4147                             getLocationBySolr(searchResultField,oleLoanDocument);
4148                             oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
4149                         }
4150                         else  if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsLocation_search") &&
4151                                 (oleLoanDocument.getItemLocation()==null || oleLoanDocument.getItemLocation().isEmpty())) {
4152                             getLocationBySolr(searchResultField,oleLoanDocument);
4153                             oleLoanDocument.setItemFullLocation(searchResultField.getFieldValue());
4154                         }
4155                         else if (searchResultField.getFieldName().equalsIgnoreCase("claimsReturnedFlagCreateDate")) {
4156                             String[] formatStrings = new String[]{"MM/dd/yyyy hh:mm:ss","MM/dd/yyyy","yyyy-MM-dd hh:mm:ss"};
4157                             Date date =tryParse(formatStrings,searchResultField.getFieldValue());
4158                             oleLoanDocument.setClaimsReturnedDate(new Timestamp(date.getTime()));
4159 
4160                         }
4161                         else if (searchResultField.getFieldName().equalsIgnoreCase("dueDateTime")) {
4162                             String[] formatStrings = new String[]{"MM/dd/yyyy hh:mm:ss","MM/dd/yyyy","yyyy-MM-dd hh:mm:ss"};
4163                              Date date =tryParse(formatStrings,searchResultField.getFieldValue());
4164                              oleLoanDocument.setLoanDueDate(new Timestamp(date.getTime()));
4165 
4166                         }
4167                         else if (searchResultField.getFieldName().equalsIgnoreCase("CallNumber_display")) {
4168                             oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
4169                         }
4170                         else if (searchResultField.getFieldName().equalsIgnoreCase("TemporaryItemTypeFullValue_search")) {
4171                             oleLoanDocument.setItemType(searchResultField.getFieldValue());
4172                         }
4173                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemTypeFullValue_display") &&
4174                                 (oleLoanDocument.getItemType()==null || oleLoanDocument.getItemType().isEmpty())) {
4175                             oleLoanDocument.setItemType(searchResultField.getFieldValue());
4176                         }
4177                         else if (searchResultField.getFieldName().equalsIgnoreCase("TemporaryItemTypeCodeValue_search")) {
4178                             oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
4179                         }
4180                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemTypeCodeValue_display") &&
4181                                 (oleLoanDocument.getItemTypeName()==null || oleLoanDocument.getItemTypeName().isEmpty())) {
4182                             oleLoanDocument.setItemTypeName(searchResultField.getFieldValue());
4183                         }
4184                         else if (searchResultField.getFieldName().equalsIgnoreCase("Enumeration_display")) {
4185                             oleLoanDocument.setEnumeration(searchResultField.getFieldValue());
4186                         }
4187                         else if (searchResultField.getFieldName().equalsIgnoreCase("Chronology_display")) {
4188                             oleLoanDocument.setChronology(searchResultField.getFieldValue());
4189                         }
4190                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemStatus_display")) {
4191                             oleLoanDocument.setItemStatus(searchResultField.getFieldValue());
4192                         }
4193                         else if (searchResultField.getFieldName().equalsIgnoreCase("ItemDamagedStatus_display")) {
4194                             oleLoanDocument.setItemDamagedStatus(searchResultField.getFieldValue().equalsIgnoreCase("true"));
4195                         }
4196                         else if (searchResultField.getFieldName().equalsIgnoreCase("DamagedItemNote_search")) {
4197                             oleLoanDocument.setItemDamagedNote(searchResultField.getFieldValue());
4198                         }
4199                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlagNote_search")) {
4200                             oleLoanDocument.setMissingPieceNote(searchResultField.getFieldValue());
4201                         }
4202                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceFlag_display")) {
4203                             oleLoanDocument.setMissingPieceFlag(searchResultField.getFieldValue().equalsIgnoreCase("true"));
4204                         }
4205                         else if (searchResultField.getFieldName().equalsIgnoreCase("CopyNumber_search")) {
4206                             oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
4207                         }
4208                         else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCopyNumber_search") &&
4209                                 (oleLoanDocument.getItemCopyNumber()==null || oleLoanDocument.getItemCopyNumber().isEmpty())) {
4210                             oleLoanDocument.setItemCopyNumber(searchResultField.getFieldValue());
4211                         }
4212                         else if (searchResultField.getFieldName().equalsIgnoreCase("HoldingsCallNumber_search") &&
4213                                 (oleLoanDocument.getItemCallNumber()==null || oleLoanDocument.getItemCallNumber().isEmpty())) {
4214                             oleLoanDocument.setItemCallNumber(searchResultField.getFieldValue());
4215                         }
4216                         else if (searchResultField.getFieldName().equalsIgnoreCase("MissingPieceCount_search")) {
4217                             oleLoanDocument.setMissingPiecesCount(searchResultField.getFieldValue());
4218                         }
4219                         else if (searchResultField.getFieldName().equalsIgnoreCase("NumberOfPieces_search")) {
4220                             oleLoanDocument.setItemNumberOfPieces(Integer.parseInt(searchResultField.getFieldValue()));
4221                             oleLoanDocument.setBackUpNoOfPieces(searchResultField.getFieldValue());
4222                         }
4223                         else if (searchResultField.getFieldName().equalsIgnoreCase("proxyBorrower")) {
4224                             oleLoanDocument.setRealPatronName(searchResultField.getFieldValue());
4225                         }else if(searchResultField.getFieldName().equalsIgnoreCase("NumberOfRenew_display")) {
4226                             oleLoanDocument.setNumberOfRenewals(searchResultField.getFieldValue());
4227                         }else if(searchResultField.getFieldName().equalsIgnoreCase("checkOutDateTime")){
4228                             SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
4229                             Date date = formatter.parse(searchResultField.getFieldValue());
4230                             oleLoanDocument.setCreateDate(date);
4231                         }
4232                     }
4233                 }
4234                 if(oleLoanDocument.getOlePatron()!=null){
4235                     oleLoanDocument.getOlePatron().setNumberOfClaimsReturned(count);
4236                 }
4237                 oleLoanDocuments.add(oleLoanDocument);
4238             }
4239 
4240         }
4241         return oleLoanDocuments;
4242     }
4243 
4244     public Date tryParse(String[] formatStrings, String dateString) throws ParseException {
4245         StringBuffer exceptionMessage = new StringBuffer("Parse Exception'");
4246         for (String formatString : formatStrings) {
4247             try {
4248                 return new SimpleDateFormat(formatString).parse(dateString);
4249             } catch (ParseException e) {
4250                 exceptionMessage.append(e.getMessage());
4251             }
4252         }
4253         throw new ParseException(exceptionMessage.toString(), 0);
4254     }
4255     /**
4256      * This method is used to set the check-in date in the replacement fee bill generated throuigh batch job
4257      * @param oleLoanDocument
4258      */
4259 
4260     public void updateReplacementFeeBill(OleLoanDocument oleLoanDocument){
4261         long begin = System.currentTimeMillis();
4262         if(LOG.isInfoEnabled()){
4263        LOG.info("Inside the updateReplacementFee for the patron barcode :"+oleLoanDocument.getPatronBarcode() + "Item Barcode : " +oleLoanDocument.getItemId() );
4264         }
4265         Map map=new HashMap<String,String>();
4266         map.put(OLEConstants.FEE_TYPE_PATRON_ID,oleLoanDocument.getPatronId());
4267         map.put(OLEConstants.ITEM_BARCODE,oleLoanDocument.getItemId());
4268         map.put(OLEConstants.FEE_TYPE_FIELD, "2");
4269         List<FeeType> feeTypeList = (List<FeeType>) getBusinessObjectService().findMatching(FeeType.class, map);
4270         if(feeTypeList!=null && feeTypeList.size()>0){
4271             for(FeeType feeType:feeTypeList){
4272             if(feeType.getDueDate()!=null && oleLoanDocument.getLoanDueDate()!=null){
4273                 if(feeType.getDueDate().getTime()==oleLoanDocument.getLoanDueDate().getTime()){
4274                     feeType.setCheckInDate(oleLoanDocument.getCheckInDate());
4275                     getBusinessObjectService().save(feeType);
4276                     break;
4277                 }
4278             }
4279 
4280             }
4281         }
4282         long end = System.currentTimeMillis();
4283         long total = end - begin;
4284         LOG.info("Time taken Inside updateReplacementFeeBill"+total);
4285     }
4286 
4287     public OleLoanDocumentDaoOjb getOleLoanDocumentDaoOjb() {
4288         if(oleLoanDocumentDaoOjb == null){
4289             oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb)SpringContext.getBean("oleLoanDao");
4290         }
4291         return oleLoanDocumentDaoOjb;
4292     }
4293 
4294     public void setOleLoanDocumentDaoOjb(OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb) {
4295         this.oleLoanDocumentDaoOjb = oleLoanDocumentDaoOjb;
4296     }
4297 
4298     public void validateCalanderForCirculationDesk(String circulationDeskLocationId) throws Exception{
4299         OleCirculationDesk oleCirculationDesk = getOleCirculationDesk(circulationDeskLocationId);
4300         if (oleCirculationDesk != null && oleCirculationDesk.getCalendarGroupId() != null) {
4301             OleCalendarService oleCalendarService = new OleCalendarServiceImpl();
4302             OleCalendar oleCalendar = oleCalendarService.getActiveCalendar(new Timestamp(System.currentTimeMillis()), oleCirculationDesk.getCalendarGroupId());
4303             if (oleCalendar == null) {
4304                 throw new Exception("Calendar does not exist");
4305             }
4306         }
4307        /* getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");*/
4308     }
4309 
4310     public OleLoanDocument retrieveByPatronAndItem(String patronId,String itemBarcode) throws Exception{
4311         LOG.debug("Inside the retrieveByPatronAndItem method");
4312         Long b1 = System.currentTimeMillis();
4313         SearchResponse searchResponse = new SearchResponse();
4314         HashMap<String,Object> loanMap = new HashMap<>();
4315         org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
4316         if(patronId != null){
4317             String itemStatusParam = getParameter(OLEParameterConstants.ITEM_STATUS_FOR_RET_LOAN);
4318             String[] itemStatus = new String[0];
4319             if(itemStatusParam != null){
4320                 itemStatus = itemStatusParam.split("[|]");
4321             }
4322             SearchParams searchParams = new SearchParams();
4323             List<SearchCondition> searchConditions = new ArrayList<>();
4324             int count = itemStatus.length;
4325             for(int i=0; i< count;i++) {
4326                 if(i == (count-1)) {
4327                     searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", itemStatus[i]), "AND"));
4328                 }
4329                 else {
4330                     searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", itemStatus[i]), "OR"));
4331                 }
4332             }
4333 
4334             searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField("item", "currentBorrower", patronId), "AND"));
4335             searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, itemBarcode), "AND"));
4336             searchParams.setPageSize(Integer.parseInt(OLEConstants.MAX_PAGE_SIZE_FOR_LOAN));
4337             buildSearchParams(searchParams);
4338             searchParams.getSearchConditions().addAll(searchConditions);
4339             searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
4340         }
4341         List<OleLoanDocument> matchingLoan = buildSearchResultsFields(searchResponse,loanMap);
4342         Long b2 = System.currentTimeMillis();
4343         Long b3 = b2-b1;
4344         LOG.info("The Time taken retrieveByPatronAndItem--"+b3);
4345         return matchingLoan!=null && matchingLoan.size()>0 ? matchingLoan.get(0) : null;
4346     }
4347 
4348     public OLEDeliverNoticeHelperService getOleDeliverNoticeHelperService() {
4349         return oleDeliverNoticeHelperService;
4350     }
4351 
4352     public void setOleDeliverNoticeHelperService(OLEDeliverNoticeHelperService oleDeliverNoticeHelperService) {
4353         this.oleDeliverNoticeHelperService = oleDeliverNoticeHelperService;
4354     }
4355 }
4356 
4357