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