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