1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.hr.time.util;
17
18 import java.math.BigDecimal;
19 import java.net.UnknownHostException;
20 import java.sql.Date;
21 import java.sql.Timestamp;
22 import java.text.ParseException;
23 import java.text.SimpleDateFormat;
24 import java.util.*;
25
26 import javax.servlet.http.HttpServletRequest;
27
28 import org.apache.commons.lang.StringUtils;
29 import org.apache.log4j.Logger;
30 import org.joda.time.DateTime;
31 import org.joda.time.DateTimeZone;
32 import org.joda.time.Days;
33 import org.joda.time.Interval;
34 import org.joda.time.Period;
35 import org.kuali.hr.time.assignment.Assignment;
36 import org.kuali.hr.time.calendar.CalendarEntries;
37 import org.kuali.hr.time.service.base.TkServiceLocator;
38 import org.kuali.hr.time.task.Task;
39 import org.kuali.rice.core.api.config.property.ConfigContext;
40
41 public class TKUtils {
42
43 private static final Logger LOG = Logger.getLogger(TKUtils.class);
44
45 public static java.sql.Date getCurrentDate() {
46 return getTimelessDate(null);
47 }
48
49
50
51
52
53 public static String getDayOfMonthFromDateString(String dateString) {
54 String[] date = dateString.split("/");
55 return date[1];
56 }
57
58 public static String getSystemTimeZone() {
59 String configTimezone = TimeZone.getDefault().getID();
60 if (ConfigContext.getCurrentContextConfig() != null
61 && StringUtils.isNotBlank(ConfigContext.getCurrentContextConfig().getProperty(TkConstants.ConfigSettings.KPME_SYSTEM_TIMEZONE).trim())) {
62 String tempTimeZoneId = ConfigContext.getCurrentContextConfig().getProperty(TkConstants.ConfigSettings.KPME_SYSTEM_TIMEZONE);
63
64 if (TimeZone.getTimeZone(tempTimeZoneId) != null) {
65 configTimezone = ConfigContext.getCurrentContextConfig().getProperty(TkConstants.ConfigSettings.KPME_SYSTEM_TIMEZONE);
66 } else {
67 LOG.error("Timezone set by configuration parameter " + TkConstants.ConfigSettings.KPME_SYSTEM_TIMEZONE + " is not a valid time zone id. Using the systems default time zone instead.");
68 }
69 }
70
71
72 return configTimezone;
73 }
74
75 public static DateTimeZone getSystemDateTimeZone() {
76 return DateTimeZone.forID(TKUtils.getSystemTimeZone());
77 }
78
79
80
81
82
83
84
85
86
87 public static java.sql.Date getTimelessDate(java.util.Date date) {
88 java.sql.Date jsd = null;
89 if (date == null) {
90 jsd = new java.sql.Date(System.currentTimeMillis());
91 } else {
92 jsd = new java.sql.Date(date.getTime());
93 }
94 return jsd;
95 }
96
97 public static long getDaysBetween(Calendar startDate, Calendar endDate) {
98 Calendar date = (Calendar) startDate.clone();
99 long daysBetween = 0;
100 while (date.before(endDate)) {
101 date.add(Calendar.DAY_OF_MONTH, 1);
102 daysBetween++;
103 }
104 return daysBetween;
105 }
106
107 public static long getDaysBetween(java.util.Date startDate, java.util.Date endDate) {
108 Calendar beginCal = GregorianCalendar.getInstance();
109 Calendar endCal = GregorianCalendar.getInstance();
110 beginCal.setTime(startDate);
111 endCal.setTime(endDate);
112
113 return getDaysBetween(beginCal, endCal);
114 }
115
116 public static BigDecimal getHoursBetween(long start, long end) {
117 long diff = end - start;
118 BigDecimal hrsReminder = new BigDecimal((diff / 3600000.0) % 24);
119
120 if (hrsReminder.compareTo(BigDecimal.ZERO) == 0 && diff > 0) {
121 return new BigDecimal(diff / 3600000.0).setScale(TkConstants.BIG_DECIMAL_SCALE, TkConstants.BIG_DECIMAL_SCALE_ROUNDING).abs();
122 }
123 return hrsReminder.setScale(TkConstants.BIG_DECIMAL_SCALE, TkConstants.BIG_DECIMAL_SCALE_ROUNDING).abs();
124 }
125
126
127
128 public static int getNumberOfWeeks(java.util.Date beginDate, java.util.Date endDate) {
129
130 DateTime beginTime = new DateTime(beginDate);
131 DateTime endTime = new DateTime(endDate);
132
133 int numOfDays = Days.daysBetween(beginTime, endTime).getDays();
134 int numOfWeeks = numOfDays / 7;
135 if (numOfDays % 7 != 0) {
136 numOfWeeks++;
137 }
138 return numOfWeeks;
139 }
140
141 public static String formatAssignmentKey(Long jobNumber, Long workArea, Long task) {
142 Long taskLong = task;
143 if (taskLong == null) {
144 taskLong = new Long("0");
145 }
146 return jobNumber + TkConstants.ASSIGNMENT_KEY_DELIMITER + workArea + TkConstants.ASSIGNMENT_KEY_DELIMITER + taskLong;
147 }
148
149 public static Map<String, String> formatAssignmentDescription(Assignment assignment) {
150 Map<String, String> assignmentDescriptions = new LinkedHashMap<String, String>();
151 Long task = assignment.getTask();
152 if (task == null) {
153 task = new Long("0");
154 }
155 String assignmentDescKey = formatAssignmentKey(assignment.getJobNumber(), assignment.getWorkArea(), task);
156 String assignmentDescValue = getAssignmentString(assignment);
157 assignmentDescriptions.put(assignmentDescKey, assignmentDescValue);
158
159 return assignmentDescriptions;
160 }
161
162 public static String getAssignmentString(Assignment assignment) {
163
164
165 if (assignment.getWorkAreaObj() == null
166 || assignment.getJob() == null
167 || assignment.getJobNumber() == null) {
168 return "";
169 }
170
171 String stringTemp = assignment.getWorkAreaObj().getDescription() + " : $"
172 + assignment.getJob().getCompRate().setScale(TkConstants.BIG_DECIMAL_SCALE)
173 + " Rcd " + assignment.getJobNumber() + " " + assignment.getJob().getDept();
174 if(assignment.getTask()!= null) {
175 Task aTask = TkServiceLocator.getTaskService().getTask(assignment.getTask(), assignment.getEffectiveDate());
176 if(aTask != null) {
177
178
179 if(!aTask.getDescription().equals(TkConstants.TASK_DEFAULT_DESP)) {
180 stringTemp += " " + aTask.getDescription();
181 }
182 }
183 }
184 return stringTemp;
185 }
186
187
188
189
190
191
192
193
194
195 public static List<Interval> getDaySpanForCalendarEntry(CalendarEntries calendarEntry, DateTimeZone timeZone) {
196 DateTime beginDateTime = calendarEntry.getBeginLocalDateTime().toDateTime(timeZone);
197 DateTime endDateTime = calendarEntry.getEndLocalDateTime().toDateTime(timeZone);
198
199 List<Interval> dayIntervals = new ArrayList<Interval>();
200
201 DateTime currDateTime = beginDateTime;
202 while (currDateTime.isBefore(endDateTime)) {
203 DateTime prevDateTime = currDateTime;
204 currDateTime = currDateTime.plusDays(1);
205 Interval daySpan = new Interval(prevDateTime, currDateTime);
206 dayIntervals.add(daySpan);
207 }
208
209 return dayIntervals;
210 }
211
212
213
214
215
216
217
218
219
220
221
222 public static List<Interval> getWeekIntervals(java.util.Date beginDate, java.util.Date endDate) {
223 List<Interval> intervals = new ArrayList<Interval>();
224 DateTime beginTime = new DateTime(beginDate);
225 DateTime endTime = new DateTime(endDate);
226
227 int dayIncrement = 7;
228 DateTime previous = beginTime;
229 DateTime nextTime = previous.plusDays(dayIncrement);
230 while (nextTime.isBefore(endTime)) {
231 Interval interval = new Interval(previous, nextTime);
232 intervals.add(interval);
233 previous = nextTime;
234 nextTime = previous.plusDays(dayIncrement);
235 }
236
237 if (previous.isBefore(endTime)) {
238
239 Interval interval = new Interval(previous, endTime);
240 intervals.add(interval);
241 }
242
243 return intervals;
244 }
245
246 public static long convertHoursToMillis(BigDecimal hours) {
247 return hours.multiply(TkConstants.BIG_DECIMAL_MS_IN_H, TkConstants.MATH_CONTEXT).longValue();
248 }
249
250 public static BigDecimal convertMillisToHours(long millis) {
251 return (new BigDecimal(millis)).divide(TkConstants.BIG_DECIMAL_MS_IN_H, TkConstants.MATH_CONTEXT);
252 }
253
254 public static BigDecimal convertMillisToMinutes(long millis) {
255 return (new BigDecimal(millis)).divide(TkConstants.BIG_DECIMAL_MS_IN_M, TkConstants.MATH_CONTEXT);
256 }
257
258 public static BigDecimal convertMillisToDays(long millis) {
259 BigDecimal hrs = convertMillisToHours(millis);
260 return hrs.divide(TkConstants.BIG_DECIMAL_HRS_IN_DAY, TkConstants.MATH_CONTEXT);
261 }
262
263 public static BigDecimal convertMinutesToHours(BigDecimal minutes) {
264 return minutes.divide(TkConstants.BIG_DECIMAL_60, TkConstants.MATH_CONTEXT);
265 }
266
267 public static int convertMillisToWholeDays(long millis) {
268 BigDecimal days = convertMillisToDays(millis);
269 return Integer.parseInt(days.setScale(0, BigDecimal.ROUND_UP).toString());
270 }
271
272
273
274
275
276 public static boolean isVirtualWorkDay(Calendar payCalendarStartTime) {
277 return (payCalendarStartTime.get(Calendar.HOUR_OF_DAY) != 0 || payCalendarStartTime.get(Calendar.MINUTE) != 0
278 && payCalendarStartTime.get(Calendar.AM_PM) != Calendar.AM);
279 }
280
281
282
283
284
285
286
287
288
289
290 public static Timestamp convertDateStringToTimestamp(String dateStr, String timeStr) {
291
292 String[] date = dateStr.split("/");
293 String[] time = timeStr.split(":");
294
295 DateTimeZone dtz = DateTimeZone.forID(TkServiceLocator.getTimezoneService().getUserTimezone());
296
297
298
299
300
301 DateTime dateTime = new DateTime(
302 Integer.parseInt(date[2]),
303 Integer.parseInt(date[0]),
304 Integer.parseInt(date[1]),
305 Integer.parseInt(time[0]),
306 Integer.parseInt(time[1]),
307 0, 0, dtz);
308
309 return new Timestamp(dateTime.getMillis());
310 }
311
312 public static Timestamp convertDateStringToTimestampWithoutZone(String dateStr, String timeStr) {
313
314 String[] date = dateStr.split("/");
315 String[] time = timeStr.split(":");
316
317
318
319
320
321 DateTime dateTime = new DateTime(
322 Integer.parseInt(date[2]),
323 Integer.parseInt(date[0]),
324 Integer.parseInt(date[1]),
325 Integer.parseInt(time[0]),
326 Integer.parseInt(time[1]),
327 0, 0);
328
329 return new Timestamp(dateTime.getMillis());
330 }
331
332 public static String getIPAddressFromRequest(HttpServletRequest request) {
333
334
335 String ip = request.getRemoteAddr();
336 if (ip.indexOf(':') > -1) {
337 LOG.warn("ignoring IPv6 address for clock-in: " + ip);
338 ip = "";
339 }
340
341 return ip;
342 }
343
344 public static Date createDate(int month, int day, int year, int hours, int minutes, int seconds) {
345 DateTime dt = new DateTime(year, month, day, hours, minutes, seconds, 0);
346 return new Date(dt.getMillis());
347 }
348
349 public static String getIPNumber() {
350 try {
351 return java.net.InetAddress.getLocalHost().getHostAddress();
352 } catch (UnknownHostException e) {
353 return "unknown";
354 }
355 }
356
357 public static Timestamp subtractOneSecondFromTimestamp(Timestamp originalTimestamp) {
358 DateTime dt = new DateTime(originalTimestamp);
359 dt = dt.minusSeconds(1);
360 return new Timestamp(dt.getMillis());
361 }
362
363 public static Date subtractOneMillisecondFromDate(java.util.Date date) {
364 DateTime dt = new DateTime(date);
365 dt = dt.minusMillis(1);
366 return new Date(dt.getMillis());
367 }
368
369 public static String formatDate(Date dt) {
370 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
371 return sdf.format(dt);
372 }
373
374
375 public static String formatDateTime(Timestamp timestamp){
376 Date dt = new Date(timestamp.getTime());
377 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
378 return sdf.format(dt);
379 }
380
381 public static Date formatDateString(String date){
382 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
383 try {
384 return new Date(sdf.parse(date).getTime());
385 } catch (ParseException e) {
386 return null;
387 }
388 }
389
390
391
392
393
394
395
396
397
398
399
400
401 public static String getTimezoneOffset(DateTime date) {
402 StringBuilder o = new StringBuilder();
403
404 int offsetms = date.getZone().getOffset(date);
405 boolean negative = offsetms < 0;
406 if (negative) offsetms = offsetms * -1;
407
408 Period period = new Period(offsetms);
409 if (negative) o.append('-');
410 o.append(StringUtils.leftPad(period.getHours() + "", 2, '0'));
411 o.append(StringUtils.leftPad(period.getMinutes() + "", 2, '0'));
412
413 return o.toString();
414 }
415
416 public static String arrayToString(String[] stringArray) {
417 StringBuilder str = new StringBuilder();
418 for (String string : stringArray) {
419 str.append(string);
420 }
421 return str.toString();
422 }
423
424
425
426
427 public static int getSessionTimeoutTime() {
428 return StringUtils.isBlank(ConfigContext.getCurrentContextConfig().getProperty(TkConstants.ConfigSettings.SESSION_TIMEOUT))
429 ? 2700 :
430 Integer.parseInt(ConfigContext.getCurrentContextConfig().getProperty(TkConstants.ConfigSettings.SESSION_TIMEOUT));
431 }
432
433
434
435
436
437
438
439
440
441 public static Timestamp convertDateStringToTimestamp(String dateStr) {
442
443 String[] date = dateStr.split("/");
444
445 DateTimeZone dtz = DateTimeZone.forID(TkServiceLocator.getTimezoneService().getUserTimezone());
446
447
448
449
450
451 DateTime dateTime = new DateTime(
452 Integer.parseInt(date[2]),
453 Integer.parseInt(date[0]),
454 Integer.parseInt(date[1]),
455 0, 0, 0, 0, dtz);
456
457 return new Timestamp(dateTime.getMillis());
458 }
459
460
461
462
463
464
465
466
467
468 public static Timestamp convertDateStringToTimestampNoTimezone(String dateStr) {
469
470 String[] date = dateStr.split("/");
471
472
473
474
475
476 DateTime dateTime = new DateTime(
477 Integer.parseInt(date[2]),
478 Integer.parseInt(date[0]),
479 Integer.parseInt(date[1]),
480 0, 0, 0, 0);
481
482 return new Timestamp(dateTime.getMillis());
483 }
484
485
486 public static Timestamp getCurrentTimestamp() {
487 return new Timestamp(System.currentTimeMillis());
488 }
489
490 public static List<Interval> createDaySpan(DateTime beginDateTime, DateTime endDateTime, DateTimeZone zone) {
491 beginDateTime = beginDateTime.toDateTime(zone);
492 endDateTime = endDateTime.toDateTime(zone);
493 List<Interval> dayIntervals = new ArrayList<Interval>();
494
495 DateTime currDateTime = beginDateTime;
496 while (currDateTime.isBefore(endDateTime)) {
497 DateTime prevDateTime = currDateTime;
498 currDateTime = currDateTime.plusDays(1);
499 Interval daySpan = new Interval(prevDateTime, currDateTime);
500 dayIntervals.add(daySpan);
501 }
502
503 return dayIntervals;
504 }
505
506 public static List<Interval> getDaySpanForCalendarEntry(CalendarEntries calendarEntry) {
507 return getDaySpanForCalendarEntry(calendarEntry, TkServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
508 }
509
510 public static List<Interval> getFullWeekDaySpanForCalendarEntry(CalendarEntries calendarEntry) {
511 return getFullWeekDaySpanForCalendarEntry(calendarEntry, TkServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
512 }
513
514 public static List<Interval> getFullWeekDaySpanForCalendarEntry(CalendarEntries calendarEntry, DateTimeZone timeZone) {
515 DateTime beginDateTime = calendarEntry.getBeginLocalDateTime().toDateTime(timeZone);
516 DateTime endDateTime = calendarEntry.getEndLocalDateTime().toDateTime(timeZone);
517
518 List<Interval> dayIntervals = new ArrayList<Interval>();
519
520 DateTime currDateTime = beginDateTime;
521 if (beginDateTime.getDayOfWeek() != 7) {
522 currDateTime = beginDateTime.plusDays(0 - beginDateTime.getDayOfWeek());
523 }
524
525 int afterEndDate = 6 - endDateTime.getDayOfWeek();
526 if (endDateTime.getDayOfWeek() == 7 && endDateTime.getHourOfDay() != 0) {
527 afterEndDate = 6;
528 }
529 if (endDateTime.getHourOfDay() == 0) {
530 afterEndDate += 1;
531 }
532 DateTime aDate = endDateTime.plusDays(afterEndDate);
533 while (currDateTime.isBefore(aDate)) {
534 DateTime prevDateTime = currDateTime;
535 currDateTime = currDateTime.plusDays(1);
536 Interval daySpan = new Interval(prevDateTime, currDateTime);
537 dayIntervals.add(daySpan);
538 }
539
540 return dayIntervals;
541 }
542
543 public static java.util.Date removeTime(java.util.Date date) {
544 Calendar cal = Calendar.getInstance();
545 cal.setTime(date);
546 cal.set(Calendar.HOUR_OF_DAY, 0);
547 cal.set(Calendar.MINUTE, 0);
548 cal.set(Calendar.SECOND, 0);
549 cal.set(Calendar.MILLISECOND, 0);
550 return cal.getTime();
551 }
552
553 public static int getWorkDays(java.util.Date startDate, java.util.Date endDate) {
554 int dayCounts = 0;
555 if(startDate.after(endDate)) {
556 return 0;
557 }
558 Calendar cal1 = Calendar.getInstance();
559 cal1.setTime(startDate);
560 Calendar cal2 = Calendar.getInstance();
561 cal2.setTime(endDate);
562
563 while(!cal1.after(cal2)) {
564 if(cal1.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
565 && cal1.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
566 dayCounts ++;
567 }
568 cal1.add(Calendar.DATE, 1);
569 }
570 return dayCounts;
571 }
572
573 public static boolean isWeekend(java.util.Date aDate) {
574 Calendar cal = Calendar.getInstance();
575 cal.setTime(aDate);
576 if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
577 || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
578 return true;
579 }
580 return false;
581 }
582
583 public static java.util.Date addDates(java.util.Date aDate, int aNumber) {
584 Calendar gc = new GregorianCalendar();
585 gc.setTime(aDate);
586 gc.add(Calendar.DAY_OF_YEAR, aNumber);
587 return gc.getTime();
588 }
589
590
591
592
593
594
595
596
597
598 public static String getFromDateString(String dateString) {
599 String toDateString = StringUtils.EMPTY;
600
601 if (StringUtils.startsWith(dateString, ">=")) {
602 toDateString = StringUtils.substringAfter(dateString, ">=");
603 } else if (StringUtils.contains(dateString, "..")) {
604 toDateString = StringUtils.substringBefore(dateString, "..");
605 }
606
607 return toDateString;
608 }
609
610
611
612
613
614
615
616
617
618 public static String getToDateString(String dateString) {
619 String toDateString = StringUtils.EMPTY;
620
621 if (StringUtils.startsWith(dateString, "<=")) {
622 toDateString = StringUtils.substringAfter(dateString, "<=");
623 } else if (StringUtils.contains(dateString, "..")) {
624 toDateString = StringUtils.substringAfter(dateString, "..");
625 }
626
627 return toDateString;
628 }
629
630 }