1 | |
package org.kuali.rice.krms.framework.engine.expression; |
2 | |
|
3 | |
import org.apache.commons.lang.ObjectUtils; |
4 | |
import org.kuali.rice.krms.api.engine.IncompatibleTypeException; |
5 | |
|
6 | 0 | public enum ComparisonOperator { |
7 | |
|
8 | 0 | EQUALS("="), |
9 | 0 | NOT_EQUALS("!="), |
10 | 0 | GREATER_THAN(">"), |
11 | 0 | GREATER_THAN_EQUAL(">="), |
12 | 0 | LESS_THAN("<"), |
13 | 0 | LESS_THAN_EQUAL("<="); |
14 | |
|
15 | |
private final String code; |
16 | |
|
17 | 0 | private ComparisonOperator(String code) { |
18 | 0 | this.code = code; |
19 | 0 | } |
20 | |
|
21 | |
public String getCode() { |
22 | 0 | return code; |
23 | |
} |
24 | |
|
25 | |
public static ComparisonOperator fromCode(String code) { |
26 | 0 | if (code == null) { |
27 | 0 | return null; |
28 | |
} |
29 | 0 | for (ComparisonOperator comparisonOperator : values()) { |
30 | 0 | if (comparisonOperator.code.equals(code)) { |
31 | 0 | return comparisonOperator; |
32 | |
} |
33 | |
} |
34 | 0 | throw new IllegalArgumentException("Failed to locate the ComparisionOperator with the given code: " + code); |
35 | |
} |
36 | |
|
37 | |
public boolean compare(Object lhs, Object rhs) { |
38 | |
|
39 | |
|
40 | |
|
41 | |
|
42 | |
|
43 | 0 | if (lhs != null && rhs != null && !lhs.getClass().equals(rhs.getClass())) { |
44 | 0 | throw new IncompatibleTypeException("Could not compare values for operator " + this, lhs, rhs.getClass()); |
45 | |
} |
46 | |
|
47 | 0 | if (this == EQUALS) { |
48 | 0 | return ObjectUtils.equals(lhs, rhs); |
49 | 0 | } else if (this == NOT_EQUALS) { |
50 | 0 | return ObjectUtils.notEqual(lhs, rhs); |
51 | 0 | } else if (lhs == null || rhs == null) { |
52 | |
|
53 | 0 | return false; |
54 | |
} |
55 | 0 | if (lhs instanceof Comparable && rhs instanceof Comparable) { |
56 | |
|
57 | |
|
58 | |
|
59 | |
|
60 | 0 | int result = ((Comparable)lhs).compareTo(rhs); |
61 | 0 | if (this == GREATER_THAN) { |
62 | 0 | return result > 0; |
63 | |
} |
64 | 0 | if (this == GREATER_THAN_EQUAL) { |
65 | 0 | return result >= 0; |
66 | |
} |
67 | 0 | if (this == LESS_THAN) { |
68 | 0 | return result < 0; |
69 | |
} |
70 | 0 | if (this == LESS_THAN_EQUAL) { |
71 | 0 | return result <= 0; |
72 | |
} |
73 | 0 | } else { |
74 | 0 | throw new IncompatibleTypeException("Could not compare values, they are not comparable for operator " + this, lhs, rhs.getClass()); |
75 | |
} |
76 | 0 | throw new IllegalStateException("Invalid operator detected: " + this); |
77 | |
} |
78 | |
|
79 | |
} |