1 28 29 package com.caucho.xpath.pattern; 30 31 import com.caucho.xpath.Expr; 32 import com.caucho.xpath.ExprEnvironment; 33 import com.caucho.xpath.XPathException; 34 35 import org.w3c.dom.Node ; 36 37 import java.util.logging.Level ; 38 39 42 public class FilterIterator extends NodeIterator { 43 private NodeIterator _parentIter; 44 45 private Expr _expr; 46 47 private Node _node; 48 private Node _next; 49 50 58 public FilterIterator(NodeIterator parentIter, Expr expr, 59 ExprEnvironment env, Node context) 60 throws XPathException 61 { 62 super(env); 63 64 _parentIter = parentIter; 65 _expr = expr; 66 _env = env; 67 68 _contextNode = context; 69 70 _node = findFirstMatchingNode(parentIter); 71 _position = 1; 72 _next = _node; 73 } 74 75 78 public boolean hasNext() 79 { 80 if (_next == null) { 81 try { 82 _next = nextNode(); 83 } catch (XPathException e) { 84 log.log(Level.FINE, e.toString(), e); 85 } 86 } 87 88 return _next != null; 89 } 90 91 94 public Node nextNode() 95 throws XPathException 96 { 97 if (_next != null) { 98 _node = _next; 99 _next = null; 100 101 return _node; 102 } 103 104 if (_node != null) { 105 _node = findFirstMatchingNode(_parentIter); 106 _position++; 107 } 108 _next = null; 109 110 return _node; 111 } 112 113 116 private Node findFirstMatchingNode(NodeIterator parentIter) 117 throws XPathException 118 { 119 Node node = parentIter.nextNode(); 120 121 while (true) { 122 if (node != null) { 123 if (_expr.isNumber()) { 124 double value = _expr.evalNumber(node, parentIter); 125 126 if (value == parentIter.getContextPosition()) 127 return node; 128 } 129 else if (_expr.isBoolean()) { 130 if (_expr.evalBoolean(node, parentIter)) 131 return node; 132 } 133 else { 134 Object value = _expr.evalObject(node, parentIter); 135 136 if (value instanceof Number ) { 137 if (Expr.toDouble(value) == parentIter.getContextPosition()) 138 return node; 139 } 140 else if (Expr.toBoolean(value)) 141 return node; 142 } 143 } 144 145 if (parentIter == null || (node = parentIter.nextNode()) == null) { 146 return null; 147 } 148 else if (parentIter.getContextPosition() == 1) { 149 _position = 0; 150 _size = 0; 151 } 152 _contextNode = node; 153 parentIter.setContextNode(node); 154 } 155 } 156 157 public Object clone() 158 { 159 FilterIterator clone = null;; 160 161 try { 162 if (_parentIter == null) 163 clone = new FilterIterator(null, _expr, _env, _contextNode); 164 else 165 clone = new FilterIterator((NodeIterator) _parentIter.clone(), 166 _expr, _env, _contextNode); 167 168 clone._env = _env; 169 clone._position = _position; 170 clone._node = _node; 171 } catch (Exception e) { 172 log.log(Level.FINE, e.toString(), e); 173 } 174 175 return clone; 176 } 177 178 public String toString() 179 { 180 return "FilterIterator[" + _expr + "]"; 181 } 182 } 183 | Popular Tags |