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.portal.kernel.util;
16  
17  import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
18  
19  import java.io.Serializable;
20  
21  import java.util.Comparator;
22  
23  /**
24   * <a href="OrderByComparator.java.html"><b><i>View Source</i></b></a>
25   *
26   * @author Brian Wing Shun Chan
27   * @author Shuyang Zhou
28   */
29  @SuppressWarnings("rawtypes")
30  public abstract class OrderByComparator implements Comparator, Serializable {
31  
32      public abstract int compare(Object obj1, Object obj2);
33  
34      public String getOrderBy() {
35          return null;
36      }
37  
38      public String[] getOrderByFields() {
39          String orderBy = getOrderBy();
40  
41          if (orderBy == null) {
42              return null;
43          }
44  
45          String[] parts = StringUtil.split(orderBy);
46  
47          String[] fields = new String[parts.length];
48  
49          for (int i = 0; i < parts.length; i++) {
50              String part = parts[i];
51  
52              int x = part.indexOf(CharPool.PERIOD);
53              int y = part.indexOf(CharPool.SPACE, x);
54  
55              if (y == -1) {
56                  y = part.length();
57              }
58  
59              fields[i] = part.substring(x + 1, y);
60          }
61  
62          return fields;
63      }
64  
65      public Object[] getOrderByValues(Object obj) {
66          String[] fields = getOrderByFields();
67  
68          Object[] values = new Object[fields.length];
69  
70          for (int i = 0; i< fields.length; i++) {
71              values[i] = BeanPropertiesUtil.getObject(obj, fields[i]);
72          }
73  
74          return values;
75      }
76  
77      public boolean isAscending() {
78          String orderBy = getOrderBy();
79  
80          if ((orderBy == null) ||
81              (orderBy.toUpperCase().endsWith(_ORDER_BY_DESC))) {
82  
83              return false;
84          }
85          else {
86              return true;
87          }
88      }
89  
90      public String toString() {
91          return getOrderBy();
92      }
93  
94      private static final String _ORDER_BY_DESC = " DESC";
95  
96  }