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 {
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(Object obj1, Object obj2) {
047 ShoppingItem item1 = (ShoppingItem)obj1;
048 ShoppingItem item2 = (ShoppingItem)obj2;
049
050 Long categoryId1 = new Long(item1.getCategoryId());
051 Long categoryId2 = new Long(item2.getCategoryId());
052
053 int value = categoryId1.compareTo(categoryId2);
054
055 if (value == 0) {
056 double price1 = (1 - item1.getDiscount()) * item1.getPrice();
057 double price2 = (1 - item2.getDiscount()) * item2.getPrice();
058
059 if (price1 < price2) {
060 value = -1;
061 }
062 else if (price1 > price2) {
063 value = 1;
064 }
065 }
066
067 if (value == 0) {
068 value = StringUtil.toLowerCase(item1.getName()).compareTo(
069 StringUtil.toLowerCase(item2.getName()));
070 }
071
072 if (_ascending) {
073 return value;
074 }
075 else {
076 return -value;
077 }
078 }
079
080 @Override
081 public String getOrderBy() {
082 if (_ascending) {
083 return ORDER_BY_ASC;
084 }
085 else {
086 return ORDER_BY_DESC;
087 }
088 }
089
090 @Override
091 public String[] getOrderByFields() {
092 return ORDER_BY_FIELDS;
093 }
094
095 @Override
096 public boolean isAscending() {
097 return _ascending;
098 }
099
100 private boolean _ascending;
101
102 }