1
19
20 package com.liferay.util;
21
22 import com.liferay.portal.kernel.log.Log;
23 import com.liferay.portal.kernel.log.LogFactoryUtil;
24
25 import java.lang.reflect.InvocationTargetException;
26
27 import java.util.Comparator;
28
29 import org.apache.commons.beanutils.PropertyUtils;
30
31
38 public class PropertyComparator implements Comparator {
39
40 public PropertyComparator(String propertyName) {
41 this(new String[] {propertyName}, true, false);
42 }
43
44 public PropertyComparator(String[] propertyNames) {
45 this(propertyNames, true, false);
46 }
47
48 public PropertyComparator(
49 String propertyName, boolean asc, boolean caseSensitive) {
50
51 this(new String[] {propertyName}, asc, caseSensitive);
52 }
53
54 public PropertyComparator(
55 String[] propertyNames, boolean asc, boolean caseSensitive) {
56
57 _propertyNames = propertyNames;
58 _asc = asc;
59 _caseSensitive = caseSensitive;
60 }
61
62 public int compare(Object obj1, Object obj2) {
63 try {
64 for (String propertyName : _propertyNames) {
65 Object property1 = PropertyUtils.getProperty(
66 obj1, propertyName);
67 Object property2 = PropertyUtils.getProperty(
68 obj2, propertyName);
69
70 if (!_asc) {
71 Object temp = property1;
72
73 property1 = property2;
74 property2 = temp;
75 }
76
77 if (property1 instanceof String) {
78 int result = 0;
79
80 if (_caseSensitive) {
81 result = property1.toString().compareTo(
82 property2.toString());
83 }
84 else {
85 result = property1.toString().compareToIgnoreCase(
86 property2.toString());
87 }
88
89 if (result != 0) {
90 return result;
91 }
92 }
93
94 if (property1 instanceof Comparable) {
95 int result = ((Comparable)property1).compareTo(property2);
96
97 if (result != 0) {
98 return result;
99 }
100 }
101 }
102 }
103 catch (IllegalAccessException iae) {
104 _log.error(iae.getMessage());
105 }
106 catch (InvocationTargetException ite) {
107 _log.error(ite.getMessage());
108 }
109 catch (NoSuchMethodException nsme) {
110 _log.error(nsme.getMessage());
111 }
112
113 return -1;
114 }
115
116 private static Log _log = LogFactoryUtil.getLog(PropertyComparator.class);
117
118 private String[] _propertyNames;
119 private boolean _asc;
120 private boolean _caseSensitive;
121
122 }