001package io.ebean.meta;
002
003import java.util.Comparator;
004
005/**
006 * Comparator for timed metrics sorted by name and then count.
007 */
008public class SortMetric {
009
010  public static final Comparator<MetaCountMetric> COUNT_NAME = new CountName();
011
012  public static final Comparator<MetaTimedMetric> NAME = new Name();
013  public static final Comparator<MetaTimedMetric> COUNT = new Count();
014  public static final Comparator<MetaTimedMetric> TOTAL = new Total();
015  public static final Comparator<MetaTimedMetric> MEAN = new Mean();
016  public static final Comparator<MetaTimedMetric> MAX = new Max();
017
018  private static int stringCompare(String name, String name2) {
019    if (name == null) {
020      return name2 == null ? 0 : -1;
021    }
022    if (name2 == null) {
023      return 1;
024    }
025    return name.compareTo(name2);
026  }
027
028  /**
029   * Sort MetaCountMetric's by name.
030   */
031  public static class CountName implements Comparator<MetaCountMetric> {
032
033    @Override
034    public int compare(MetaCountMetric o1, MetaCountMetric o2) {
035      return stringCompare(o1.name(), o2.name());
036    }
037  }
038
039  /**
040   * Sort by name.
041   */
042  public static class Name implements Comparator<MetaTimedMetric> {
043
044    @Override
045    public int compare(MetaTimedMetric o1, MetaTimedMetric o2) {
046      int i = stringCompare(o1.name(), o2.name());
047      return i != 0 ? i : Long.compare(o1.count(), o2.count());
048    }
049  }
050
051  /**
052   * Sort by count desc.
053   */
054  public static class Count implements Comparator<MetaTimedMetric> {
055
056    @Override
057    public int compare(MetaTimedMetric o1, MetaTimedMetric o2) {
058      return Long.compare(o2.count(), o1.count());
059    }
060  }
061
062  /**
063   * Sort by total time desc.
064   */
065  public static class Total implements Comparator<MetaTimedMetric> {
066
067    @Override
068    public int compare(MetaTimedMetric o1, MetaTimedMetric o2) {
069      return Long.compare(o2.total(), o1.total());
070    }
071  }
072
073  /**
074   * Sort by mean desc.
075   */
076  public static class Mean implements Comparator<MetaTimedMetric> {
077
078    @Override
079    public int compare(MetaTimedMetric o1, MetaTimedMetric o2) {
080      return Long.compare(o2.mean(), o1.mean());
081    }
082  }
083
084  /**
085   * Sort by max desc.
086   */
087  public static class Max implements Comparator<MetaTimedMetric> {
088
089    @Override
090    public int compare(MetaTimedMetric o1, MetaTimedMetric o2) {
091      return Long.compare(o2.max(), o1.max());
092    }
093  }
094}