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