001
014
015 package com.liferay.portlet.shopping.util.comparator;
016
017 import com.liferay.portal.kernel.util.OrderByComparator;
018 import com.liferay.portlet.shopping.model.ShoppingItem;
019
020
023 public class ItemPriceComparator extends OrderByComparator {
024
025 public static String ORDER_BY_ASC = "categoryId ASC, price ASC, name ASC";
026
027 public static String ORDER_BY_DESC =
028 "categoryId DESC, price DESC, name DESC";
029
030 public static String[] ORDER_BY_FIELDS = {"categoryId", "price", "name"};
031
032 public ItemPriceComparator() {
033 this(false);
034 }
035
036 public ItemPriceComparator(boolean ascending) {
037 _ascending = ascending;
038 }
039
040 public int compare(Object obj1, Object obj2) {
041 ShoppingItem item1 = (ShoppingItem)obj1;
042 ShoppingItem item2 = (ShoppingItem)obj2;
043
044 Long categoryId1 = new Long(item1.getCategoryId());
045 Long categoryId2 = new Long(item2.getCategoryId());
046
047 int value = categoryId1.compareTo(categoryId2);
048
049 if (value == 0) {
050 double price1 = (1 - item1.getDiscount()) * item1.getPrice();
051 double price2 = (1 - item2.getDiscount()) * item2.getPrice();
052
053 if (price1 < price2) {
054 value = -1;
055 }
056 else if (price1 > price2) {
057 value = 1;
058 }
059 }
060
061 if (value == 0) {
062 value = item1.getName().toLowerCase().compareTo(
063 item2.getName().toLowerCase());
064 }
065
066 if (_ascending) {
067 return value;
068 }
069 else {
070 return -value;
071 }
072 }
073
074 public String getOrderBy() {
075 if (_ascending) {
076 return ORDER_BY_ASC;
077 }
078 else {
079 return ORDER_BY_DESC;
080 }
081 }
082
083 public String[] getOrderByFields() {
084 return ORDER_BY_FIELDS;
085 }
086
087 public boolean isAscending() {
088 return _ascending;
089 }
090
091 private boolean _ascending;
092
093 }