001
014
015 package com.liferay.portlet.calendar.util.comparator;
016
017 import com.liferay.portal.kernel.util.CalendarFactoryUtil;
018 import com.liferay.portal.kernel.util.StringUtil;
019 import com.liferay.portal.kernel.util.Time;
020 import com.liferay.portlet.calendar.model.CalEvent;
021 import com.liferay.portlet.calendar.util.CalUtil;
022
023 import java.util.Calendar;
024 import java.util.Comparator;
025 import java.util.Date;
026 import java.util.Locale;
027 import java.util.TimeZone;
028
029
033 public class EventTimeComparator implements Comparator<CalEvent> {
034
035 public EventTimeComparator(TimeZone timeZone, Locale locale) {
036 _timeZone = timeZone;
037 _locale = locale;
038 }
039
040 @Override
041 public int compare(CalEvent event1, CalEvent event2) {
042 boolean allDay1 = CalUtil.isAllDay(event1, _timeZone, _locale);
043 boolean allDay2 = CalUtil.isAllDay(event2, _timeZone, _locale);
044
045 if (allDay1 && allDay2) {
046 return compareTitle(event1, event2);
047 }
048 else if (allDay1) {
049 return -1;
050 }
051 else if (allDay2) {
052 return 1;
053 }
054
055 boolean repeating = event1.isRepeating() || event2.isRepeating();
056
057 Date startDate1 = getStartDate(event1, _timeZone, repeating);
058 Date startDate2 = getStartDate(event2, _timeZone, repeating);
059
060 int value = startDate1.compareTo(startDate2);
061
062 if (value != 0) {
063 return value;
064 }
065
066 Long duration1 = getDuration(event1);
067 Long duration2 = getDuration(event2);
068
069 value = duration1.compareTo(duration2);
070
071 if (value != 0) {
072 return value;
073 }
074
075 return compareTitle(event1, event2);
076 }
077
078 protected int compareTitle(CalEvent event1, CalEvent event2) {
079 return StringUtil.toLowerCase(event1.getTitle()).compareTo(
080 StringUtil.toLowerCase(event2.getTitle()));
081 }
082
083 protected Long getDuration(CalEvent event) {
084 return (Time.HOUR * event.getDurationHour()) +
085 (Time.MINUTE * event.getDurationMinute());
086 }
087
088 protected Date getStartDate(
089 CalEvent event, TimeZone timeZone, boolean repeating) {
090
091 if (repeating) {
092
093
094
095
096 Calendar calendar = null;
097
098 if (event.isTimeZoneSensitive()) {
099 calendar = CalendarFactoryUtil.getCalendar(_timeZone);
100 }
101 else {
102 calendar = CalendarFactoryUtil.getCalendar();
103 }
104
105 calendar.setTime(event.getStartDate());
106
107 calendar.set(Calendar.MONTH, Calendar.JANUARY);
108 calendar.set(Calendar.DATE, 1);
109 calendar.set(Calendar.YEAR, 1);
110
111 return Time.getDate(calendar);
112 }
113
114 if (event.isTimeZoneSensitive()) {
115 return Time.getDate(event.getStartDate(), timeZone);
116 }
117 else {
118 return event.getStartDate();
119 }
120 }
121
122 private Locale _locale;
123 private TimeZone _timeZone;
124
125 }