1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springmodules.validation.valang.predicates;
18
19 import java.math.BigDecimal;
20 import java.util.Date;
21
22 import org.springmodules.validation.valang.ValangException;
23 import org.springmodules.validation.valang.functions.Function;
24
25
26 /**
27 * Base class for comparing less than and greater than comparisons.
28 *
29 * @author David Winterfeldt
30 */
31 public abstract class AbstractCompareTestPredicate extends AbstractPropertyPredicate {
32
33 private final String operatorSymbol;
34
35 /**
36 * <p>Constructor taking two functions and an operator.
37 *
38 * @param leftFunction the left function
39 * @param operator the operator.
40 */
41 public AbstractCompareTestPredicate(Function leftFunction, Operator operator, Function rightFunction,
42 int line, int column, String operatorSymbol) {
43 super(leftFunction, operator, rightFunction, line, column);
44 this.operatorSymbol = operatorSymbol;
45 }
46
47
48 /**
49 * <p>The evaluate method takes the result of both functions and tests with the operator.
50 *
51 * @param target The target bean.
52 * @return boolean Whether or not the test passed.
53 */
54 public final boolean evaluate(Object target) {
55
56 Object leftValue = getLeftFunction().getResult(target);
57 Object rightValue = (getRightFunction() != null ? getRightFunction().getResult(target) : null);
58
59 if (leftValue instanceof Number && rightValue instanceof Number) {
60 if (!(leftValue instanceof BigDecimal)) {
61 leftValue = new BigDecimal(leftValue.toString());
62 }
63 if (!(rightValue instanceof BigDecimal)) {
64 rightValue = new BigDecimal(rightValue.toString());
65 }
66
67 return doEvaluate((BigDecimal) leftValue, (BigDecimal) rightValue);
68 } else if (leftValue instanceof Date && rightValue instanceof Date) {
69 return doEvaluate((Date) leftValue, (Date) rightValue);
70 } else {
71 throw new ValangException("The " + operatorSymbol + " operator only supports two date or two number values!", getLine(), getColumn());
72 }
73 }
74
75 /**
76 * Evaluates a <code>BigDecimal</code> and is called by
77 * <code>evaluate</code>.
78 */
79 protected abstract boolean doEvaluate(BigDecimal leftValue, BigDecimal rightValue);
80
81 /**
82 * Evaluates a <code>Date</code> and is called by
83 * <code>evaluate</code>.
84 */
85 protected abstract boolean doEvaluate(Date leftValue, Date rightValue);
86
87 }