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