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