1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
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  public abstract class OrderByComparator implements Comparator, Serializable {
30  
31      public abstract int compare(Object obj1, Object obj2);
32  
33      public String getOrderBy() {
34          return null;
35      }
36  
37      public String[] getOrderByFields() {
38          String orderBy = getOrderBy();
39  
40          if (orderBy == null) {
41              return null;
42          }
43  
44          String[] parts = StringUtil.split(orderBy);
45  
46          String[] fields = new String[parts.length];
47  
48          for (int i = 0; i < parts.length; i++) {
49              String part = parts[i];
50  
51              int x = part.indexOf(StringPool.PERIOD);
52              int y = part.indexOf(StringPool.SPACE, x);
53  
54              if (y == -1) {
55                  y = part.length();
56              }
57  
58              fields[i] = part.substring(x + 1, y);
59          }
60  
61          return fields;
62      }
63  
64      public Object[] getOrderByValues(Object obj) {
65          String[] fields = getOrderByFields();
66  
67          Object[] values = new Object[fields.length];
68  
69          for (int i = 0; i< fields.length; i++) {
70              values[i] = BeanPropertiesUtil.getObject(obj, fields[i]);
71          }
72  
73          return values;
74      }
75  
76      public boolean isAscending() {
77          String orderBy = getOrderBy();
78  
79          if ((orderBy == null) ||
80              (orderBy.toUpperCase().endsWith(_ORDER_BY_DESC))) {
81  
82              return false;
83          }
84          else {
85              return true;
86          }
87      }
88  
89      public String toString() {
90          return getOrderBy();
91      }
92  
93      private static final String _ORDER_BY_DESC = " DESC";
94  
95  }