package com.onaro.util.jfc.date;
import java.util.*;
/**
* Time filter for "last-week" and "last-month". This is a relative time filter
* that its start-time is relative to the time when it was requested.
*/
public class TimeFilterLast implements TimeFilter {
/**
* Start-time fields that are zeroed.
*/
private static final int FIELDS_TO_CLEAN[] = new int[] {
Calendar.MILLISECOND,
Calendar.SECOND,
Calendar.MINUTE,
Calendar.HOUR_OF_DAY,
};
/**
* The time field to role back when the start date is requested.
*/
private int field;
/**
* Sets the time field that is subtructed from the current time to get the
* start-time.
* @param field Calendar.WEEK_OF_MONTH
field == Calendar.MONTH
only
*/
public TimeFilterLast(int field) {
assert field == Calendar.WEEK_OF_MONTH || field == Calendar.MONTH : "Wrong field value " + field; //$NON-NLS-1$
this.field = field;
}
/**
* Gets the start time by subtracting a whole unit of the selcted time-field
* from the current time and zeroeing unimportant time fields.
* @return the start-time
*/
public Date getStartTime() {
Calendar start = new GregorianCalendar();
for (int i = 0; i < FIELDS_TO_CLEAN.length; ++i) {
start.set(FIELDS_TO_CLEAN[i], 0);
}
switch (field) {
case Calendar.WEEK_OF_MONTH: /** Last week */
start.add(Calendar.WEEK_OF_MONTH, -1);
break;
case Calendar.MONTH: /** Last month */
start.add(Calendar.MONTH, -1);
break;
default:
//do nothing
}
return start.getTime();
}
public Date getEndTime() {
return new Date();
}
public String toString() {
StringBuilder s = new StringBuilder("TimeFilterLast"); //$NON-NLS-1$
s.append("[field=").append(field); //$NON-NLS-1$
s.append(", startTime=").append(getStartTime()).append(']'); //$NON-NLS-1$
return s.toString();
}
/**
* Test if two filters are equal. Used to prevent unneeded server request if the
* filter didn't really changed.
* @param obj the other filter
* @return true if the filters have thesame absolute start time
*/
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof TimeFilterLast)) {
return false;
}
TimeFilterLast other = (TimeFilterLast)obj;
return field == other.field;
}
public int hashCode() {
return field;
}
}