View Javadoc
1   package org.kuali.ole.deliver.calendar.service.impl;
2   
3   import org.apache.log4j.Logger;
4   import org.joda.time.Interval;
5   import org.kuali.ole.OLEConstants;
6   import org.kuali.ole.deliver.calendar.bo.*;
7   import org.kuali.ole.deliver.calendar.controller.OleCalendarController;
8   import org.kuali.ole.deliver.calendar.service.DateUtil;
9   import org.kuali.ole.deliver.calendar.service.OleCalendarService;
10  import org.kuali.ole.deliver.service.ParameterValueResolver;
11  import org.kuali.ole.deliver.util.ItemFineRate;
12  import org.kuali.rice.krad.service.BusinessObjectService;
13  import org.kuali.rice.krad.service.KRADServiceLocator;
14  import org.kuali.rice.krad.util.GlobalVariables;
15  import org.kuali.rice.krad.util.KRADConstants;
16  
17  import java.sql.Timestamp;
18  import java.util.*;
19  import java.util.concurrent.TimeUnit;
20  
21  /**
22   * Created with IntelliJ IDEA.
23   * User: arjuns
24   * Date: 7/27/13
25   * Time: 5:39 PM
26   * To change this template use File | Settings | File Templates.
27   */
28  
29  
30  public class OleCalendarServiceImpl implements OleCalendarService {
31  
32      private static final Logger LOG = Logger.getLogger(OleCalendarController.class);
33  
34      private BusinessObjectService businessObjectService;
35      private Map<String, OleCalendarGroup> calendarGroupMap;
36      private Map<String, OleCalendar> activeCalendarMap;
37  
38      public void setBusinessObjectService(BusinessObjectService businessObjectService) {
39          this.businessObjectService = businessObjectService;
40      }
41  
42      private int totalWorkingDays = 0;
43      private int totalDays = 0;
44      private ParameterValueResolver parameterValueResolver;
45  
46      public ParameterValueResolver getParameterValueResolver() {
47          if (parameterValueResolver == null) {
48              parameterValueResolver = ParameterValueResolver.getInstance();
49          }
50          return parameterValueResolver;
51      }
52  
53      public void setParameterValueResolver(ParameterValueResolver parameterValueResolver) {
54          this.parameterValueResolver = parameterValueResolver;
55      }
56  
57      public OleCalendarGroup getCalendarGroup(String deskId) {
58  
59          if(null == calendarGroupMap){
60              calendarGroupMap = new HashMap<>();
61          }
62  
63          if (!calendarGroupMap.containsKey(deskId)) {
64              HashMap criteriaMap = new HashMap();
65              criteriaMap.put(OLEConstants.CALENDER_ID, deskId);
66              List<OleCalendarGroup> oleCalendarGroupList = (List<OleCalendarGroup>) getBusinessObjectService().findMatching(OleCalendarGroup.class, criteriaMap);
67              if (oleCalendarGroupList != null && oleCalendarGroupList.size() > 0) {
68                  calendarGroupMap.put(deskId, oleCalendarGroupList.get(0));
69              }
70          }
71  
72          return calendarGroupMap.get(deskId);
73      }
74  
75  
76      @Override
77      public OleCalendar getActiveCalendar(Timestamp date, String groupId) {
78  
79          if (null == activeCalendarMap) {
80              activeCalendarMap = new HashMap<>();
81          }
82          if (!activeCalendarMap.containsKey(groupId)) {
83              HashMap criteriaMap = new HashMap();
84              criteriaMap.put(OLEConstants.CALENDER_ID, groupId);
85              List<OleCalendar> oleCalendarList = (List<OleCalendar>) getBusinessObjectService().findMatching(OleCalendar.class, criteriaMap);
86              for (OleCalendar calendar : oleCalendarList) {
87                  if (calendar.getBeginDate() != null && date != null && calendar.getEndDate() != null && isCalendarExists(calendar.getBeginDate(), calendar.getEndDate())) {
88                      calendar = continuousWeek(calendar);
89                      activeCalendarMap.put(groupId, calendar);
90                  } else if (calendar.getBeginDate() != null && calendar.getEndDate() == null) {
91                      calendar = continuousWeek(calendar);
92                      activeCalendarMap.put(groupId, calendar);
93                  }
94              }
95          }
96          return activeCalendarMap.get(groupId);
97      }
98  
99      public OleCalendar continuousWeek(OleCalendar oleCalendar) {     //each day of a week
100         int week = -1;
101         List<OleCalendarWeek> oleCalendarWeekList = new ArrayList<OleCalendarWeek>();
102         for (OleCalendarWeek oleCalendarWeek : oleCalendar.getOleCalendarWeekList()) {
103             if (!oleCalendarWeek.isEachDayWeek() && !oleCalendarWeek.getEndDay().equals(oleCalendarWeek.getStartDay())) {
104                 if (Integer.parseInt(oleCalendarWeek.getStartDay()) < Integer.parseInt(oleCalendarWeek.getEndDay())) {
105                     for (int strt = new Integer(oleCalendarWeek.getStartDay()); strt <= new Integer(oleCalendarWeek.getEndDay()); strt++) {
106                         OleCalendarWeek oleCalendarWeek1 = new OleCalendarWeek();
107                         oleCalendarWeek1.setCalendarId(oleCalendarWeek.getCalendarId());
108                         oleCalendarWeek1.setStartDay(String.valueOf(strt));
109                         oleCalendarWeek1.setEndDay(String.valueOf(strt));
110                         oleCalendarWeek1.setOpenTimeSession(oleCalendarWeek.getOpenTimeSession());
111                         oleCalendarWeek1.setCloseTimeSession(oleCalendarWeek.getCloseTimeSession());
112                         oleCalendarWeek1.setOpenTime("00:00");
113                         oleCalendarWeek1.setCloseTime("23:59");
114                         if (strt == new Integer(oleCalendarWeek.getStartDay())) {
115                             oleCalendarWeek1.setOpenTime(oleCalendarWeek.getOpenTime());
116                         } else if (strt == new Integer(oleCalendarWeek.getEndDay())) {
117                             oleCalendarWeek1.setCloseTime(oleCalendarWeek.getCloseTime());
118                         }
119                         oleCalendarWeekList.add(week + 1, oleCalendarWeek1);
120                     }
121                 } else {
122                     for (int strt = new Integer(oleCalendarWeek.getStartDay()); strt < 7; strt++) {
123                         OleCalendarWeek oleCalendarWeek1 = new OleCalendarWeek();
124                         oleCalendarWeek1.setCalendarId(oleCalendarWeek.getCalendarId());
125                         oleCalendarWeek1.setStartDay(String.valueOf(strt));
126                         oleCalendarWeek1.setEndDay(String.valueOf(strt));
127                         oleCalendarWeek1.setOpenTimeSession(oleCalendarWeek.getOpenTimeSession());
128                         oleCalendarWeek1.setCloseTimeSession(oleCalendarWeek.getCloseTimeSession());
129                         oleCalendarWeek1.setOpenTime("00:00");
130                         oleCalendarWeek1.setCloseTime("23:59");
131                         if (strt == new Integer(oleCalendarWeek.getStartDay())) {
132                             oleCalendarWeek1.setOpenTime(oleCalendarWeek.getOpenTime());
133                         } else if (strt == new Integer(oleCalendarWeek.getEndDay())) {
134                             oleCalendarWeek1.setCloseTime(oleCalendarWeek.getCloseTime());
135                         }
136                         oleCalendarWeekList.add(week + 1, oleCalendarWeek1);
137                         if (strt >= 6) {
138                             for (int end = 0; end <= new Integer(oleCalendarWeek.getEndDay()); end++) {
139                                 oleCalendarWeek1 = new OleCalendarWeek();
140                                 oleCalendarWeek1.setCalendarId(oleCalendarWeek.getCalendarId());
141                                 oleCalendarWeek1.setStartDay(String.valueOf(end));
142                                 oleCalendarWeek1.setEndDay(String.valueOf(end));
143                                 oleCalendarWeek1.setOpenTimeSession(oleCalendarWeek.getOpenTimeSession());
144                                 oleCalendarWeek1.setCloseTimeSession(oleCalendarWeek.getCloseTimeSession());
145                                 oleCalendarWeek1.setOpenTime("00:00");
146                                 oleCalendarWeek1.setCloseTime("23:59");
147                                 if (end == new Integer(oleCalendarWeek.getStartDay())) {
148                                     oleCalendarWeek1.setOpenTime(oleCalendarWeek.getOpenTime());
149                                 } else if (end == new Integer(oleCalendarWeek.getEndDay())) {
150                                     oleCalendarWeek1.setCloseTime(oleCalendarWeek.getCloseTime());
151                                 }
152                                 oleCalendarWeekList.add(week + 1, oleCalendarWeek1);
153                             }
154                         }
155                     }
156 
157                 }
158             } else {
159                 oleCalendarWeekList.add(oleCalendarWeek);
160             }
161         }
162         oleCalendar.setOleCalendarWeekList(oleCalendarWeekList);
163         for (OleCalendarExceptionPeriod oleCalendarExceptionPeriod : oleCalendar.getOleCalendarExceptionPeriodList()) {
164             int period = -1;
165             List<OleCalendarExceptionPeriodWeek> oleCalendarExceptionPeriodWeekList = new ArrayList<>();
166             for (OleCalendarExceptionPeriodWeek oleCalendarExceptionPeriodWeek : oleCalendarExceptionPeriod.getOleCalendarExceptionPeriodWeekList()) {
167                 if (!oleCalendarExceptionPeriodWeek.isEachDayOfExceptionWeek() && !oleCalendarExceptionPeriodWeek.getEndDay().equals(oleCalendarExceptionPeriodWeek.getStartDay())) {
168                     if (Integer.parseInt(oleCalendarExceptionPeriodWeek.getStartDay()) < Integer.parseInt(oleCalendarExceptionPeriodWeek.getEndDay())) {
169                         for (int strt = new Integer(oleCalendarExceptionPeriodWeek.getStartDay()); strt <= new Integer(oleCalendarExceptionPeriodWeek.getEndDay()); strt++) {
170                             OleCalendarExceptionPeriodWeek oleCalendarExceptionPeriodWeek1 = new OleCalendarExceptionPeriodWeek();
171                             oleCalendarExceptionPeriodWeek1.setStartDay(String.valueOf(strt));
172                             oleCalendarExceptionPeriodWeek1.setEndDay(String.valueOf(strt));
173                             oleCalendarExceptionPeriodWeek1.setOpenTimeSession("AM");
174                             oleCalendarExceptionPeriodWeek1.setCloseTimeSession("PM");
175                             oleCalendarExceptionPeriodWeek1.setOpenTime("00:00");
176                             oleCalendarExceptionPeriodWeek1.setCloseTime("23:59");
177                             oleCalendarExceptionPeriodWeek1.setEachDayOfExceptionWeek(true);
178                             if (strt == new Integer(oleCalendarExceptionPeriodWeek.getStartDay())) {
179                                 oleCalendarExceptionPeriodWeek1.setOpenTime(oleCalendarExceptionPeriodWeek.getOpenTime());
180                             } else if (strt == new Integer(oleCalendarExceptionPeriodWeek.getEndDay())) {
181                                 oleCalendarExceptionPeriodWeek1.setCloseTime(oleCalendarExceptionPeriodWeek.getCloseTime());
182                             }
183                             oleCalendarExceptionPeriodWeekList.add(period + 1, oleCalendarExceptionPeriodWeek1);
184                         }
185                     } else {
186                         for (int strt = new Integer(oleCalendarExceptionPeriodWeek.getStartDay()); strt < 7; strt++) {
187                             OleCalendarExceptionPeriodWeek oleCalendarExceptionPeriodWeek1 = new OleCalendarExceptionPeriodWeek();
188                             oleCalendarExceptionPeriodWeek1.setStartDay(String.valueOf(strt));
189                             oleCalendarExceptionPeriodWeek1.setEndDay(String.valueOf(strt));
190                             oleCalendarExceptionPeriodWeek1.setOpenTimeSession("AM");
191                             oleCalendarExceptionPeriodWeek1.setCloseTimeSession("PM");
192                             oleCalendarExceptionPeriodWeek1.setOpenTime("00:00");
193                             oleCalendarExceptionPeriodWeek1.setCloseTime("23:59");
194                             oleCalendarExceptionPeriodWeek1.setEachDayOfExceptionWeek(true);
195                             if (strt == new Integer(oleCalendarExceptionPeriodWeek.getStartDay())) {
196                                 oleCalendarExceptionPeriodWeek1.setOpenTime(oleCalendarExceptionPeriodWeek.getOpenTime());
197                             } else if (strt == new Integer(oleCalendarExceptionPeriodWeek.getEndDay())) {
198                                 oleCalendarExceptionPeriodWeek1.setCloseTime(oleCalendarExceptionPeriodWeek.getCloseTime());
199                             }
200                             oleCalendarExceptionPeriodWeekList.add(period + 1, oleCalendarExceptionPeriodWeek1);
201                             if (strt >= 6) {
202                                 for (int end = 0; end <= new Integer(oleCalendarExceptionPeriodWeek.getEndDay()); end++) {
203                                     oleCalendarExceptionPeriodWeek1 = new OleCalendarExceptionPeriodWeek();
204                                     oleCalendarExceptionPeriodWeek1.setStartDay(String.valueOf(strt));
205                                     oleCalendarExceptionPeriodWeek1.setEndDay(String.valueOf(strt));
206                                     oleCalendarExceptionPeriodWeek1.setOpenTimeSession("AM");
207                                     oleCalendarExceptionPeriodWeek1.setCloseTimeSession("PM");
208                                     oleCalendarExceptionPeriodWeek1.setOpenTime("00:00");
209                                     oleCalendarExceptionPeriodWeek1.setCloseTime("23:59");
210                                     oleCalendarExceptionPeriodWeek1.setEachDayOfExceptionWeek(true);
211                                     if (strt == new Integer(oleCalendarExceptionPeriodWeek.getStartDay())) {
212                                         oleCalendarExceptionPeriodWeek1.setOpenTime(oleCalendarExceptionPeriodWeek.getOpenTime());
213                                     } else if (strt == new Integer(oleCalendarExceptionPeriodWeek.getEndDay())) {
214                                         oleCalendarExceptionPeriodWeek1.setCloseTime(oleCalendarExceptionPeriodWeek.getCloseTime());
215                                     }
216                                     oleCalendarExceptionPeriodWeekList.add(period + 1, oleCalendarExceptionPeriodWeek1);
217                                 }
218                             }
219                         }
220 
221                     }
222                 } else {
223                     oleCalendarExceptionPeriodWeekList.add(oleCalendarExceptionPeriodWeek);
224                 }
225             }
226             oleCalendarExceptionPeriod.setOleCalendarExceptionPeriodWeekList(oleCalendarExceptionPeriodWeekList);
227         }
228         return oleCalendar;
229     }
230 
231     //
232     public boolean isCalendarExists(Timestamp fromDate, Timestamp toDate) {
233         Interval interval = new Interval(fromDate.getTime(), toDate.getTime());
234         return interval.contains(System.currentTimeMillis());
235     }
236 
237 
238     public boolean isHoliday(String deskId, Timestamp currentDate) {
239         OleCalendarGroup ocg = getCalendarGroup(deskId);
240         if (ocg == null)
241             return false;
242         OleCalendar oc = getActiveCalendar(currentDate, ocg.getCalendarGroupId());
243         boolean holidayExceptionType = false;
244 
245         List<OleCalendarExceptionDate> oleCalendarExceptionDates = oc != null && oc.getOleCalendarExceptionDateList() != null ? oc.getOleCalendarExceptionDateList() : new ArrayList<OleCalendarExceptionDate>();
246         for (OleCalendarExceptionDate exceptionDate : oleCalendarExceptionDates) {
247             if (exceptionDate.getExceptionType().equals(OLEConstants.CALENDAR_EXCEPTION_TYPE) && currentDate != null && currentDate.toString().split(" ")[0].equals(exceptionDate.getDate().toString().split(" ")[0])) {
248 
249                 holidayExceptionType = true;
250                 break;
251 
252             }
253         }
254         if (!holidayExceptionType) {
255             HashMap<String, String> timeMap;
256             timeMap = getOpenAndCloseTime(deskId, currentDate);
257             if (timeMap.size() != 2) {
258                 holidayExceptionType = true;
259             }
260         }
261         return holidayExceptionType;
262     }
263 
264 
265     //Due date calculation - days input
266     public Timestamp calculateDueDate(String deskId, String timePeriod, Timestamp currentDate) {
267 
268         Integer count = Integer.parseInt(timePeriod != null ? timePeriod.split("-")[0] : "0");
269         while (count > 0) {
270             boolean temp = false;
271             if (isHoliday(deskId, currentDate)) {
272                 temp = true;
273             }
274             if (temp) {
275                 currentDate = DateUtil.addDays(currentDate, 1);
276             } else {
277                 count = count - 1;
278                 currentDate = DateUtil.addDays(currentDate, 1);
279             }
280         }
281         if (isHoliday(deskId, currentDate)) {
282             currentDate = nextWorkingDay(deskId, currentDate);
283 
284         }
285         HashMap<String, String> timeMap = getOpenAndCloseTime(deskId, currentDate);
286         float openTime = 0;
287         float closeTime = 0;
288         float currentTime = 0;
289 
290         if (timeMap.size() > 0) {
291             String[] openTimes = timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME) != null ? timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":") : new String[0];
292             String openTimeHrs = openTimes.length > 0 ? openTimes[0] : null;
293             String openTimeMin = openTimes.length > 1 ? openTimes[1] : null;
294             if (openTimeHrs != null && openTimeMin != null) {
295                 openTime = Float.parseFloat(openTimeHrs + "." + openTimeMin);
296             }
297             String[] closeTimes = timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME) != null ? timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME).split(":") : new String[0];
298             String closeTimeHrs = closeTimes.length > 0 ? closeTimes[0] : null;
299             String closeTimeMin = closeTimes.length > 1 ? closeTimes[1] : null;
300             if (closeTimeHrs != null && closeTimeMin != null) {
301                 closeTime = Float.parseFloat(closeTimeHrs + "." + closeTimeMin);
302             }
303             String[] currentTimeFromDate = currentDate.toString().split(" ");
304             String[] currentTimes = currentTimeFromDate.length > 1 && currentTimeFromDate[1] != null ? currentTimeFromDate[1].split(":") : new String[0];
305             String currentTimeHrs = currentTimes.length > 0 ? currentTimes[0] : null;
306             String currentTimeMin = currentTimes.length > 1 ? currentTimes[1] : null;
307             if (currentTimeHrs != null && currentTimeMin != null) {
308                 currentTime = Float.parseFloat(currentTimeHrs + "." + currentTimeMin);
309             }
310             if (currentTime < openTime) {
311                 currentDate = Timestamp.valueOf(new StringBuilder().append(currentDate.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString());
312             } else if (currentTime > closeTime) {
313                 boolean holidayExceptionType = true;
314                 Timestamp temp;
315 
316                 int count1 = 1;
317                 while (holidayExceptionType) {
318 
319                     temp = DateUtil.addDays(currentDate, count1);
320                     timeMap = getOpenAndCloseTime(deskId, temp);
321                     holidayExceptionType = isHoliday(deskId, temp);
322                     if (holidayExceptionType == false) {
323                         timeMap = getOpenAndCloseTime(deskId, temp);
324                         currentDate = Timestamp.valueOf(new StringBuilder().append(temp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString());
325                     }
326                     count1++;
327                 }//while ends
328             } else {
329                 currentDate = Timestamp.valueOf(new StringBuilder().append(currentDate.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME)).append(":00").toString());
330             }
331 
332         }
333         return currentDate;
334 
335     }//end calculateDueDate method..
336 
337     public Timestamp nextWorkingDay(String deskId, Timestamp currentDate) {
338         boolean holidayExceptionType = true;
339         Timestamp temp;
340         int count = 1;
341         while (holidayExceptionType) {
342 
343             temp = DateUtil.addDays(currentDate, count);
344             holidayExceptionType = isHoliday(deskId, temp);
345             if (holidayExceptionType == false) {
346                 return temp;
347             }
348 
349             count++;
350 
351         }//while ends
352         return null;
353     }
354 
355     //Due date calculation - hours input
356     public Timestamp calculateDueDateHrs(String deskId, String timePeriod, Timestamp currentDate) {
357         boolean isDay = false;
358         String[] timePeriods = timePeriod.split("-");
359         String timePeriodType = timePeriods.length > 1 ? timePeriods[1] : "";
360         Timestamp destinationTimestamp = null;
361         Timestamp destinationTemp = null;
362         String sysFlag = getParameterValueResolver().getParameter(OLEConstants
363                 .APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, OLEConstants.CALENDER_FLAG);
364         if (timePeriodType != null && timePeriodType.equalsIgnoreCase("H")) {
365             destinationTemp = DateUtil.addHours(currentDate, new Integer(timePeriods.length > 0 ? timePeriods[0] : "0"));
366         }
367         if (timePeriodType != null && timePeriodType.equalsIgnoreCase("D")) {
368             isDay = true;
369             destinationTemp = DateUtil.addDays(currentDate, Integer.parseInt(timePeriods.length > 0 ? timePeriods[0] : "0"));
370         }
371         if (sysFlag.equalsIgnoreCase("true")) {
372             HashMap<String, String> timeMap = new HashMap<String, String>();
373             if (isHoliday(deskId, destinationTemp)) { //holiday
374                 destinationTemp = nextWorkingDay(deskId, destinationTemp);
375                 timeMap = getOpenAndCloseTime(deskId, destinationTemp);
376                 destinationTimestamp = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString());
377             } else {
378                 timeMap = getOpenAndCloseTime(deskId, destinationTemp);
379                 long openTime = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString()).getTime();
380                 long closeTime = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME)).append(":00").toString()).getTime();
381                 long currentTime = destinationTemp.getTime();
382                 if (currentTime < openTime) {
383                     destinationTimestamp = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString());
384                 } else if (currentTime >= openTime && currentTime <= closeTime) {
385                     if (isDay) {
386                         destinationTimestamp = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME)).append(":00").toString());
387                     } else {
388                         destinationTimestamp = destinationTemp;
389                     }
390 
391                 } else {
392                     destinationTemp = nextWorkingDay(deskId, destinationTemp);
393                     timeMap = getOpenAndCloseTime(deskId, destinationTemp);
394                     destinationTimestamp = Timestamp.valueOf(new StringBuilder().append(destinationTemp.toString().split(" ")[0]).append(" ").append(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString());
395                 }
396 
397             }
398         } else {
399             Long currentTimeMillis = currentDate.getTime();
400             Long loanHoursMillis = (Long.parseLong(timePeriod.split("-")[0])) * 60 * 60 * 1000;
401             Long currentDayStartTime;
402             Long currentDayEndTime;
403             Long workingMillisLeft;
404             Long tempLoanHoursMillis = loanHoursMillis;
405             if (!isHoliday(deskId, currentDate)) {
406                 HashMap<String, String> startEndTimeMap = getOpenAndCloseTime(deskId, currentDate);
407                 // currentDayStartTime = Timestamp.valueOf(new StringBuilder().append(currentDate.toString().split(" ")[0]).append(" ").append(startEndTimeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString()).getTime();
408                 currentDayEndTime = Timestamp.valueOf(new StringBuilder().append(currentDate.toString().split(" ")[0]).append(" ").append(startEndTimeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME)).append(":00").toString()).getTime();
409                 workingMillisLeft = currentDayEndTime - currentTimeMillis;
410                 loanHoursMillis = loanHoursMillis - workingMillisLeft;
411                 Timestamp nextDay = currentDate;
412                 if (loanHoursMillis <= 0) {
413                     nextDay = new Timestamp(currentTimeMillis + tempLoanHoursMillis);
414                 }
415                 //while ends
416                 while (loanHoursMillis > 0) {
417                     boolean holidayExceptionType = true;
418                     //   int count = 1;
419                     while (holidayExceptionType) {
420                         nextDay = DateUtil.addDays(nextDay, 1);
421                         holidayExceptionType = isHoliday(deskId, nextDay);
422                         //      count++;
423                     }
424                     startEndTimeMap = getOpenAndCloseTime(deskId, nextDay);
425                     currentDayStartTime = Timestamp.valueOf(new StringBuilder().append(nextDay.toString().split(" ")[0]).append(" ").append(startEndTimeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME)).append(":00").toString()).getTime();
426                     currentDayEndTime = Timestamp.valueOf(new StringBuilder().append(nextDay.toString().split(" ")[0]).append(" ").append(startEndTimeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME)).append(":00").toString()).getTime();
427                     workingMillisLeft = currentDayEndTime - currentDayStartTime;
428                     tempLoanHoursMillis = loanHoursMillis;
429                     loanHoursMillis = loanHoursMillis - workingMillisLeft;
430                     if (loanHoursMillis <= 0) {
431                         nextDay = new Timestamp(currentDayStartTime + tempLoanHoursMillis);
432                     }
433                 }
434                 if (nextDay != null) {
435                     destinationTimestamp = nextDay;
436                 }
437             }
438         }
439         return destinationTimestamp;
440     }
441 
442 
443     public Float calculateFine(String deskId, Timestamp dueDate, Timestamp currentDate, String fineAmount) {
444 
445         String difference = String.valueOf(currentDate.getTime() - dueDate.getTime());
446         Long diffInt = new Long(difference);
447         Float fineRate = 0.0f;
448 
449         if (diffInt > 0) {
450 
451             if (fineAmount != null && fineAmount.contains("/")) {
452                 String[] fineCal = fineAmount.split("/");
453                 String fineAmt = fineCal[0];
454                 String fineMode = fineCal[1];
455                 String sysFlag = getParameterValueResolver().getParameter(OLEConstants
456                         .APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, OLEConstants.FINE_FLAG);
457                 if (fineMode != null && fineMode.equalsIgnoreCase("H")) {
458                     Integer numberOfHours = 0;
459                     if (sysFlag.equalsIgnoreCase("true")) {
460                         numberOfHours = getHoursDiff(dueDate, currentDate);
461                     } else {
462                         numberOfHours = workingHours(deskId, dueDate, currentDate);
463                     }
464                     fineRate = numberOfHours * Float.parseFloat(fineAmt);
465                 } else if (fineMode != null && fineMode.equalsIgnoreCase("D")) {
466                     workingDays(deskId, dueDate, currentDate);
467                     if (sysFlag.equalsIgnoreCase("true")) {
468                         fineRate = totalDays * Float.parseFloat(fineAmt);
469                     } else {
470                         fineRate = totalWorkingDays * Float.parseFloat(fineAmt);
471                     }
472                 }
473             }
474         }
475         return fineRate;
476 
477     }
478 
479     public Integer getHoursDiff(java.util.Date dateOne, java.util.Date dateTwo) {
480         if (dateOne != null && dateTwo != null && dateOne.compareTo(dateTwo) <= 0) {
481             String diff = "";
482             long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
483             diff = String.format("%d", TimeUnit.MILLISECONDS.toHours(timeDiff),
484                     -TimeUnit.HOURS.toMinutes(timeDiff));
485             return new Integer(diff);
486         }
487         return 0;
488     }
489 
490     public void workingDays(String deskId, Timestamp dueDate, Timestamp currentDate) {
491         totalWorkingDays = 0;
492         totalDays = 0;
493         while (dueDate.getTime() < currentDate.getTime()) {
494             if (currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDate.toString().split(" ")[0])) {
495 
496                 break;
497             } else if (!currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDate.toString().split(" ")[0])) {
498                 boolean isHoliday = isHoliday(deskId, dueDate);
499                 if (!isHoliday) {
500                     totalWorkingDays++;
501 
502                 }
503                 totalDays++;
504                 dueDate = DateUtil.addDays(dueDate, 1);
505             }
506         }
507     }
508 
509     public Integer workingHours(String deskId, Timestamp dueDateTime, Timestamp currentDate) {
510         float totalHours = 0;
511         float openTime;
512         float closeTime;
513         int openTimeHrs;
514         int closeTimeHrs;
515         int totalHrs = 0;
516         Timestamp dueDate = dueDateTime;
517         HashMap<String, String> timeMap;
518         while (dueDate.getTime() <= currentDate.getTime() || currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDate.toString().split(" ")[0])) {
519             if (currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDate.toString().split(" ")[0])) {
520 
521                 timeMap = getOpenAndCloseTime(deskId, currentDate);
522                 openTime = Float.parseFloat(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[0] + "." + timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[1]);
523                 openTimeHrs = Integer.parseInt(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[0]);
524 
525                 if (currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDateTime.toString().split(" ")[0])) {
526                     openTime = Float.parseFloat(dueDateTime.toString().split(" ")[1].split(":")[0] + "." + dueDateTime.toString().split(" ")[1].split(":")[1]);
527                     openTimeHrs = Integer.parseInt(dueDateTime.toString().split(" ")[1].split(":")[0]);
528                 }
529                 float openTimeTemp = Float.parseFloat(currentDate.toString().split(" ")[1].split(":")[0] + "." + currentDate.toString().split(" ")[1].split(":")[1]);
530                 int openTimeHrsTemp = Integer.parseInt(currentDate.toString().split(" ")[1].split(":")[0]);
531 
532                 totalHours = totalHours + (openTimeTemp - openTime);
533                 totalHrs = totalHrs + (openTimeHrsTemp - openTimeHrs);
534                 break;
535             } else if (!currentDate.toString().split(" ")[0].equalsIgnoreCase(dueDate.toString().split(" ")[0])) {
536                 boolean isHoliday = isHoliday(deskId, dueDate);
537                 if (!isHoliday) {
538                     timeMap = getOpenAndCloseTime(deskId, dueDate);
539                     openTime = Float.parseFloat(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[0] + "." + timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[1]);
540                     closeTime = Float.parseFloat(timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME).split(":")[0] + "." + timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME).split(":")[1]);
541                     closeTimeHrs = Integer.parseInt(timeMap.get(OLEConstants.CALENDAR_GET_CLOSE_TIME).split(":")[0]);
542                     openTimeHrs = Integer.parseInt(timeMap.get(OLEConstants.CALENDAR_GET_OPEN_TIME).split(":")[0]);
543                     if (dueDate.equals(dueDateTime)) {
544                         Float currentTime = Float.parseFloat(dueDateTime.toString().split(" ")[1].split(":")[0] + "." + dueDateTime.toString().split(" ")[1].split(":")[1]);
545                         if (currentTime > openTime) {
546                             openTime = currentTime;
547                         }
548                         int currentTimeHrs = Integer.parseInt(dueDateTime.toString().split(" ")[1].split(":")[0]);
549                         if (currentTimeHrs > openTimeHrs) {
550                             openTimeHrs = currentTimeHrs;
551                         }
552                     }
553                     totalHours = totalHours + (closeTime - openTime);
554                     totalHrs = totalHrs + (closeTimeHrs - openTimeHrs);
555                 }
556                 dueDate = DateUtil.addDays(dueDate, 1);
557             }
558         }
559 
560 
561         return totalHrs;
562 
563     }
564 
565 
566     //Open and Close Time of a Date
567     public HashMap getOpenAndCloseTime(String deskId, Timestamp currentDate) {
568         HashMap<String, String> timeMap = new HashMap<>();
569         OleCalendarGroup ocg = getCalendarGroup(deskId);
570         OleCalendar calendar = getActiveCalendar(currentDate, ocg.getCalendarGroupId());
571 
572 
573         List<OleCalendarWeek> oleCalendarWeekList = calendar.getOleCalendarWeekList();
574         List<OleCalendarExceptionDate> oleCalendarExceptionDates = calendar.getOleCalendarExceptionDateList();
575         List<OleCalendarExceptionPeriod> oleCalendarExceptionPeriodList = calendar.getOleCalendarExceptionPeriodList();
576 
577         if (timeMap.size() == 0) {
578             for (OleCalendarExceptionDate exceptionDate : oleCalendarExceptionDates) {
579                 if (currentDate.toString().split(" ")[0].equals(exceptionDate.getDate().toString().split(" ")[0])) {
580                     timeMap.put(OLEConstants.CALENDAR_GET_OPEN_TIME, exceptionDate.getOpenTime());
581                     timeMap.put(OLEConstants.CALENDAR_GET_CLOSE_TIME, convertTimeInto24HrFormat(exceptionDate.getCloseTime()));
582                     break;
583                 }
584             }
585         }
586         boolean exceptionPeriodFlag = true;
587         if (timeMap.size() == 0) {
588             for (OleCalendarExceptionPeriod exceptionPeriod : oleCalendarExceptionPeriodList) {
589                 if (currentDate.getTime() >= exceptionPeriod.getBeginDate().getTime() && currentDate.getTime() <= exceptionPeriod.getEndDate().getTime()) {
590                     exceptionPeriodFlag = false;
591                     List<OleCalendarExceptionPeriodWeek> oleCalendarExceptionPeriodWeekList = exceptionPeriod.getOleCalendarExceptionPeriodWeekList();
592                     for (OleCalendarExceptionPeriodWeek exceptionPeriodWeek : oleCalendarExceptionPeriodWeekList) {
593                         int startDay = new Integer(exceptionPeriodWeek.getStartDay());
594                         int endDay = new Integer(exceptionPeriodWeek.getEndDay());
595                         //if(!exceptionPeriodWeek.isEachDayOfExceptionWeek()){
596                         if (startDay > endDay) {
597                             if ((currentDate.getDay() >= startDay && currentDate.getDay() <= 6) || (currentDate.getDay() >= 0 && currentDate.getDay() <= endDay)) {
598                                 timeMap.put(OLEConstants.CALENDAR_GET_OPEN_TIME, exceptionPeriodWeek.getOpenTime());
599                                 timeMap.put(OLEConstants.CALENDAR_GET_CLOSE_TIME, convertTimeInto24HrFormat(exceptionPeriodWeek.getCloseTime()));
600                                 break;
601                             }
602                         } else {
603                             if ((currentDate.getDay() >= startDay && currentDate.getDay() <= endDay)) {
604                                 timeMap.put(OLEConstants.CALENDAR_GET_OPEN_TIME, exceptionPeriodWeek.getOpenTime());
605                                 timeMap.put(OLEConstants.CALENDAR_GET_CLOSE_TIME, convertTimeInto24HrFormat(exceptionPeriodWeek.getCloseTime()));
606                                 break;
607                             }
608                         }  //end of else
609                     }
610                 }
611 
612 
613             }
614         }
615         if (timeMap.size() == 0 && exceptionPeriodFlag) {
616             for (OleCalendarWeek week : oleCalendarWeekList) {
617                 int startDay = new Integer(week.getStartDay());
618                 int endDay = new Integer(week.getEndDay());
619                 if (startDay > endDay) {
620                     if ((currentDate.getDay() >= startDay && currentDate.getDay() <= 6) || (currentDate.getDay() >= 0 && currentDate.getDay() <= endDay)) {
621                         timeMap.put(OLEConstants.CALENDAR_GET_OPEN_TIME, week.getOpenTime());
622                         timeMap.put(OLEConstants.CALENDAR_GET_CLOSE_TIME, convertTimeInto24HrFormat(week.getCloseTime()));
623                         break;
624                     }
625                 } else {
626                     if ((currentDate.getDay() >= startDay && currentDate.getDay() <= endDay)) {
627                         timeMap.put(OLEConstants.CALENDAR_GET_OPEN_TIME, week.getOpenTime());
628                         timeMap.put(OLEConstants.CALENDAR_GET_CLOSE_TIME, convertTimeInto24HrFormat(week.getCloseTime()));
629                         break;
630                     }
631                 }  //end of else
632             }
633         }
634 
635 
636         return timeMap;
637     }
638     //Open and Close Time of a Date
639 
640     private String convertTimeInto24HrFormat(String time) {
641         StringBuffer newTime = new StringBuffer();
642         String[] times = time.split(":");
643         if (times != null && times.length > 1 && Integer.parseInt(times[0]) == 0) {
644             newTime.append("24:" + times[1]);
645         } else {
646             newTime.append(time);
647         }
648         return newTime.toString();
649     }
650 
651     public void generalInfoValidation(OleCalendar oleCalendar, boolean isNew) {
652         List<OleCalendarWeek> oleCalendarWeekList = oleCalendar.getOleCalendarWeekList();
653 
654         //millitary format conversion
655 
656         DateUtil dateUtil = new DateUtil();
657 
658         if (oleCalendar.getCalendarGroupId().equals("")) {
659             GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "temp.group.name");//"oleCalendarGroupId"
660         }
661 
662 
663         if (oleCalendar.getOleCalendarWeekList().size() > 0) {
664 
665             for (OleCalendarWeek oleCalendarWeek : oleCalendarWeekList) {
666                 if (oleCalendarWeek.getOpenTime().equals("")) {
667                     GlobalVariables.getMessageMap().putErrorForSectionId("GeneralInfo", "temp.week.open.time");
668                 }
669                 if (oleCalendarWeek.getCloseTime().equals("")) {
670                     GlobalVariables.getMessageMap().putErrorForSectionId("GeneralInfo", "temp.week.close.time");
671                 }
672             }
673 
674             boolean repeat = false;
675 
676             List<Integer> dest = new ArrayList<>();
677             for (int i = 0; i < oleCalendarWeekList.size(); i++) {
678                 for (int x = new Integer(oleCalendarWeekList.get(i).getStartDay()); x <= new Integer(oleCalendarWeekList.get(i).getEndDay()); x++) {
679                     if (dest.size() > 0) {
680                         if (dest.contains(x)) {
681                             repeat = true;
682                             break;
683                         } else {
684                             dest.add(x);
685                         }
686                     } else {
687                         dest.add(x);
688                     }
689 
690                 }
691 
692 
693             }
694             if (repeat) {
695                 GlobalVariables.getMessageMap().putErrorForSectionId("GeneralInfo", "temp.weak.days.overlap");
696 
697             }
698 
699 //            To set exception period end date (concat with 23:59:59)
700             String excptEndDateSplit = null;
701             for (OleCalendarExceptionPeriod oleCalendarExceptionPeriod : oleCalendar.getOleCalendarExceptionPeriodList()) {
702                 if (oleCalendarExceptionPeriod.getEndDate() != null && oleCalendarExceptionPeriod.getEndDate().toString().contains(" ")) {
703                     excptEndDateSplit = oleCalendarExceptionPeriod.getEndDate().toString().split(" ")[0];
704                     oleCalendarExceptionPeriod.setEndDate(Timestamp.valueOf(excptEndDateSplit + " " + "23:59:59"));
705                 }
706             }
707 //            To set exception period end date (concat with 23:59:59)
708 
709 
710             String openTimePeriodWeek = "";
711             String closeTimePeriodWeek = "";
712             String openTimeConvExceptionDate = "";
713             String closeTimeConvExceptionDate = "";
714 
715             for (OleCalendarWeek oleCalendarWeek : oleCalendar.getOleCalendarWeekList()) {
716                 if (oleCalendarWeek.getOpenTime().equals("") || oleCalendarWeek.getCloseTime().equals("")) {
717                     break;
718                 }
719                 String openTimeWeek = oleCalendarWeek.getOpenTime() + oleCalendarWeek.getOpenTimeSession();
720                 String closeTimeWeek = oleCalendarWeek.getCloseTime() + oleCalendarWeek.getCloseTimeSession();
721                 String openTime = "";
722                 String closeTime = "";
723 
724                 try {
725                     openTime = dateUtil.convertTo24HoursFormat(openTimeWeek);
726                     closeTime = dateUtil.convertTo24HoursFormat(closeTimeWeek);
727                 } catch (java.text.ParseException e) {
728                     LOG.error("Exception while converting to 12Hours format", e);
729                 }
730 
731                 oleCalendarWeek.setOpenTime(openTime);
732                 oleCalendarWeek.setCloseTime(closeTime);
733             }
734 
735             for (OleCalendarExceptionPeriod oleCalendarExceptionPeriod : oleCalendar.getOleCalendarExceptionPeriodList()) {
736                 for (OleCalendarExceptionPeriodWeek oleCalendarExceptionPeriodWeek : oleCalendarExceptionPeriod.getOleCalendarExceptionPeriodWeekList()) {
737                     if (!oleCalendarExceptionPeriodWeek.getOpenTime().equals("") && oleCalendarExceptionPeriodWeek.getOpenTime() != null && !oleCalendarExceptionPeriodWeek.getCloseTime().equals("") && oleCalendarExceptionPeriodWeek.getCloseTime() != null) {
738                         String openTimeExceptionPeriodWeek = oleCalendarExceptionPeriodWeek.getOpenTime() + oleCalendarExceptionPeriodWeek.getOpenTimeSession();
739                         String closeTimeExceptionPeriodWeek = oleCalendarExceptionPeriodWeek.getCloseTime() + oleCalendarExceptionPeriodWeek.getCloseTimeSession();
740                         try {
741                             openTimePeriodWeek = dateUtil.convertTo24HoursFormat(openTimeExceptionPeriodWeek);
742                             closeTimePeriodWeek = dateUtil.convertTo24HoursFormat(closeTimeExceptionPeriodWeek);
743                         } catch (java.text.ParseException e) {
744                             LOG.error("Exception while converting to 12Hours format", e);
745                         }
746                         oleCalendarExceptionPeriodWeek.setOpenTime(openTimePeriodWeek);
747                         oleCalendarExceptionPeriodWeek.setCloseTime(closeTimePeriodWeek);
748                     }
749 
750                 }
751             }
752 
753             for (OleCalendarExceptionDate oleCalendarExceptionDate : oleCalendar.getOleCalendarExceptionDateList()) {
754 
755                 if ((!oleCalendarExceptionDate.getOpenTime().equals("")) && (!oleCalendarExceptionDate.getCloseTime().equals(""))) {
756                     String openTimeExceptionDate = oleCalendarExceptionDate.getOpenTime() + oleCalendarExceptionDate.getOpenTimeSession();
757                     String closeTimeExceptionDate = oleCalendarExceptionDate.getCloseTime() + oleCalendarExceptionDate.getCloseTimeSession();
758                     try {
759                         openTimeConvExceptionDate = dateUtil.convertTo24HoursFormat(openTimeExceptionDate);
760                         closeTimeConvExceptionDate = dateUtil.convertTo24HoursFormat(closeTimeExceptionDate);
761                     } catch (java.text.ParseException e) {
762                         LOG.error("Exception while converting to 12Hours format", e);
763                     }
764                     if (!oleCalendarExceptionDate.getExceptionType().equals("Holiday")) {  //changed
765                         oleCalendarExceptionDate.setOpenTime(openTimeConvExceptionDate);
766                         oleCalendarExceptionDate.setCloseTime(closeTimeConvExceptionDate);
767 
768                     }
769                 }
770 
771             }
772 
773             if (isNew) {
774                 String groupId1 = oleCalendar.getCalendarGroupId();
775                 Map map1 = new HashMap();
776                 map1.put("calendarGroupId", groupId1);
777                 Collection<OleCalendar> calendars1 = getBusinessObjectService().findMatching(OleCalendar.class, map1);
778                 Integer latestCalChrSeqNo = 0;
779                 Integer maxChrSeqNo = 0;
780                 for (OleCalendar calendar1 : calendars1) {
781                     if (calendar1.getChronologicalSequence() != null) {
782                         latestCalChrSeqNo = Integer.parseInt(calendar1.getChronologicalSequence());
783                         maxChrSeqNo = Math.max(maxChrSeqNo, latestCalChrSeqNo);
784                     }
785                 }
786 
787                 map1.put("chronologicalSequence", maxChrSeqNo.toString());
788                 List<OleCalendar> calendars2 = (List<OleCalendar>) getBusinessObjectService().findMatching(OleCalendar.class, map1);
789                 OleCalendar lastCalendar = calendars2 != null && calendars2.size() > 0 ? calendars2.get(0) : null;
790                 if (oleCalendar != null && oleCalendar.getBeginDate() != null && lastCalendar != null && lastCalendar.getBeginDate() != null &&
791                         oleCalendar.getBeginDate().compareTo(lastCalendar.getBeginDate()) <= 0) {
792                     GlobalVariables.getMessageMap().putErrorForSectionId("GeneralInfo", "temp.strt.end.date.new.cal");
793                 }
794             }
795         }
796         /*chronologicalSequence strt*/
797         Map<String, String> criteria = new HashMap<>();
798         int seq = 0;
799 
800         criteria.put("calendarGroupId", oleCalendar.getCalendarGroupId());
801         List<OleCalendar> oleCalendarGroups = (List<OleCalendar>) getBusinessObjectService().findMatching(OleCalendar.class, criteria);
802         if (oleCalendarGroups.size() > 0) {
803             //int high=0;
804             for (int i = 0; i < oleCalendarGroups.size(); i++) {
805                 if (seq == 0) {
806                     seq = new Integer(oleCalendarGroups.get(i).getChronologicalSequence());
807                 } else {
808                     if (seq < new Integer(oleCalendarGroups.get(i).getChronologicalSequence())) {
809                         seq = new Integer(oleCalendarGroups.get(i).getChronologicalSequence());
810                     }
811                 }
812             }
813             if (oleCalendar.getChronologicalSequence() == null || oleCalendar.getChronologicalSequence().equals("")) {
814                 oleCalendar.setChronologicalSequence(new StringBuilder().append(seq + 1).toString());
815             }
816 
817         } else {
818 
819             oleCalendar.setChronologicalSequence(new StringBuilder().append(seq + 1).toString());
820         }
821         /*chronologicalSequence end*/
822     }
823 
824     public BusinessObjectService getBusinessObjectService() {
825         if (this.businessObjectService == null) {
826             this.businessObjectService = KRADServiceLocator.getBusinessObjectService();
827         }
828         return this.businessObjectService;
829     }
830 
831     public void assignEndDate(OleCalendar oleCalendar) {
832 
833         if (GlobalVariables.getMessageMap().getErrorMessages().isEmpty()) {
834 
835             //*-*-*-Setting End-Date of a calendar while adding a new Calendar*-*-*-
836             Date endDate = DateUtil.addDays(oleCalendar.getBeginDate(), -1);
837             String groupId = oleCalendar.getCalendarGroupId();
838             Map map = new HashMap();
839             map.put("calendarGroupId", groupId);
840             Collection<OleCalendar> calendars = getBusinessObjectService().findMatching(OleCalendar.class, map);
841             Integer latestCalChrSeqNo = 0;
842             Integer maxChrSeqNo = 0;
843 
844             for (OleCalendar calendar1 : calendars) {
845                 if (calendar1.getChronologicalSequence() != null) {
846                     latestCalChrSeqNo = Integer.parseInt(calendar1.getChronologicalSequence());
847                     maxChrSeqNo = Math.max(maxChrSeqNo, latestCalChrSeqNo);
848                 }
849             }
850 
851             for (OleCalendar calendar : calendars) {
852                 if (oleCalendar.getCalendarId() != null && oleCalendar.getCalendarId().equals(calendar.getCalendarId())) {
853                     break;
854                 }
855                 if ((oleCalendar.getCalendarId() == null || !oleCalendar.getCalendarId().equals(calendar.getCalendarId()))
856                         && calendar.getCalendarGroupId().equalsIgnoreCase(groupId) && (maxChrSeqNo == 0 || maxChrSeqNo == Integer.parseInt(calendar.getChronologicalSequence()))) {
857                     String endDateSplit = null;
858                     if (endDate != null) {
859                         if (endDate.toString().contains(" ")) {
860 
861                             endDateSplit = endDate.toString().split(" ")[0];
862                         }
863 
864 
865                     }
866                     calendar.setEndDate(Timestamp.valueOf(endDateSplit + " " + "23:59:59"));
867                     getBusinessObjectService().save(calendar);
868                 }
869             }
870         }
871     }
872 
873     public void convert12HrsFormat(OleCalendar oldCalendar) {
874         DateUtil dateUtil = new DateUtil();
875         for (OleCalendarWeek oldCalendarWeek : oldCalendar.getOleCalendarWeekList()) {
876 
877             if (oldCalendarWeek.getOpenTime().equals("") || oldCalendarWeek.getCloseTime().equals("")) {
878                 break;
879             }
880             String convertedOpenTime = "";
881             String convertCloseTime = "";
882             String oleOpenTime = oldCalendarWeek.getOpenTime();
883             String oleCloseTime = oldCalendarWeek.getCloseTime();
884             try {
885                 convertedOpenTime = dateUtil.convertTo12HoursFormat(oleOpenTime);
886                 convertCloseTime = dateUtil.convertTo12HoursFormat(oleCloseTime);
887             } catch (java.text.ParseException e) {
888                 LOG.error("Exception while converting to 12Hours format", e);
889             }
890 
891             if (convertedOpenTime != null) {
892                 oldCalendarWeek.setOpenTime(convertedOpenTime.substring(0, convertedOpenTime.length() - 2));
893                 //oldCalendarWeek.setOpenTimeSession(convertedOpenTime.substring(convertedOpenTime.length() - 2, convertedOpenTime.length()));
894             }
895             if (convertCloseTime != null) {
896                 // oldCalendarWeek.setCloseTimeSession(convertCloseTime.substring(convertCloseTime.length() - 2, convertCloseTime.length()));
897                 oldCalendarWeek.setCloseTime(convertCloseTime.substring(0, convertCloseTime.length() - 2));
898             }
899         }
900 
901 
902         for (OleCalendarExceptionPeriod oleCalendarExceptionPeriod : oldCalendar.getOleCalendarExceptionPeriodList()) {
903             //changed
904             for (OleCalendarExceptionPeriodWeek oleCalendarExceptionPeriodWeek : oleCalendarExceptionPeriod.getOleCalendarExceptionPeriodWeekList()) {
905                 if (!oleCalendarExceptionPeriodWeek.getOpenTime().equals("") && oleCalendarExceptionPeriodWeek.getOpenTime() != null && !oleCalendarExceptionPeriodWeek.getCloseTime().equals("") && oleCalendarExceptionPeriodWeek.getCloseTime() != null) {
906                     String convOpenTimeExcptPrdWk = "";
907                     String convCloseTimeExcptPrdWk = "";
908                     String oleOpenTimeExcptPrdWk = oleCalendarExceptionPeriodWeek.getOpenTime();
909                     String oleCloseTimeExcptPrdWk = oleCalendarExceptionPeriodWeek.getCloseTime();
910                     try {
911                         convOpenTimeExcptPrdWk = dateUtil.convertTo12HoursFormat(oleOpenTimeExcptPrdWk);
912                         convCloseTimeExcptPrdWk = dateUtil.convertTo12HoursFormat(oleCloseTimeExcptPrdWk);
913                     } catch (java.text.ParseException e) {
914                         LOG.error("Exception while converting to 12Hours format", e);
915                     }
916 
917                     if (convOpenTimeExcptPrdWk != null) {
918                         oleCalendarExceptionPeriodWeek.setOpenTime(convOpenTimeExcptPrdWk.substring(0, convOpenTimeExcptPrdWk.length() - 2));
919                         //oleCalendarExceptionPeriodWeek.setOpenTimeSession(convOpenTimeExcptPrdWk.substring(convOpenTimeExcptPrdWk.length() - 2, convOpenTimeExcptPrdWk.length()));
920                     }
921                     if (convCloseTimeExcptPrdWk != null) {
922                         // oleCalendarExceptionPeriodWeek.setCloseTimeSession(convCloseTimeExcptPrdWk.substring(convCloseTimeExcptPrdWk.length() - 2, convCloseTimeExcptPrdWk.length()));
923                         oleCalendarExceptionPeriodWeek.setCloseTime(convCloseTimeExcptPrdWk.substring(0, convCloseTimeExcptPrdWk.length() - 2));
924                     }
925                 }
926 
927             }
928         }
929 
930 
931         for (OleCalendarExceptionDate oleCalendarExceptionDate : oldCalendar.getOleCalendarExceptionDateList()) {
932             String convertedOpenTimeExcptDate = "";
933             String convertedCloseTimeExcptDate = "";
934             String oleOpenTimeExcptDate = oleCalendarExceptionDate.getOpenTime();
935             String oleCloseTimeExcptDate = oleCalendarExceptionDate.getCloseTime();
936             if ((!oleCalendarExceptionDate.getOpenTime().equals("")) && (!oleCalendarExceptionDate.getCloseTime().equals(""))) { //changed
937                 try {
938                     convertedOpenTimeExcptDate = dateUtil.convertTo12HoursFormat(oleOpenTimeExcptDate);
939                     convertedCloseTimeExcptDate = dateUtil.convertTo12HoursFormat(oleCloseTimeExcptDate);
940                 } catch (java.text.ParseException e) {
941                     LOG.error("Exception while converting to 12Hours format", e);  //To change body of catch statement use File | Settings | File Templates.
942                 }
943 
944                 if (convertedOpenTimeExcptDate != null) {
945                     oleCalendarExceptionDate.setOpenTime(convertedOpenTimeExcptDate.substring(0, convertedOpenTimeExcptDate.length() - 2));
946                     //  oleCalendarExceptionDate.setOpenTimeSession(convertedOpenTimeExcptDate.substring(convertedOpenTimeExcptDate.length() - 2, convertedOpenTimeExcptDate.length()));
947                 }
948                 if (convertedCloseTimeExcptDate != null) {
949                     //  oleCalendarExceptionDate.setCloseTimeSession(convertedCloseTimeExcptDate.substring(convertedCloseTimeExcptDate.length() - 2, convertedCloseTimeExcptDate.length()));
950                     oleCalendarExceptionDate.setCloseTime(convertedCloseTimeExcptDate.substring(0, convertedCloseTimeExcptDate.length() - 2));
951                 }
952             }
953         }
954     }
955 
956     public void validateCalendarDocument(OleCalendar oleCalendar) {
957         oleCalendar.setEndDateNoMessage(null);
958         oleCalendar.setEndDateYesMessage(null);
959         oleCalendar.setEndDateYesFlag(false);
960         oleCalendar.setEndDateNoFlag(false);
961         oleCalendar.setMessage("");
962         OleCalendar calendar = null;
963         String groupId = oleCalendar.getCalendarGroupId();
964         Map map = new HashMap();
965         map.put("calendarGroupId", groupId);
966         Collection<OleCalendar> calendars = getBusinessObjectService().findMatching(OleCalendar.class, map);
967         int cseq = 0;
968         for (OleCalendar oleCalendar1 : calendars) {
969             if (cseq < Integer.parseInt(oleCalendar1.getChronologicalSequence())) {
970                 cseq = Integer.parseInt(oleCalendar1.getChronologicalSequence());
971             }
972         }
973         if (oleCalendar.getCalendarId() != null && !oleCalendar.getCalendarId().equals("") && oleCalendar.getChronologicalSequence() != null && !oleCalendar.getChronologicalSequence().equals("")) { //for edit
974             Map calMap = new HashMap();
975             calMap.put("calendarId", oleCalendar.getCalendarId());
976             calendar = getBusinessObjectService().findByPrimaryKey(OleCalendar.class, calMap);
977             String beginDate = null;
978             String beginDateDataBase = null;
979             String endDate = null;
980             String endDateDataBase = null;
981             if (cseq != Integer.parseInt(oleCalendar.getChronologicalSequence())) {
982                 if (oleCalendar.getEndDate() != null && oleCalendar.getEndDate().toString().contains(" ")) {
983                     endDate = oleCalendar.getEndDate().toString().split(" ")[0];
984                 }
985                 if (oleCalendar.getBeginDate() != null && oleCalendar.getBeginDate().toString().contains(" ")) {
986                     beginDate = oleCalendar.getBeginDate().toString().split(" ")[0];
987                 }
988                 if (calendar.getEndDate() != null && calendar.getEndDate().toString().contains(" ")) {
989                     endDateDataBase = calendar.getEndDate().toString().split(" ")[0];
990                 }
991                 if (calendar.getBeginDate() != null && calendar.getBeginDate().toString().contains(" ")) {
992                     beginDateDataBase = calendar.getBeginDate().toString().split(" ")[0];
993                 }
994                 if (beginDate != null && beginDateDataBase != null && !beginDate.equals(beginDateDataBase)) {
995                     oleCalendar.setMessage("This Calendar End-Date cannot be edited");
996                 }
997                 if (endDate != null && endDateDataBase != null && !endDate.equals(endDateDataBase)) {
998                     oleCalendar.setMessage("This Calendar End-Date cannot be edited");
999                 }
1000             }
1001             if (oleCalendar.getMessage().equals("This Calendar End-Date cannot be edited")) {
1002 
1003                 oleCalendar.setBeginDate(calendar.getBeginDate());
1004                 oleCalendar.setEndDate(calendar.getEndDate());
1005 
1006             }
1007         }
1008 
1009         if (oleCalendar.getChronologicalSequence() != null && !oleCalendar.getChronologicalSequence().equals("") && oleCalendar.getEndDate() != null) {
1010             if (cseq == 0 || cseq == Integer.parseInt(oleCalendar.getChronologicalSequence())) {
1011                 oleCalendar.setEndDateYesMessage("By entering an End Date this calendar will become inactive and there is no future calendar.");
1012                 oleCalendar.setEndDateYesFlag(true);
1013             }
1014         }
1015         if (oleCalendar.getChronologicalSequence().equals("") && oleCalendar.getEndDate() != null) {
1016             oleCalendar.setEndDateYesMessage("By entering an End Date this calendar will become inactive and there is no future calendar.");
1017             oleCalendar.setEndDateYesFlag(true);
1018         }
1019 
1020         if (calendars.size() >= 1 && (oleCalendar.getCalendarId() == null || oleCalendar.getCalendarId().equals(""))) {
1021             oleCalendar.setEndDateNoMessage("The Previous calendars End-Date will be changed to ensure no gaps are created.");
1022             oleCalendar.setEndDateNoFlag(true);
1023         }
1024     }
1025 
1026     public void deleteCalendarDocument(OleCalendar oleCalendar) {
1027         OleCalendar prevCalendar;
1028         OleCalendar nextCalendar;
1029         try {
1030             if (oleCalendar != null && oleCalendar.getCalendarId() != null) {
1031                 Map map = new HashMap<>();
1032                 map.put("calendarGroupId", oleCalendar.getCalendarGroupId());
1033                 List<OleCalendar> calendars = (List<OleCalendar>) getBusinessObjectService().findMatchingOrderBy(OleCalendar.class, map, "CL_SEQ", true);
1034                 for (int i = 0; i < calendars.size(); i++) {
1035                     OleCalendar calendar = calendars.get(i);
1036                     if (calendar.getChronologicalSequence().equalsIgnoreCase(oleCalendar.getChronologicalSequence())) {
1037 
1038                         prevCalendar = (i - 1) >= 0 ? calendars.get(i - 1) : null;
1039                         nextCalendar = (i + 1) < calendars.size() ? calendars.get(i + 1) : null;
1040                         if (nextCalendar == null && prevCalendar != null) {
1041                             prevCalendar.setEndDate(null);
1042                             getBusinessObjectService().save(prevCalendar);
1043                         } else if (nextCalendar != null && prevCalendar != null) {
1044                             Timestamp prevCalNewEndDate = DateUtil.addDays(nextCalendar.getBeginDate(), -1);
1045                             prevCalendar.setEndDate(prevCalNewEndDate);
1046                             getBusinessObjectService().save(prevCalendar);
1047                         }
1048 
1049                     }
1050                 }
1051                 getBusinessObjectService().delete(oleCalendar);
1052             } else {
1053                 GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_MESSAGES, OLEConstants.OlePatron.ERROR_PATRON_NOT_FOUND);
1054             }
1055         } catch (Exception ex) {
1056             LOG.error(ex.getMessage(), ex);
1057             throw new RuntimeException();
1058         }
1059     }
1060 
1061     public Double calculateOverdueFine(String deskId, Timestamp dueDate, Timestamp checkInDate, ItemFineRate itemFineRate) {
1062 
1063         String difference = String.valueOf(checkInDate.getTime() - dueDate.getTime());
1064         Long diffInt = new Long(difference);
1065         Double fine = 0.0;
1066 
1067         if (diffInt > 0) {
1068             Double rateOfFine = itemFineRate.getFineRate();
1069             String fineMode = itemFineRate.getInterval();
1070             String sysFlag = getParameterValueResolver().getParameter(OLEConstants
1071                     .APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, OLEConstants.FINE_FLAG);
1072             if (fineMode != null && fineMode.equalsIgnoreCase("H")) {
1073                 Integer numberOfHours = 0;
1074                 if (sysFlag.equalsIgnoreCase("true")) {
1075                     numberOfHours = getHoursDiff(dueDate, checkInDate);
1076                 } else {
1077                     numberOfHours = workingHours(deskId, dueDate, checkInDate);
1078                 }
1079                 fine = numberOfHours * rateOfFine;
1080             } else if (fineMode != null && fineMode.equalsIgnoreCase("D")) {
1081                 workingDays(deskId, dueDate, checkInDate);
1082                 if (sysFlag.equalsIgnoreCase("true")) {
1083                     fine = totalDays * rateOfFine;
1084                 } else {
1085                     fine = totalWorkingDays * rateOfFine;
1086                 }
1087             }
1088         }
1089         return fine;
1090 
1091     }
1092 }