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