View Javadoc
1   package org.kuali.ole.deliver.controller.checkout;
2   
3   import org.apache.commons.collections.CollectionUtils;
4   import org.apache.commons.lang.StringUtils;
5   import org.apache.log4j.Logger;
6   import org.kie.api.runtime.KieSession;
7   import org.kie.api.runtime.rule.Agenda;
8   import org.kie.api.runtime.rule.AgendaGroup;
9   import org.kuali.ole.OLEConstants;
10  import org.kuali.ole.deliver.OleLoanDocumentsFromSolrBuilder;
11  import org.kuali.ole.deliver.bo.OLEDeliverNotice;
12  import org.kuali.ole.deliver.bo.OleItemSearch;
13  import org.kuali.ole.deliver.bo.OleLoanDocument;
14  import org.kuali.ole.deliver.bo.OleNoticeTypeConfiguration;
15  import org.kuali.ole.deliver.calendar.service.DateUtil;
16  import org.kuali.ole.deliver.drools.CustomAgendaFilter;
17  import org.kuali.ole.deliver.drools.DroolsConstants;
18  import org.kuali.ole.deliver.drools.DroolsKieEngine;
19  import org.kuali.ole.deliver.service.CircDeskLocationResolver;
20  import org.kuali.ole.deliver.util.NoticeInfo;
21  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
22  import org.kuali.ole.docstore.common.document.Item;
23  import org.kuali.ole.docstore.common.document.ItemOleml;
24  import org.kuali.ole.docstore.common.document.content.enums.DocType;
25  import org.kuali.ole.docstore.common.document.content.instance.*;
26  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
27  import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemRecord;
28  import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.LocationsCheckinCountRecord;
29  import org.kuali.ole.sys.context.SpringContext;
30  import org.kuali.ole.util.DocstoreUtil;
31  import org.kuali.rice.core.api.CoreApiServiceLocator;
32  import org.kuali.rice.krad.service.BusinessObjectService;
33  import org.kuali.rice.krad.service.KRADServiceLocator;
34  import org.kuali.rice.krad.util.GlobalVariables;
35  
36  import java.math.BigDecimal;
37  import java.sql.Timestamp;
38  import java.text.ParseException;
39  import java.text.SimpleDateFormat;
40  import java.util.*;
41  import java.util.regex.Matcher;
42  import java.util.regex.Pattern;
43  
44  /**
45   * Created by pvsubrah on 6/4/15.
46   */
47  public class CircUtilController {
48      private static final Logger LOG = Logger.getLogger(CircUtilController.class);
49      private BusinessObjectService businessObjectService;
50      private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
51      private DocstoreClientLocator docstoreClientLocator;
52      private SimpleDateFormat dateFormatForDocstoreDueDate;
53      private OleLoanDocumentsFromSolrBuilder oleLoanDocumentsFromSolrBuilder;
54  
55      public void fireRules(List<Object> facts, String[] expectedRules, String agendaGroup) {
56          KieSession session = DroolsKieEngine.getInstance().getSession();
57          for (Iterator<Object> iterator = facts.iterator(); iterator.hasNext(); ) {
58              Object fact = iterator.next();
59              session.insert(fact);
60          }
61  
62          if (null != expectedRules && expectedRules.length > 0) {
63              session.fireAllRules(new CustomAgendaFilter(expectedRules));
64          } else {
65              Agenda agenda = session.getAgenda();
66              AgendaGroup group = agenda.getAgendaGroup(agendaGroup);
67              group.setFocus();
68              session.fireAllRules();
69          }
70  
71          session.dispose();
72      }
73  
74      public List<OLEDeliverNotice> processNotices(OleLoanDocument currentLoanDocument, ItemRecord itemRecord) {
75          List<OLEDeliverNotice> deliverNotices = new ArrayList<>();
76  
77          HashMap<String, Object> map = new HashMap<>();
78          map.put("circPolicyId", currentLoanDocument.getCirculationPolicyId());
79          List<OleNoticeTypeConfiguration> oleNoticeTypeConfigurations =
80                  (List<OleNoticeTypeConfiguration>) getBusinessObjectService().findMatching(OleNoticeTypeConfiguration.class, map);
81  
82          OleNoticeTypeConfiguration oleNoticeTypeConfiguration = null;
83          if (CollectionUtils.isNotEmpty(oleNoticeTypeConfigurations)) {
84              oleNoticeTypeConfiguration = oleNoticeTypeConfigurations.get(0);
85              NoticeInfo noticeInfo = new NoticeInfo();
86              noticeInfo.setNoticeType(oleNoticeTypeConfiguration.getNoticeType());
87  
88              ArrayList<Object> facts = new ArrayList<>();
89              facts.add(noticeInfo);
90              facts.add(itemRecord);
91              fireRules(facts, null, "notice generation");
92  
93  
94              Map<String, Map<String, Object>> noticeInfoForTypeMap = noticeInfo.getNoticeInfoForTypeMap();
95  
96              if (null != noticeInfoForTypeMap) {
97                  for (Iterator<String> iterator = noticeInfoForTypeMap.keySet().iterator(); iterator.hasNext(); ) {
98                      String noticeType = iterator.next();
99                      if (noticeType.equalsIgnoreCase(OLEConstants.COURTESY_NOTICE)) {
100                         processCourtseyNotices(noticeInfo, deliverNotices, currentLoanDocument);
101                     } else if (noticeType.equalsIgnoreCase(OLEConstants.OVERDUE_NOTICE)) {
102                         Integer numOverDueNoticeToBeSent = Integer.parseInt((String) noticeInfo.getNoticeInfoForTypeMap().get
103                                 (OLEConstants.OVERDUE_NOTICE).get(DroolsConstants.NUMBER_OF_OVERDUE_NOTICES_TO_BE_SENT));
104                         int count = 0;
105                         for (count = 0; count < numOverDueNoticeToBeSent; count++) {
106                             processOverdueNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
107                         }
108                         processLostNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
109                     } else if (noticeType.equalsIgnoreCase(OLEConstants.RECALL_COURTESY_NOTICE)) {
110                         processCourtseyNotices(noticeInfo, deliverNotices, currentLoanDocument);
111                     } else if (noticeType.equalsIgnoreCase(OLEConstants.RECALL_OVERDUE_NOTICE)) {
112                         Integer numOverDueNoticeToBeSent = Integer.parseInt((String) noticeInfo.getNoticeInfoForTypeMap().get
113                                 (OLEConstants.RECALL_OVERDUE_NOTICE).get(DroolsConstants.NUMBER_OF_OVERDUE_NOTICES_TO_BE_SENT));
114                         int count = 0;
115                         for (count = 0; count < numOverDueNoticeToBeSent; count++) {
116                             processOverdueNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
117                         }
118                         processLostNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
119 
120                     }
121                 }
122             }
123 
124         } else {
125             LOG.error("No notice coniguration mapping was found for the circulation policy id: " + currentLoanDocument.getCirculationLocationId());
126         }
127 
128         return deliverNotices;
129     }
130 
131     private void processLostNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, int count, OleLoanDocument currentLoanDocument) {
132         OLEDeliverNotice lostNotice = new OLEDeliverNotice();
133         lostNotice.setNoticeType(OLEConstants.NOTICE_LOST);
134         lostNotice.setNoticeSendType(DroolsConstants.EMAIL);
135         lostNotice.setPatronId(currentLoanDocument.getPatronId());
136         Map<String, Object> overdueMap = new HashMap<String, Object>();
137         if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.OVERDUE_NOTICE)) {
138             overdueMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.OVERDUE_NOTICE);
139         } else if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.RECALL_OVERDUE_NOTICE)) {
140             overdueMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.RECALL_OVERDUE_NOTICE);
141         }
142         lostNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(Integer.parseInt((String) overdueMap.get(DroolsConstants
143                 .INTERVAL_TO_GENERATE_NOTICE_FOR_OVERDUE)), currentLoanDocument.getLoanDueDate(), count + 1));
144         deliverNotices.add(lostNotice);
145         lostNotice.setReplacementFeeAmount(BigDecimal.valueOf(Double.parseDouble((String) overdueMap.get(DroolsConstants
146                 .REPLACEMENT_BILL_AMT))));
147     }
148 
149     private void processOverdueNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, int count, OleLoanDocument currentLoanDocument) {
150         OLEDeliverNotice overdueNotice = new OLEDeliverNotice();
151         Map<String, Object> overdueMap = new HashMap<String, Object>();
152         if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.OVERDUE_NOTICE)) {
153             overdueMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.OVERDUE_NOTICE);
154         } else if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.RECALL_OVERDUE_NOTICE)) {
155             overdueMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.RECALL_OVERDUE_NOTICE);
156         }
157         overdueNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(Integer.parseInt((String) overdueMap.get(DroolsConstants.INTERVAL_TO_GENERATE_NOTICE_FOR_OVERDUE)),
158                 currentLoanDocument.getLoanDueDate(), count + 1));
159         overdueNotice.setNoticeSendType(DroolsConstants.EMAIL);
160         overdueNotice.setNoticeType(OLEConstants.OVERDUE_NOTICE);
161         overdueNotice.setPatronId(currentLoanDocument.getPatronId());
162         overdueNotice.setLoanId(currentLoanDocument.getLoanId());
163         deliverNotices.add(overdueNotice);
164     }
165 
166     private void processCourtseyNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, OleLoanDocument currentLoanDocument) {
167         OLEDeliverNotice courtseyNotice = new OLEDeliverNotice();
168         String loanId = currentLoanDocument.getLoanId();
169         courtseyNotice.setNoticeType(OLEConstants.COURTESY_NOTICE);
170         courtseyNotice.setNoticeSendType(DroolsConstants.EMAIL);
171         Map<String, Object> courtesyMap = new HashMap<String, Object>();
172         if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.COURTESY_NOTICE)) {
173             courtesyMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.COURTESY_NOTICE);
174         } else if (noticeInfo.getNoticeInfoForTypeMap().containsKey(OLEConstants.RECALL_COURTESY_NOTICE)) {
175             courtesyMap = noticeInfo.getNoticeInfoForTypeMap().get(OLEConstants.RECALL_COURTESY_NOTICE);
176         }
177 
178         courtseyNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(-Integer.parseInt((String) courtesyMap.get(DroolsConstants.INTERVAL_TO_GENERATE_NOTICE_FOR_COURTESY)),
179                 currentLoanDocument.getLoanDueDate(), 1));
180         courtseyNotice.setLoanId(loanId);
181         courtseyNotice.setPatronId(currentLoanDocument.getPatronId());
182         deliverNotices.add(courtseyNotice);
183     }
184 
185     private Timestamp calculateNoticeToBeSentDate(Integer interval, Timestamp dueDate, Integer count) {
186         Timestamp noticeToBeSentDate;
187 
188         noticeToBeSentDate = interval != null && dueDate != null ?
189                 DateUtil.addDays(dueDate, interval * count) : null;
190         return noticeToBeSentDate;
191     }
192 
193     public ItemRecord getItemRecordByBarcode(String itemBarcode) {
194         ItemRecord itemRecord = null;
195         HashMap<String, String> criteriaMap = new HashMap<>();
196         criteriaMap.put("barCode", itemBarcode);
197         List<ItemRecord> itemRecords = (List<ItemRecord>) getBusinessObjectService().findMatching(ItemRecord.class,
198                 criteriaMap);
199         if (null != itemRecords && !itemRecords.isEmpty()) {
200             itemRecord = itemRecords.get(0);
201         }
202 
203         return itemRecord;
204     }
205 
206     public String convertDateToString(Date date, String format) {
207         LOG.info("Date Format : " + format + "Date : " + date);
208         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
209         String dateValue = "";
210         try {
211             dateValue = simpleDateFormat.format(date);
212         } catch (Exception e) {
213             LOG.error(e, e);
214         }
215         LOG.info("Formatted Date : " + dateValue);
216         return dateValue;
217     }
218 
219     public String convertToString(Timestamp date) {
220         SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
221         SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
222         Date itemDate = null;
223         try {
224             itemDate = format2.parse(date.toString());
225         } catch (ParseException e) {
226             LOG.error("format string to Date " + e);
227         }
228         return format1.format(itemDate).toString();
229     }
230 
231     public String getLoginUserId() {
232         return GlobalVariables.getUserSession().getPrincipalId();
233     }
234 
235 
236     public BusinessObjectService getBusinessObjectService() {
237         if (null == businessObjectService) {
238             businessObjectService = KRADServiceLocator.getBusinessObjectService();
239         }
240         return businessObjectService;
241     }
242 
243     public CircDeskLocationResolver getCircDeskLocationResolver() {
244         return new CircDeskLocationResolver();
245     }
246 
247     public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
248         if (itemOlemlRecordProcessor == null) {
249             itemOlemlRecordProcessor = SpringContext.getBean(ItemOlemlRecordProcessor.class);
250         }
251         return itemOlemlRecordProcessor;
252     }
253 
254     public DocstoreClientLocator getDocstoreClientLocator() {
255         if (docstoreClientLocator == null) {
256             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
257         }
258         return docstoreClientLocator;
259     }
260 
261     public void setDateFormatForDocstoreDueDate(SimpleDateFormat dateFormatForDocstoreDueDate) {
262         this.dateFormatForDocstoreDueDate = dateFormatForDocstoreDueDate;
263     }
264 
265     public SimpleDateFormat getDateFormatForDocstoreDueDate() {
266         if (dateFormatForDocstoreDueDate == null) {
267             dateFormatForDocstoreDueDate = new SimpleDateFormat(CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString("info.DateFormat") + " HH:mm:ss");
268         }
269         return dateFormatForDocstoreDueDate;
270     }
271 
272 
273     public void rollBackSavedLoanRecord(String barcode) {
274         Map<String, String> criteria = new HashMap<String, String>();
275         criteria.put("itemId", barcode);
276         List<OleLoanDocument> oleLoanDocument = (List<OleLoanDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class, criteria);
277         if (oleLoanDocument.size() > 0) {
278             KRADServiceLocator.getBusinessObjectService().delete(oleLoanDocument.get(0));
279         }
280     }
281 
282     public OleLoanDocument updateLoanDocumentWithItemInformation(ItemRecord itemRecord, OleLoanDocument oleLoanDocument) {
283 
284         OleItemSearch oleItemSearch = new DocstoreUtil().getOleItemSearchListFromLocalClient(itemRecord.getItemId());
285         oleLoanDocument.setTitle(oleItemSearch.getTitle());
286         oleLoanDocument.setAuthor(oleItemSearch.getAuthor());
287         String location = oleItemSearch.getShelvingLocation().split("/")[oleItemSearch.getShelvingLocation().split("/").length - 1];
288         try {
289             getOleLoanDocumentsFromSolrBuilder().getLocationBySolr(location, oleLoanDocument);
290         } catch (Exception e) {
291             e.printStackTrace();
292         }
293         oleLoanDocument.setItemCallNumber(oleItemSearch.getCallNumber());
294         oleLoanDocument.setItemCopyNumber(oleItemSearch.getCopyNumber());
295         oleLoanDocument.setChronology(oleItemSearch.getChronology());
296         oleLoanDocument.setEnumeration(oleItemSearch.getEnumeration());
297         oleLoanDocument.setItemType(oleItemSearch.getItemType());
298         oleLoanDocument.setItemStatus(OLEConstants.ITEM_STATUS_CHECKEDOUT);
299         oleLoanDocument.setItemUuid(itemRecord.getUniqueIdPrefix() + "-" + oleItemSearch.getItemUUID());
300         oleLoanDocument.setInstanceUuid(oleItemSearch.getInstanceUUID());
301         oleLoanDocument.setBibUuid(oleItemSearch.getBibUUID());
302         return oleLoanDocument;
303     }
304 
305 
306     /**
307      * @param map
308      * @param itemUUID
309      * @param updateNulls - This indicates if null values should be updated for the corosponding parameters in SOLR.
310      * @return If SOLR update was successfull.
311      */
312     public Boolean updateItemInfoInSolr(Map map, String itemUUID, boolean updateNulls) {
313         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getExistingItemFromSolr(itemUUID);
314         if (oleItem != null) {
315             setItemInfoForUpdate(map, oleItem, updateNulls);
316             try {
317                 updateItem(oleItem);
318             } catch (Exception e) {
319                 return false;
320             }
321         }
322         return true;
323     }
324 
325     public Boolean deleteItemInfoInSolr(Map map, String itemUUID) {
326         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getExistingItemFromSolr(itemUUID);
327         if (oleItem != null) {
328             setItemInfoForDelete(map, oleItem);
329             try {
330                 updateItem(oleItem);
331             } catch (Exception e) {
332                 return false;
333             }
334         }
335         return true;
336     }
337 
338     private void setItemInfoForDelete(Map map, org.kuali.ole.docstore.common.document.content.instance.Item oleItem) {
339         if (map.keySet().contains("checkinNote"))
340             oleItem.setCheckinNote("");
341         if (map.containsKey("deleteClaimsReturn")) {
342             oleItem.setClaimsReturnedFlag(false);
343             oleItem.setClaimsReturnedNote(null);
344             oleItem.setClaimsReturnedFlagCreateDate(null);
345         }
346         if (map.containsKey("deleteDamagedItem")) {
347             oleItem.setItemDamagedStatus(false);
348             oleItem.setDamagedItemNote(null);
349         }
350         if (map.containsKey("deleteMissingPieceItem")) {
351             oleItem.setMissingPieceFlag(false);
352             oleItem.setMissingPieceFlagNote(null);
353             oleItem.setMissingPieceEffectiveDate(null);
354             oleItem.setMissingPiecesCount(null);
355         }
356     }
357 
358     private void setItemInfoForUpdate(Map map, org.kuali.ole.docstore.common.document.content.instance.Item oleItem, boolean updateNulls) {
359         String patronId = null == map.get("patronId") ? null : (String) map.get("patronId");
360         String proxyPatronId = null == map.get("proxyPatronId") ? null : (String) map.get("proxyPatronId");
361         Date itemCheckoutDateTime = null == map.get("itemCheckoutDateTime") ? null : (Date) map.get("itemCheckoutDateTime");
362         Timestamp loanDueDate = null == map.get("loanDueDate") ? null : (Timestamp) map.get("loanDueDate");
363         String numRenewals = null == map.get("numRenewals") ? null : (String) map.get("numRenewals");
364         String itemStatus = null == map.get("itemStatus") ? null : (String) map.get("itemStatus");
365         LocationsCheckinCountRecord locationsCheckinCountRecordToBeUpdated = null == map.get("locationsCheckinCountRecordToBeUpdated") ? null : (LocationsCheckinCountRecord) map.get("locationsCheckinCountRecordToBeUpdated");
366 
367         Boolean itemClaimsReturnedFlag = null == map.get("itemClaimsReturnedFlag") ? null : (Boolean) map.get("itemClaimsReturnedFlag");
368         String claimsReturnNote = null == map.get("claimsReturnNote") ? null : (String) map.get("claimsReturnNote");
369         String ClaimsReturnedDate = null == map.get("ClaimsReturnedDate") ? null : (String) map.get("ClaimsReturnedDate");
370 
371         List<ItemClaimsReturnedRecord> itemClaimsReturnedRecords = null == map.get("itemClaimsReturnedRecords") ? null : (List<ItemClaimsReturnedRecord>) map.get("itemClaimsReturnedRecords");
372 
373         String damagedItemNote = null == map.get("damagedItemNote") ? null : (String) map.get("damagedItemNote");
374         List<ItemDamagedRecord> itemDamagedRecords = null == map.get("itemDamagedRecords") ? null : (List<ItemDamagedRecord>) map.get("itemDamagedRecords");
375 
376         Boolean missingPieceItemFlag = null == map.get("missingPieceItemFlag") ? null : (Boolean) map.get("missingPieceItemFlag");
377         String missingPieceItemNote = null == map.get("missingPieceItemNote") ? null : (String) map.get("missingPieceItemNote");
378         String missingPieceItemCount = null == map.get("missingPieceItemCount") ? null : (String) map.get("missingPieceItemCount");
379         String noOfmissingPiece = null == map.get("noOfmissingPiece") ? null : (String) map.get("noOfmissingPiece");
380         String missingPieceItemDate = null == map.get("missingPieceItemDate") ? null : (String) map.get("missingPieceItemDate");
381         List<MissingPieceItemRecord> itemMissingPieceItemRecords = null == map.get("itemMissingPieceItemRecords") ? null : (List<MissingPieceItemRecord>) map.get("itemMissingPieceItemRecords");
382 
383         if (updateNulls) {
384             oleItem.setCurrentBorrower(patronId);
385             oleItem.setProxyBorrower(proxyPatronId);
386         }
387         if (null != itemCheckoutDateTime) {
388             oleItem.setCheckOutDateTime(convertDateToString(itemCheckoutDateTime, "MM/dd/yyyy HH:mm:ss"));
389         } else if (updateNulls) {
390             oleItem.setCheckOutDateTime(null);
391         }
392 
393         if (loanDueDate != null) {
394             oleItem.setDueDateTime(convertToString(loanDueDate));
395         } else if (updateNulls) {
396             oleItem.setDueDateTime("");
397         }
398 
399         if (updateNulls) {
400             oleItem.setNumberOfRenew(null == numRenewals ? 0 : Integer.parseInt(numRenewals));
401         }
402 
403         if (null != locationsCheckinCountRecordToBeUpdated) {
404             setNumberOfCirculationsCount(oleItem, locationsCheckinCountRecordToBeUpdated);
405         }
406 
407         if (null != itemStatus) {
408             ItemStatus itemSt = new ItemStatus();
409             itemSt.setCodeValue(itemStatus);
410             itemSt.setFullValue(itemStatus);
411             oleItem.setItemStatus(itemSt);
412         }
413 
414         if (CollectionUtils.isNotEmpty(itemClaimsReturnedRecords)) {
415             oleItem.setClaimsReturnedNote(claimsReturnNote);
416             oleItem.setClaimsReturnedFlagCreateDate(ClaimsReturnedDate);
417             oleItem.setClaimsReturnedFlag(itemClaimsReturnedFlag);
418             oleItem.setItemClaimsReturnedRecords(itemClaimsReturnedRecords);
419         }
420 
421         if (CollectionUtils.isNotEmpty(itemDamagedRecords)) {
422             oleItem.setDamagedItemNote(damagedItemNote);
423             oleItem.setItemDamagedStatus(true);
424             oleItem.setItemDamagedRecords(itemDamagedRecords);
425         }
426 
427         if (CollectionUtils.isNotEmpty(itemMissingPieceItemRecords)) {
428             oleItem.setMissingPieceFlagNote(missingPieceItemNote);
429             oleItem.setMissingPieceFlag(missingPieceItemFlag);
430             oleItem.setMissingPiecesCount(missingPieceItemCount);
431             oleItem.setNumberOfPieces(noOfmissingPiece);
432             oleItem.setMissingPieceEffectiveDate(missingPieceItemDate);
433             oleItem.setMissingPieceItemRecordList(itemMissingPieceItemRecords);
434         }
435     }
436 
437     private void setNumberOfCirculationsCount(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, LocationsCheckinCountRecord locationsCheckinCountRecordToBeUpdated) {
438         //TODO: We should really use the LocationsCheckinCountRecord in DocStore rather than using some intermediary pojo like CheckinLocation and then a wrapper NumberOfCirculations;
439         //TODO: Docstore needs to be fixed at some point.
440         NumberOfCirculations numberOfCirculations = new NumberOfCirculations();
441         ArrayList<CheckInLocation> checkInLocations = new ArrayList<>();
442         CheckInLocation checkInLocation = new CheckInLocation();
443         checkInLocation.setCount(locationsCheckinCountRecordToBeUpdated.getLocationCount());
444         checkInLocation.setInHouseCount(locationsCheckinCountRecordToBeUpdated.getLocationInhouseCount());
445         checkInLocation.setName(locationsCheckinCountRecordToBeUpdated.getLocationName());
446         checkInLocations.add(checkInLocation);
447         numberOfCirculations.setCheckInLocation(checkInLocations);
448         oleItem.setNumberOfCirculations(numberOfCirculations);
449     }
450 
451 
452     protected org.kuali.ole.docstore.common.document.content.instance.Item getExistingItemFromSolr(String itemUUID) {
453         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
454         try {
455             Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
456             return itemOlemlRecordProcessor.fromXML(item.getContent());
457         } catch (Exception e) {
458             e.printStackTrace();
459         }
460         return null;
461     }
462 
463 
464     public void updateItem(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
465         try {
466             String itemUuid = oleItem.getItemIdentifier();
467             String itemXmlContent = buildItemContent(oleItem);
468             Item item = new ItemOleml();
469             item.setId(itemUuid);
470             item.setContent(itemXmlContent);
471             item.setCategory(OLEConstants.WORK_CATEGORY);
472             item.setType(DocType.ITEM.getCode());
473             item.setFormat(OLEConstants.OLEML_FORMAT);
474             item.setStaffOnly(oleItem.isStaffOnlyFlag());
475             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
476         } catch (Exception e) {
477             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
478             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
479         }
480     }
481 
482 
483     public String buildItemContent(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
484         oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
485         String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
486         return itemContent;
487     }
488 
489 
490     public OleLoanDocument getLoanDocumentFromListBasedOnItemUuid(String itemUuid, List<OleLoanDocument> selectedLoanDocumentList) {
491         for (Iterator<OleLoanDocument> iterator = selectedLoanDocumentList.iterator(); iterator.hasNext(); ) {
492             OleLoanDocument oleLoanDocument = iterator.next();
493             if (oleLoanDocument.getItemUuid().equalsIgnoreCase(itemUuid)) {
494                 return oleLoanDocument;
495             }
496         }
497         return null;
498     }
499 
500     public OleLoanDocument getLoanDocumentFromListBasedOnItemBarcode(String itemBarcode, List<OleLoanDocument> selectedLoanDocumentList) {
501         for (Iterator<OleLoanDocument> iterator = selectedLoanDocumentList.iterator(); iterator.hasNext(); ) {
502             OleLoanDocument oleLoanDocument = iterator.next();
503             if (oleLoanDocument.getItemId().equalsIgnoreCase(itemBarcode)) {
504                 return oleLoanDocument;
505             }
506         }
507         return null;
508     }
509 
510 
511     public Item getItemForUpdate(Map<String, Object> parameterMap) {
512         if (parameterMap.size() > 0) {
513             Item item = null;
514             try {
515                 item = getDocstoreClientLocator().getDocstoreClient().retrieveItem((String) parameterMap.get("itemUUID"));
516                 for (Iterator<String> iterator = parameterMap.keySet().iterator(); iterator.hasNext(); ) {
517                     String key = iterator.next();
518                     if (key.equalsIgnoreCase("loanDueDate")) {
519                         Timestamp dueDate = (Timestamp) parameterMap.get(key);
520                         if (null != dueDate) {
521                             item.setField(Item.DUE_DATE_TIME, getDateFormatForDocstoreDueDate().format(dueDate));
522                         } else {
523                             item.setField(Item.DUE_DATE_TIME, null);
524                         }
525                     } else if (key.equalsIgnoreCase("numRenewals")) {
526                         item.setField(Item.NO_OF_RENEWAL, (String) parameterMap.get(key));
527                     }
528                 }
529                 return item;
530             } catch (Exception e) {
531                 e.printStackTrace();
532             }
533 
534         }
535         return null;
536     }
537 
538 
539     public Timestamp processDateAndTimeForAlterDueDate(Date loanDueDateToAlter, String loanDueDateTimeToAlter) throws Exception {
540         boolean timeFlag;
541         Timestamp timestamp;
542         SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OlePatron.PATRON_MAINTENANCE_DATE_FORMAT);
543 
544         if (org.apache.commons.lang3.StringUtils.isNotBlank(loanDueDateTimeToAlter)) {
545             String[] str = loanDueDateTimeToAlter.split(":");
546             timeFlag = validateTime(loanDueDateTimeToAlter);
547             if (timeFlag) {
548                 if (str != null && str.length <= 2) {
549                     loanDueDateTimeToAlter = loanDueDateTimeToAlter + OLEConstants.CHECK_IN_TIME_MS;
550                 }
551                 timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).format(loanDueDateToAlter).concat(" ").concat(loanDueDateTimeToAlter));
552             } else {
553                 throw new Exception("Invalid time format");
554             }
555         } else if (fmt.format(loanDueDateToAlter).compareTo(fmt.format(new Date())) == 0) {
556             timestamp = new Timestamp(new Date().getTime());
557         } else {
558             timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).format(loanDueDateToAlter).concat(" ").concat(new SimpleDateFormat("HH:mm:ss").format(new Date())));
559         }
560         return timestamp;
561     }
562 
563 
564     public boolean validateTime(String timeString) {
565         if (StringUtils.isNotBlank(timeString)) {
566             Pattern pattern;
567             Matcher matcher;
568             pattern = Pattern.compile(OLEConstants.TIME_24_HR_PATTERN);
569             matcher = pattern.matcher(timeString);
570             boolean validTime = matcher.matches();
571             return validTime;
572         } else {
573             return true;
574         }
575     }
576 
577 
578     private OleLoanDocumentsFromSolrBuilder getOleLoanDocumentsFromSolrBuilder() {
579         if (null == oleLoanDocumentsFromSolrBuilder) {
580             oleLoanDocumentsFromSolrBuilder = new OleLoanDocumentsFromSolrBuilder();
581         }
582         return oleLoanDocumentsFromSolrBuilder;
583     }
584 
585 
586     public void addToFormattedContent(StringBuilder stringBuilder, String content) {
587         if (stringBuilder.length() > 0) {
588             stringBuilder.append("<br/>").append(content);
589         } else {
590             stringBuilder.append(content);
591         }
592     }
593 
594     public void updateNoticesForLoanDocument(OleLoanDocument oleLoanDocument) {
595         ItemRecord itemRecord = getItemRecordByBarcode(oleLoanDocument.getItemId());
596         List<OLEDeliverNotice> oleDeliverNotices = processNotices(oleLoanDocument, itemRecord);
597         oleLoanDocument.setDeliverNotices(oleDeliverNotices);
598     }
599 }