001    package org.hackystat.dailyprojectdata.resource.snapshot;
002    
003    import java.io.Serializable;
004    import java.util.Comparator;
005    
006    import javax.xml.datatype.XMLGregorianCalendar;
007    
008    import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorDataRef;
009    import org.hackystat.utilities.tstamp.Tstamp;
010    
011    /**
012     * Comparator that allows <code>SensorDataRef</code>s to be sorted by their timestamp.
013     * 
014     * @author jsakuda
015     * 
016     */
017    public class SensorDataRefComparator implements Comparator<SensorDataRef>, Serializable {
018      /** Generated serial id. */
019      private static final long serialVersionUID = -1334273923611860686L;
020    
021      /** The order of the sorting. */
022      private boolean ascending = true;
023    
024      /**
025       * Creates a new comparator.
026       * 
027       * @param ascending True if the <code>SensorDataRef</code>s are being sorted in ascending
028       *          order, otherwise false for descending.
029       */
030      public SensorDataRefComparator(boolean ascending) {
031        this.ascending = ascending;
032      }
033    
034      /**
035       * Compares two SensorDataRefs.
036       * 
037       * @param o1 The first ref.
038       * @param o2 The second ref.
039       * @return Returns -1, 0, or 1 if the first argument is less than, equal to, or greater than
040       *         the second.
041       */
042      public int compare(SensorDataRef o1, SensorDataRef o2) {
043        int result = this.compare(o1.getTimestamp(), o2.getTimestamp());
044        
045        if (!ascending) {
046          // descending sort order, change result to be in reverse order
047          result = result * -1;
048        }
049        
050        return result;
051      }
052    
053      /**
054       * Compares two timestamps.
055       * 
056       * @param cal1 The first timestamp.
057       * @param cal2 The second timestamp.
058       * @return Returns -1 if cal1 < cal2, 1 if cal1 > cal2, otherwise returns 0.
059       */
060      private int compare(XMLGregorianCalendar cal1, XMLGregorianCalendar cal2) {
061        if (Tstamp.lessThan(cal1, cal2)) {
062          return -1;
063        }
064        else if (Tstamp.greaterThan(cal1, cal2)) {
065          return 1;
066        }
067        return 0;
068      }
069    
070    }