| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.xpath; |
| 9 | |
| 10 | import net.sf.saxon.Configuration; |
| 11 | import net.sf.saxon.expr.*; |
| 12 | import net.sf.saxon.expr.instruct.Executable; |
| 13 | import net.sf.saxon.expr.instruct.SlotManager; |
| 14 | import net.sf.saxon.functions.Number_1; |
| 15 | import net.sf.saxon.om.*; |
| 16 | import net.sf.saxon.trans.XPathException; |
| 17 | import net.sf.saxon.tree.wrapper.VirtualNode; |
| 18 | import net.sf.saxon.value.AtomicValue; |
| 19 | import net.sf.saxon.value.DoubleValue; |
| 20 | import net.sf.saxon.value.NumericValue; |
| 21 | import org.xml.sax.InputSource; |
| 22 | |
| 23 | import javax.xml.namespace.QName; |
| 24 | import javax.xml.transform.ErrorListener; |
| 25 | import javax.xml.transform.sax.SAXSource; |
| 26 | import javax.xml.xpath.XPathConstants; |
| 27 | import javax.xml.xpath.XPathExpression; |
| 28 | import javax.xml.xpath.XPathExpressionException; |
| 29 | |
| 30 | /** |
| 31 | * <p>The JAXP XPathExpression interface represents a compiled XPath expression that can be repeatedly |
| 32 | * evaluated. This class is Saxon's implementation of that interface.</p> |
| 33 | * <p>The class also includes some methods retained from Saxon's original XPath API. When these methods |
| 34 | * are used, the object contains the context node and other state, so it is not thread-safe.</p> |
| 35 | * |
| 36 | * @author Michael H. Kay |
| 37 | */ |
| 38 | |
| 39 | |
| 40 | public class XPathExpressionImpl implements XPathExpression { |
| 41 | |
| 42 | private Configuration config; |
| 43 | private Executable executable; |
| 44 | private Expression expression; |
| 45 | private Expression atomizer; |
| 46 | private SlotManager stackFrameMap; |
| 47 | |
| 48 | /** |
| 49 | * The constructor is protected, to ensure that instances can only be |
| 50 | * created using the compile() method of XPathEvaluator |
| 51 | * |
| 52 | * @param exp the compiled expression |
| 53 | * @param exec the executable |
| 54 | */ |
| 55 | |
| 56 | protected XPathExpressionImpl(Expression exp, /*@NotNull*/ Executable exec) { |
| 57 | expression = exp; |
| 58 | executable = exec; |
| 59 | config = exec.getConfiguration(); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Define the number of slots needed for local variables within the expression. |
| 64 | * This method is for internal use only. |
| 65 | * |
| 66 | * @param map description of the stack frame |
| 67 | */ |
| 68 | |
| 69 | protected void setStackFrameMap(SlotManager map) { |
| 70 | stackFrameMap = map; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Get the stack frame map. This holds information about the allocation of slots to variables. |
| 75 | * This is needed by applications using low-level interfaces for evaluating the expression |
| 76 | * |
| 77 | * @return a description of the stack frame |
| 78 | */ |
| 79 | |
| 80 | public SlotManager getStackFrameMap() { |
| 81 | return stackFrameMap; |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Get the Configuration under which this XPath expression was compiled |
| 86 | * |
| 87 | * @return the Saxon configuration |
| 88 | */ |
| 89 | |
| 90 | public Configuration getConfiguration() { |
| 91 | return config; |
| 92 | } |
| 93 | |
| 94 | /** |
| 95 | * JAXP 1.3 evaluate() method |
| 96 | * |
| 97 | * @param node The context node. This must use a representation of nodes that this implementation understands. |
| 98 | * This may be a Saxon NodeInfo, or a node in one of the external object models supported, for example |
| 99 | * DOM, DOM4J, JDOM, or XOM, provided the support module for that object model is loaded. |
| 100 | * |
| 101 | * <p>An instance of {@link TreeInfo} is also accepted.</p> |
| 102 | * |
| 103 | * <p><b>Contrary to the interface specification, Saxon does not supply an empty |
| 104 | * document when the value is null. This is because XPath 2.0 allows the context |
| 105 | * item to be "absent" (null). So Saxon executes the XPath expression with the |
| 106 | * context item undefined.</b></p> |
| 107 | * @param qName Indicates the type of result required. This must be one of the constants defined in |
| 108 | * the JAXP {@link XPathConstants} class. |
| 109 | * Saxon will attempt to convert the actual result of the expression to the required type using the |
| 110 | * XPath 1.0 conversion rules. |
| 111 | * @return the result of the evaluation, as a Java object of the appropriate type. Saxon interprets the |
| 112 | * rules as follows: |
| 113 | * <table> |
| 114 | * <thead><tr><td>QName</td><td>Return Value</td></thead> |
| 115 | * <tbody> |
| 116 | * <tr><td valign="top">BOOLEAN</td> |
| 117 | * <td>The effective boolean value of the actual result, |
| 118 | * as a Java Boolean object</td></tr> |
| 119 | * <tr><td valign="top">STRING</td> |
| 120 | * <td>The result of applying the string() function to the actual result, |
| 121 | * as a Java String object</td></tr> |
| 122 | * <tr><td valign="top">NUMBER</td> |
| 123 | * <td>The result of applying the number() function to the actual result, |
| 124 | * as a Java Double object</td></tr> |
| 125 | * <tr><td valign="top">NODE</td> |
| 126 | * <td>A single node, in the native data model supplied as input. If the |
| 127 | * expression returns more than one node, the first is returned. If |
| 128 | * the expression returns an empty sequence, null is returned. If the |
| 129 | * expression returns an atomic value, or if the first item in the |
| 130 | * result sequence is an atomic value, an exception is thrown.</td></tr> |
| 131 | * <tr><td valign="top">NODESET</td> |
| 132 | * <td>This is interpreted as allowing any sequence, of nodes or atomic values. |
| 133 | * If the first argument is a wrapper around a DOM Node, then the result is |
| 134 | * returned as a DOM NodeList, and an exception is then thrown if the result sequence |
| 135 | * contains a value that is not a DOM Node. In all other cases |
| 136 | * the result is returned as a Java List object, unless it is empty, in which |
| 137 | * case null is returned. The contents of the list may be node objects (in the |
| 138 | * native data model supplied as input), or Java objects representing the XPath |
| 139 | * atomic values in the actual result: String for an xs:string, Double for a xs:double, |
| 140 | * Long for an xs:integer, and so on. (For safety, cast the values to a type |
| 141 | * such as xs:string within the XPath expression). </td></tr></tbody></table> |
| 142 | * @throws XPathExpressionException if evaluation of the expression fails or if the |
| 143 | * result cannot be converted to the requested type. |
| 144 | */ |
| 145 | /*@Nullable*/ |
| 146 | public Object evaluate(/*@Nullable*/ Object node, /*@NotNull*/ QName qName) throws XPathExpressionException { |
| 147 | Item contextItem; |
| 148 | if (node instanceof ZeroOrOne) { |
| 149 | node = ((ZeroOrOne) node).head(); |
| 150 | } |
| 151 | if (node instanceof TreeInfo) { |
| 152 | node = ((TreeInfo)node).getRootNode(); |
| 153 | } |
| 154 | if (node instanceof DocumentInfo) { |
| 155 | node = ((DocumentInfo)node).getUnderlyingNode(); |
| 156 | } |
| 157 | if (node instanceof NodeInfo) { |
| 158 | if (!((NodeInfo) node).getConfiguration().isCompatible(config)) { |
| 159 | throw new XPathExpressionException( |
| 160 | "Supplied node must be built using the same or a compatible Configuration"); |
| 161 | } |
| 162 | if (node instanceof TreeInfo && ((TreeInfo) node).isTyped() && !executable.isSchemaAware()) { |
| 163 | throw new XPathExpressionException( |
| 164 | "The expression was compiled to handled untyped data, but the input is typed"); |
| 165 | } |
| 166 | contextItem = (NodeInfo) node; |
| 167 | } else if (node instanceof Item) { |
| 168 | contextItem = (Item) node; |
| 169 | } else { |
| 170 | JPConverter converter = JPConverter.allocate(node.getClass(), null, config); |
| 171 | Sequence<?> val; |
| 172 | try { |
| 173 | val = converter.convert(node, new EarlyEvaluationContext(config)); |
| 174 | } catch (XPathException e) { |
| 175 | throw new XPathExpressionException( |
| 176 | "Failure converting a node of class " + node.getClass().getName() + |
| 177 | ": " + e.getMessage()); |
| 178 | } |
| 179 | if (val instanceof NodeInfo) { |
| 180 | if (!((NodeInfo) val).getConfiguration().isCompatible(config)) { |
| 181 | throw new XPathExpressionException( |
| 182 | "Supplied node must be built using the same or a compatible Configuration"); |
| 183 | } |
| 184 | if (((NodeInfo) val).getTreeInfo().isTyped() && !executable.isSchemaAware()) { |
| 185 | throw new XPathExpressionException( |
| 186 | "The expression was compiled to handled untyped data, but the input is typed"); |
| 187 | } |
| 188 | contextItem = (NodeInfo) val; |
| 189 | } else { |
| 190 | throw new XPathExpressionException( |
| 191 | "Cannot locate an object model implementation for nodes of class " |
| 192 | + node.getClass().getName()); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | XPathContextMajor context = new XPathContextMajor(contextItem, executable); |
| 197 | context.openStackFrame(stackFrameMap); |
| 198 | try { |
| 199 | if (qName.equals(XPathConstants.BOOLEAN)) { |
| 200 | return expression.effectiveBooleanValue(context); |
| 201 | } else if (qName.equals(XPathConstants.STRING)) { |
| 202 | SequenceIterator iter = expression.iterate(context); |
| 203 | |
| 204 | Item first = iter.next(); |
| 205 | if (first == null) { |
| 206 | return ""; |
| 207 | } |
| 208 | return first.getStringValue(); |
| 209 | |
| 210 | } else if (qName.equals(XPathConstants.NUMBER)) { |
| 211 | if (atomizer == null) { |
| 212 | atomizer = Atomizer.makeAtomizer(expression, null); |
| 213 | } |
| 214 | SequenceIterator iter = atomizer.iterate(context); |
| 215 | |
| 216 | Item first = iter.next(); |
| 217 | if (first == null) { |
| 218 | return Double.NaN; |
| 219 | } |
| 220 | if (first instanceof NumericValue) { |
| 221 | return ((NumericValue) first).getDoubleValue(); |
| 222 | } else { |
| 223 | DoubleValue v = Number_1.convert((AtomicValue) first, getConfiguration()); |
| 224 | return v.getDoubleValue(); |
| 225 | } |
| 226 | |
| 227 | } else if (qName.equals(XPathConstants.NODE)) { |
| 228 | SequenceIterator<?> iter = expression.iterate(context); |
| 229 | Item<?> first = iter.next(); |
| 230 | if (first instanceof VirtualNode) { |
| 231 | return ((VirtualNode) first).getRealNode(); |
| 232 | } |
| 233 | if (first == null || first instanceof NodeInfo) { |
| 234 | return first; |
| 235 | } |
| 236 | throw new XPathExpressionException("Expression result is not a node"); |
| 237 | } else if (qName.equals(XPathConstants.NODESET)) { |
| 238 | context.openStackFrame(stackFrameMap); |
| 239 | SequenceIterator<?> iter = expression.iterate(context); |
| 240 | GroundedValue<?> extent = iter.materialize(); |
| 241 | PJConverter converter = PJConverter.allocateNodeListCreator(config, node); |
| 242 | return converter.convert(extent, Object.class, context); |
| 243 | } else { |
| 244 | throw new IllegalArgumentException("qName: Unknown type for expected result"); |
| 245 | } |
| 246 | } catch (XPathException e) { |
| 247 | throw new XPathExpressionException(e); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * Evaluate the expression to return a string value |
| 253 | * |
| 254 | * @param node the initial context node. This must be either an instance of NodeInfo or a node |
| 255 | * recognized by a known external object model. |
| 256 | * <p><b>Contrary to the interface specification, Saxon does not supply an empty |
| 257 | * document when the value is null. This is because XPath 2.0 allows the context |
| 258 | * item to be "absent" (null). So Saxon executes the XPath expression with the |
| 259 | * context item undefined.</b></p> |
| 260 | * @return the results of the expression, converted to a String |
| 261 | * @throws XPathExpressionException if evaluation fails |
| 262 | */ |
| 263 | |
| 264 | /*@NotNull*/ |
| 265 | public String evaluate(Object node) throws XPathExpressionException { |
| 266 | return (String) evaluate(node, XPathConstants.STRING); |
| 267 | } |
| 268 | |
| 269 | /** |
| 270 | * Evaluate the XPath expression against an input source to obtain a result of a specified type |
| 271 | * |
| 272 | * @param inputSource The input source document against which the expression is evaluated. |
| 273 | * <p>If any error occurs reading or parsing this document, the error is notified |
| 274 | * to the {@link ErrorListener} registered with the {@link Configuration}, |
| 275 | * and also causes an exception to be thrown. </p> |
| 276 | * <p>(Note that there is no caching. This will be parsed, and |
| 277 | * the parsed result will be discarded.) </p> |
| 278 | * <p>If the supplied value is null then (contrary to the JAXP specifications), the XPath expression |
| 279 | * is evaluated with the context item undefined.</p> |
| 280 | * @param qName The type required, identified by a constant in {@link XPathConstants} |
| 281 | * @return the result of the evaluation, as a Java object of the appropriate type: |
| 282 | * see {@link #evaluate(Object, javax.xml.namespace.QName)} |
| 283 | * @throws XPathExpressionException |
| 284 | */ |
| 285 | /*@Nullable*/ |
| 286 | public Object evaluate(/*@Nullable*/ InputSource inputSource, /*@Nullable*/ QName qName) throws XPathExpressionException { |
| 287 | if (qName == null) { |
| 288 | throw new NullPointerException("qName"); |
| 289 | } |
| 290 | try { |
| 291 | NodeInfo doc = null; |
| 292 | if (inputSource != null) { |
| 293 | doc = config.buildDocumentTree(new SAXSource(inputSource)).getRootNode(); |
| 294 | } |
| 295 | return evaluate(doc, qName); |
| 296 | } catch (XPathException e) { |
| 297 | throw new XPathExpressionException(e); |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Evaluate the XPath expression against an input source to obtain a string result. |
| 303 | * |
| 304 | * @param inputSource The input source document against which the expression is evaluated. |
| 305 | * <p>If any error occurs reading or parsing this document, the error is notified |
| 306 | * to the {@link ErrorListener} registered with the {@link Configuration}, |
| 307 | * and also causes an exception to be thrown. </p> |
| 308 | * <p>(Note that there is no caching. This will be parsed, and |
| 309 | * the parsed result will be discarded.) </p> |
| 310 | * <p>If the supplied value is null then (contrary to the JAXP specifications), the XPath expression |
| 311 | * is evaluated with the context item undefined.</p> |
| 312 | * @return the result of the evaluation, converted to a String |
| 313 | * @throws XPathExpressionException in the event of an XPath dynamic error |
| 314 | * @throws NullPointerException If <code>inputSource</code> is <code>null</code>. |
| 315 | */ |
| 316 | |
| 317 | /*@NotNull*/ |
| 318 | public String evaluate(/*@Nullable*/ InputSource inputSource) throws XPathExpressionException { |
| 319 | if (inputSource == null) { |
| 320 | throw new NullPointerException("inputSource"); |
| 321 | } |
| 322 | try { |
| 323 | NodeInfo doc = config.buildDocumentTree(new SAXSource(inputSource)).getRootNode(); |
| 324 | return (String) evaluate(doc, XPathConstants.STRING); |
| 325 | } catch (XPathException e) { |
| 326 | throw new XPathExpressionException(e); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | |
| 331 | /** |
| 332 | * Low-level method to get the internal Saxon expression object. This exposes a wide range of |
| 333 | * internal methods that may be needed by specialized applications, and allows greater control |
| 334 | * over the dynamic context for evaluating the expression. |
| 335 | * |
| 336 | * @return the underlying Saxon expression object. |
| 337 | */ |
| 338 | |
| 339 | public Expression getInternalExpression() { |
| 340 | return expression; |
| 341 | } |
| 342 | |
| 343 | } |
| 344 |