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 final String ORDER_BY_ASC =
026 "ShoppingItem.categoryId ASC, ShoppingItem.price ASC, " +
027 "ShoppingItem.name ASC";
028
029 public static final String ORDER_BY_DESC =
030 "ShoppingItem.categoryId DESC, ShoppingItem.price DESC, " +
031 "ShoppingItem.name DESC";
032
033 public static final String[] ORDER_BY_FIELDS =
034 {"categoryId", "price", "name"};
035
036 public ItemPriceComparator() {
037 this(false);
038 }
039
040 public ItemPriceComparator(boolean ascending) {
041 _ascending = ascending;
042 }
043
044 @Override
045 public int compare(Object obj1, Object obj2) {
046 ShoppingItem item1 = (ShoppingItem)obj1;
047 ShoppingItem item2 = (ShoppingItem)obj2;
048
049 Long categoryId1 = new Long(item1.getCategoryId());
050 Long categoryId2 = new Long(item2.getCategoryId());
051
052 int value = categoryId1.compareTo(categoryId2);
053
054 if (value == 0) {
055 double price1 = (1 - item1.getDiscount()) * item1.getPrice();
056 double price2 = (1 - item2.getDiscount()) * item2.getPrice();
057
058 if (price1 < price2) {
059 value = -1;
060 }
061 else if (price1 > price2) {
062 value = 1;
063 }
064 }
065
066 if (value == 0) {
067 value = item1.getName().toLowerCase().compareTo(
068 item2.getName().toLowerCase());
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 boolean _ascending;
100
101 }