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 String title1 = StringUtil.toLowerCase(event1.getTitle());
080 String title2 = StringUtil.toLowerCase(event2.getTitle());
081
082 return title1.compareTo(title2);
083 }
084
085 protected Long getDuration(CalEvent event) {
086 return (Time.HOUR * event.getDurationHour()) +
087 (Time.MINUTE * event.getDurationMinute());
088 }
089
090 protected Date getStartDate(
091 CalEvent event, TimeZone timeZone, boolean repeating) {
092
093 if (repeating) {
094
095
096
097
098 Calendar calendar = null;
099
100 if (event.isTimeZoneSensitive()) {
101 calendar = CalendarFactoryUtil.getCalendar(_timeZone);
102 }
103 else {
104 calendar = CalendarFactoryUtil.getCalendar();
105 }
106
107 calendar.setTime(event.getStartDate());
108
109 calendar.set(Calendar.MONTH, Calendar.JANUARY);
110 calendar.set(Calendar.DATE, 1);
111 calendar.set(Calendar.YEAR, 1);
112
113 return Time.getDate(calendar);
114 }
115
116 if (event.isTimeZoneSensitive()) {
117 return Time.getDate(event.getStartDate(), timeZone);
118 }
119 else {
120 return event.getStartDate();
121 }
122 }
123
124 private Locale _locale;
125 private TimeZone _timeZone;
126
127 }