1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portlet.shopping.util.comparator;
16  
17  import com.liferay.portal.kernel.util.OrderByComparator;
18  import com.liferay.portlet.shopping.model.ShoppingItem;
19  
20  /**
21   * <a href="ItemPriceComparator.java.html"><b><i>View Source</i></b></a>
22   *
23   * @author Brian Wing Shun Chan
24   */
25  public class ItemPriceComparator extends OrderByComparator {
26  
27      public static String ORDER_BY_ASC = "categoryId ASC, price ASC, name ASC";
28  
29      public static String ORDER_BY_DESC =
30          "categoryId DESC, price DESC, name DESC";
31  
32      public static String[] ORDER_BY_FIELDS = {"categoryId", "price", "name"};
33  
34      public ItemPriceComparator() {
35          this(false);
36      }
37  
38      public ItemPriceComparator(boolean asc) {
39          _asc = asc;
40      }
41  
42      public int compare(Object obj1, Object obj2) {
43          ShoppingItem item1 = (ShoppingItem)obj1;
44          ShoppingItem item2 = (ShoppingItem)obj2;
45  
46          Long categoryId1 = new Long(item1.getCategoryId());
47          Long categoryId2 = new Long(item2.getCategoryId());
48  
49          int value = categoryId1.compareTo(categoryId2);
50  
51          if (value == 0) {
52              double price1 = (1 - item1.getDiscount()) * item1.getPrice();
53              double price2 = (1 - item2.getDiscount()) * item2.getPrice();
54  
55              if (price1 < price2) {
56                  value = -1;
57              }
58              else if (price1 > price2) {
59                  value = 1;
60              }
61          }
62  
63          if (value == 0) {
64              value = item1.getName().toLowerCase().compareTo(
65                  item2.getName().toLowerCase());
66          }
67  
68          if (_asc) {
69              return value;
70          }
71          else {
72              return -value;
73          }
74      }
75  
76      public String getOrderBy() {
77          if (_asc) {
78              return ORDER_BY_ASC;
79          }
80          else {
81              return ORDER_BY_DESC;
82          }
83      }
84  
85      public String[] getOrderByFields() {
86          return ORDER_BY_FIELDS;
87      }
88  
89      public boolean isAscending() {
90          return _asc;
91      }
92  
93      private boolean _asc;
94  
95  }