…lines 1–12 unchanged (12 lines)
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17package org.apache.commons.jxpath.ri.compiler;
18
19import java.util.Collection;
20import java.util.HashSet;
21import java.util.Iterator;
22
23import org.apache.commons.jxpath.ri.EvalContext;
24import org.apache.commons.jxpath.ri.InfoSetUtil;
25import org.apache.commons.jxpath.ri.axes.InitialContext;
26import org.apache.commons.jxpath.ri.axes.SelfContext;
27
28/**
29 * Base implementation of Expression for the operations ">", ">=", "<", "<=".
30 *
31 * @author Matt Benson
32 * @version $Revision:$ $Date:$
33 */
34public abstract class CoreOperationRelationalExpression extends CoreOperation {
35
36 protected CoreOperationRelationalExpression(Expression[] args) {
37 super(args);
38 }
39
40 public final Object computeValue(EvalContext context) {
41 return compute(args[0].computeValue(context), args[1]
42 .computeValue(context)) ? Boolean.TRUE : Boolean.FALSE;
43 }
44
45 protected final int getPrecedence() {
46 return 3;
47 }
48
49 protected final boolean isSymmetric() {
50 return false;
51 }
52
53 protected abstract boolean evaluateCompare(int compare);
54
55 private boolean compute(Object left, Object right) {
56 left = reduce(left);
57 right = reduce(right);
58
59 if (left instanceof InitialContext) {
60 ((InitialContext) left).reset();
61 }
62 if (right instanceof InitialContext) {
63 ((InitialContext) right).reset();
64 }
65 if (left instanceof Iterator && right instanceof Iterator) {
66 return findMatch((Iterator) left, (Iterator) right);
67 }
68 if (left instanceof Iterator) {
69 return containsMatch((Iterator) left, right);
70 }
71 if (right instanceof Iterator) {
72 return containsMatch((Iterator) right, left);
73 }
74 return evaluateCompare(compare(left, right));
75 }
76
77 private Object reduce(Object o) {
78 if (o instanceof SelfContext) {
79 o = ((EvalContext) o).getSingleNodePointer();
80 }
81 if (o instanceof Collection) {
82 o = ((Collection) o).iterator();
83 }
84 return o;
85 }
86
87 private boolean containsMatch(Iterator it, Object value) {
88 while (it.hasNext()) {
89 Object element = it.next();
90 if (evaluateCompare(compare(element, value))) {
91 return true;
92 }
93 }
94 return false;
95 }
96
97 private boolean findMatch(Iterator lit, Iterator rit) {
98 HashSet left = new HashSet();
99 while (lit.hasNext()) {
100 left.add(lit.next());
101 }
102 while (rit.hasNext()) {
103 if (containsMatch(left.iterator(), rit.next())) {
104 return true;
105 }
106 }
107 return false;
108 }
109
110 private int compare(Object l, Object r) {
111 double ld = InfoSetUtil.doubleValue(l);
112 double rd = InfoSetUtil.doubleValue(r);
113 return ld == rd ? 0 : ld < rd ? -1 : 1;
114 }
115
116}
117