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