| 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.s9api; |
| 9 | |
| 10 | import net.sf.saxon.Configuration; |
| 11 | import net.sf.saxon.expr.StaticContext; |
| 12 | import net.sf.saxon.expr.parser.OptimizerOptions; |
| 13 | import net.sf.saxon.lib.StringCollator; |
| 14 | import net.sf.saxon.sxpath.IndependentContext; |
| 15 | import net.sf.saxon.sxpath.XPathEvaluator; |
| 16 | import net.sf.saxon.sxpath.XPathExpression; |
| 17 | import net.sf.saxon.sxpath.XPathVariable; |
| 18 | import net.sf.saxon.trans.DecimalFormatManager; |
| 19 | import net.sf.saxon.trans.DecimalSymbols; |
| 20 | import net.sf.saxon.trans.XPathException; |
| 21 | import net.sf.saxon.value.SequenceType; |
| 22 | |
| 23 | import java.net.URI; |
| 24 | import java.net.URISyntaxException; |
| 25 | import java.util.Iterator; |
| 26 | import java.util.Map; |
| 27 | import java.util.Objects; |
| 28 | import java.util.concurrent.ConcurrentHashMap; |
| 29 | |
| 30 | /** |
| 31 | * An XPathCompiler object allows XPath queries to be compiled. The compiler holds information that |
| 32 | * represents the static context for an XPath expression. |
| 33 | * <p>To construct an XPathCompiler, use the factory method |
| 34 | * {@link Processor#newXPathCompiler}.</p> |
| 35 | * <p>An XPathCompiler may be used repeatedly to compile multiple |
| 36 | * queries. Any changes made to the XPathCompiler (that is, to the |
| 37 | * static context) do not affect queries that have already been compiled. |
| 38 | * An XPathCompiler may be used concurrently in multiple threads, but |
| 39 | * it should not then be modified once initialized.</p> |
| 40 | * <p>Changes to an XPathCompiler are cumulative. There is no simple way to reset |
| 41 | * the XPathCompiler to its initial state; instead, simply create a new |
| 42 | * XPathCompiler.</p> |
| 43 | * <p>The <code>XPathCompiler</code> has the ability to maintain a cache of compiled |
| 44 | * expressions. This is active only if enabled by calling {@link #setCaching(boolean)}. |
| 45 | * If caching is enabled, then the compiler will recognize an attempt to compile |
| 46 | * the same expression twice, and will avoid the cost of recompiling it. The cache |
| 47 | * is emptied by any method that changes the static context for subsequent expressions, |
| 48 | * for example, {@link #setBaseURI(java.net.URI)}. Unless the cache is emptied, |
| 49 | * it grows indefinitely: compiled expressions are never discarded.</p> |
| 50 | * |
| 51 | * @since 9.0 |
| 52 | */ |
| 53 | |
| 54 | public class XPathCompiler { |
| 55 | |
| 56 | private Processor processor; |
| 57 | private XPathEvaluator evaluator; |
| 58 | private IndependentContext env; |
| 59 | private ItemType requiredContextItemType; |
| 60 | |
| 61 | private Map<String, XPathExecutable> cache = null; |
| 62 | |
| 63 | /** |
| 64 | * Protected constructor |
| 65 | * |
| 66 | * @param processor the s9api Processor |
| 67 | */ |
| 68 | |
| 69 | protected XPathCompiler(Processor processor) { |
| 70 | this.processor = processor; |
| 71 | this.evaluator = new XPathEvaluator(processor.getUnderlyingConfiguration()); |
| 72 | env = (IndependentContext) this.evaluator.getStaticContext(); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Get the Processor from which this XPathCompiler was constructed |
| 77 | * |
| 78 | * @return the Processor to which this XPathCompiler belongs |
| 79 | * @since 9.3 |
| 80 | */ |
| 81 | |
| 82 | public Processor getProcessor() { |
| 83 | return processor; |
| 84 | } |
| 85 | |
| 86 | /** |
| 87 | * Say whether XPath 1.0 backwards compatibility mode is to be used. In backwards compatibility |
| 88 | * mode, more implicit type conversions are allowed in XPath expressions, for example it |
| 89 | * is possible to compare a number with a string. The default is false (backwards compatibility |
| 90 | * mode is off). |
| 91 | * |
| 92 | * @param option true if XPath 1.0 backwards compatibility is to be enabled, false if it is to |
| 93 | * be disabled. |
| 94 | * @since 9.1; changed in 9.8 to throw IllegalStateException if the feature is not available; change |
| 95 | * reverted by bug 3817. |
| 96 | */ |
| 97 | |
| 98 | public void setBackwardsCompatible(boolean option) { |
| 99 | if (cache != null) { |
| 100 | cache.clear(); |
| 101 | } |
| 102 | env.setBackwardsCompatibilityMode(option); |
| 103 | } |
| 104 | |
| 105 | |
| 106 | /** |
| 107 | * Ask whether XPath 1.0 backwards compatibility mode is in force. |
| 108 | * |
| 109 | * @return true if XPath 1.0 backwards compatibility is enabled, false if it is disabled. |
| 110 | */ |
| 111 | |
| 112 | public boolean isBackwardsCompatible() { |
| 113 | return env.isInBackwardsCompatibleMode(); |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Say whether XPath expressions compiled using this {@code XPathCompiler} are |
| 118 | * schema-aware. They will automatically be schema-aware if the method |
| 119 | * {@link #importSchemaNamespace(String)} is called. An XPath expression |
| 120 | * must be marked as schema-aware if it is to handle typed (validated) |
| 121 | * input documents. |
| 122 | * |
| 123 | * @param schemaAware true if expressions are to be schema-aware, false otherwise |
| 124 | * @throws UnsupportedOperationException if schema-awareness is requested when this is |
| 125 | * not a licensed Saxon-EE configuration. |
| 126 | * @since 9.3. Changed in 9.9 to throw an exception if Saxon-EE is not available (previously, |
| 127 | * the option was either silently ignored, or caused a failure at some later time.) |
| 128 | */ |
| 129 | |
| 130 | public void setSchemaAware(boolean schemaAware) { |
| 131 | if (schemaAware && !processor.getUnderlyingConfiguration().isLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION)) { |
| 132 | throw new UnsupportedOperationException("Schema processing requires a licensed Saxon-EE configuration"); |
| 133 | } |
| 134 | env.setSchemaAware(schemaAware); |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Ask whether XPath expressions compiled using this XPathCompiler are |
| 139 | * schema-aware. They will automatically be schema-aware if the method |
| 140 | * {@link #importSchemaNamespace(String)} is called. An XPath expression |
| 141 | * must be marked as schema-aware if it is to handle typed (validated) |
| 142 | * input documents. |
| 143 | * |
| 144 | * @return true if expressions are to be schema-aware, false otherwise |
| 145 | * @since 9.3 |
| 146 | */ |
| 147 | |
| 148 | public boolean isSchemaAware() { |
| 149 | return env.getPackageData().isSchemaAware(); |
| 150 | } |
| 151 | |
| 152 | /** |
| 153 | * Say whether an XPath 2.0, XPath 3.0 or XPath 3.1 processor is required. |
| 154 | * |
| 155 | * @param value One of the values 1.0, 2.0, 3.0, 3.05, 3.1. |
| 156 | * <p>Setting the option to 1.0 requests an XPath 2.0 processor running in 1.0 compatibility mode; |
| 157 | * this is equivalent to setting the language version to 2.0 and backwards compatibility mode to true. |
| 158 | * Requesting "3.05" gives XPath 3.0 plus the extensions defined in the XSLT 3.0 specification |
| 159 | * (map types and map constructors).</p> |
| 160 | * @throws IllegalArgumentException if the version is not numerically equal to 1.0, 2.0, 3.0, 3.05, or 3.1. |
| 161 | * @since 9.3 |
| 162 | */ |
| 163 | |
| 164 | public void setLanguageVersion(String value) { |
| 165 | if (cache != null) { |
| 166 | cache.clear(); |
| 167 | } |
| 168 | int version; |
| 169 | if ("1.0".equals(value)) { |
| 170 | version = 20; |
| 171 | env.setBackwardsCompatibilityMode(true); |
| 172 | } else if ("2.0".equals(value)) { |
| 173 | version = 20; |
| 174 | } else if ("3.0".equals(value) || "3.05".equals(value)) { |
| 175 | version = 30; |
| 176 | } else if ("3.1".equals(value)) { |
| 177 | version = 31; |
| 178 | } else { |
| 179 | throw new IllegalArgumentException("XPath version"); |
| 180 | } |
| 181 | env.setXPathLanguageLevel(version); |
| 182 | env.setDefaultFunctionLibrary(version); |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * Ask whether an XPath 2.0, XPath 3.0 or XPath 3.1 processor is being used |
| 187 | * |
| 188 | * @return version: "2.0", "3.0" or "3.1" |
| 189 | * @since 9.3 |
| 190 | */ |
| 191 | |
| 192 | public String getLanguageVersion() { |
| 193 | if (env.getXPathVersion() == 20) { |
| 194 | return "2.0"; |
| 195 | } else if (env.getXPathVersion() == 30) { |
| 196 | return "3.0"; |
| 197 | } else if (env.getXPathVersion() == 31) { |
| 198 | return "3.1"; |
| 199 | } else { |
| 200 | throw new IllegalStateException("Unknown XPath version " + env.getXPathVersion()); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Set the static base URI for XPath expressions compiled using this XPathCompiler. The base URI |
| 206 | * is part of the static context, and is used to resolve any relative URIs appearing within an XPath |
| 207 | * expression, for example a relative URI passed as an argument to the doc() function. If no |
| 208 | * static base URI is supplied, then the current working directory is used. |
| 209 | * |
| 210 | * @param uri the base URI to be set in the static context. This must be an absolute URI, or null |
| 211 | * to indicate that no static base URI is available. |
| 212 | */ |
| 213 | |
| 214 | public void setBaseURI(URI uri) { |
| 215 | if (cache != null) { |
| 216 | cache.clear(); |
| 217 | } |
| 218 | if (uri == null) { |
| 219 | env.setBaseURI(null); |
| 220 | } else { |
| 221 | if (!uri.isAbsolute()) { |
| 222 | throw new IllegalArgumentException("Supplied base URI must be absolute"); |
| 223 | } |
| 224 | env.setBaseURI(uri.toString()); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | /** |
| 229 | * Get the static base URI for XPath expressions compiled using this XPathCompiler. The base URI |
| 230 | * is part of the static context, and is used to resolve any relative URIs appearing within an XPath |
| 231 | * expression, for example a relative URI passed as an argument to the doc() function. If no |
| 232 | * static base URI has been explicitly set, this method returns null. |
| 233 | * |
| 234 | * @return the base URI from the static context |
| 235 | */ |
| 236 | |
| 237 | public URI getBaseURI() { |
| 238 | try { |
| 239 | return new URI(env.getStaticBaseURI()); |
| 240 | } catch (URISyntaxException err) { |
| 241 | throw new IllegalStateException(err); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Declare a namespace binding as part of the static context for XPath expressions compiled using this |
| 247 | * XPathCompiler |
| 248 | * |
| 249 | * @param prefix The namespace prefix. If the value is a zero-length string, this method sets the default |
| 250 | * namespace for elements and types. |
| 251 | * @param uri The namespace URI. It is possible to specify a zero-length string to "undeclare" a namespace; |
| 252 | * in this case the prefix will not be available for use, except in the case where the prefix |
| 253 | * is also a zero length string, in which case the absence of a prefix implies that the name |
| 254 | * is in no namespace. |
| 255 | * @throws NullPointerException if either the prefix or uri is null. |
| 256 | */ |
| 257 | |
| 258 | public void declareNamespace(String prefix, String uri) { |
| 259 | if (cache != null) { |
| 260 | cache.clear(); |
| 261 | } |
| 262 | env.declareNamespace(prefix, uri); |
| 263 | } |
| 264 | |
| 265 | /** |
| 266 | * Import a schema namespace: that is, add the element and attribute declarations and type definitions |
| 267 | * contained in a given namespace to the static context for the XPath expression. |
| 268 | * <p>This method will not cause the schema to be loaded. That must be done separately, using the |
| 269 | * {@link SchemaManager}. This method will not fail if the schema has not been loaded (but in that case |
| 270 | * the set of declarations and definitions made available to the XPath expression is empty). The schema |
| 271 | * document for the specified namespace may be loaded before or after this method is called.</p> |
| 272 | * <p>This method does not bind a prefix to the namespace. That must be done separately, using the |
| 273 | * {@link #declareNamespace(String, String)} method.</p> |
| 274 | * |
| 275 | * @param uri The schema namespace to be imported. To import declarations in a no-namespace schema, |
| 276 | * supply a zero-length string. |
| 277 | * @since 9.1 |
| 278 | */ |
| 279 | |
| 280 | public void importSchemaNamespace(String uri) { |
| 281 | if (cache != null) { |
| 282 | cache.clear(); |
| 283 | } |
| 284 | env.getImportedSchemaNamespaces().add(uri); |
| 285 | env.setSchemaAware(true); |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * Say whether undeclared variables are allowed. By default, they are not allowed. When |
| 290 | * undeclared variables are allowed, it is not necessary to predeclare the variables that |
| 291 | * may be used in the XPath expression; instead, a variable is automatically declared when a reference |
| 292 | * to the variable is encountered within the expression. |
| 293 | * |
| 294 | * @param allow true if undeclared variables are allowed, false if they are not allowed. |
| 295 | * @since 9.2 |
| 296 | */ |
| 297 | |
| 298 | public void setAllowUndeclaredVariables(boolean allow) { |
| 299 | if (cache != null) { |
| 300 | cache.clear(); |
| 301 | } |
| 302 | env.setAllowUndeclaredVariables(allow); |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Ask whether undeclared variables are allowed. By default, they are not allowed. When |
| 307 | * undeclared variables are allowed, it is not necessary to predeclare the variables that |
| 308 | * may be used in the XPath expression; instead, a variable is automatically declared when a reference |
| 309 | * to the variable is encountered within the expression. |
| 310 | * |
| 311 | * @return true if undeclared variables are allowed, false if they are not allowed. |
| 312 | * @since 9.2 |
| 313 | */ |
| 314 | |
| 315 | public boolean isAllowUndeclaredVariables() { |
| 316 | return env.isAllowUndeclaredVariables(); |
| 317 | } |
| 318 | |
| 319 | /** |
| 320 | * Declare a variable as part of the static context for XPath expressions compiled using this |
| 321 | * {@code XPathCompiler}. It is an error for the XPath expression to refer to a variable unless it has been |
| 322 | * declared, unless the method {@link #setAllowUndeclaredVariables(boolean)} has been called to permit |
| 323 | * undeclared variables. This method declares the existence of the variable, but it does not |
| 324 | * bind any value to the variable; that is done later, when the XPath expression is evaluated. |
| 325 | * The variable is allowed to have any type (that is, the required type is <code>item()*</code>). |
| 326 | * |
| 327 | * @param qname The name of the variable, expressions as a QName |
| 328 | */ |
| 329 | |
| 330 | public void declareVariable(QName qname) { |
| 331 | if (cache != null) { |
| 332 | cache.clear(); |
| 333 | } |
| 334 | env.declareVariable(qname.getNamespaceURI(), qname.getLocalName()); |
| 335 | } |
| 336 | |
| 337 | /** |
| 338 | * Declare a variable as part of the static context for XPath expressions compiled using this |
| 339 | * {@code XPathCompiler}. It is an error for the XPath expression to refer to a variable unless it has been |
| 340 | * declared, unless the method {@link #setAllowUndeclaredVariables(boolean)} has been called to permit |
| 341 | * undeclared variables. This method declares the existence of the variable, and defines the required type |
| 342 | * of the variable, but it does not bind any value to the variable; that is done later, |
| 343 | * when the XPath expression is evaluated. |
| 344 | * |
| 345 | * @param qname The name of the variable, expressed as a {@link QName} |
| 346 | * @param itemType The required item type of the value of the variable, for example {@code ItemType.BOOLEAN} |
| 347 | * @param occurrences The allowed number of items in the sequence forming the value of the variable |
| 348 | */ |
| 349 | |
| 350 | public void declareVariable(QName qname, ItemType itemType, OccurrenceIndicator occurrences) { |
| 351 | if (cache != null) { |
| 352 | cache.clear(); |
| 353 | } |
| 354 | XPathVariable var = env.declareVariable(qname.getNamespaceURI(), qname.getLocalName()); |
| 355 | var.setRequiredType( |
| 356 | SequenceType.makeSequenceType( |
| 357 | itemType.getUnderlyingItemType(), occurrences.getCardinality())); |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * Declare the static type of the context item. If this type is declared, and if a context item |
| 362 | * is supplied when the query is invoked, then the context item must conform to this type (no |
| 363 | * type conversion will take place to force it into this type). |
| 364 | * |
| 365 | * @param type the required type of the context item, for example, {@link ItemType#ANY_NODE}. |
| 366 | * @since 9.3 |
| 367 | */ |
| 368 | |
| 369 | public void setRequiredContextItemType(ItemType type) { |
| 370 | requiredContextItemType = type; |
| 371 | env.setRequiredContextItemType(type.getUnderlyingItemType()); |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Get the required type of the context item. If no type has been explicitly declared for the context |
| 376 | * item, an instance of {@link ItemType#ANY_ITEM} (representing the type {@code item()}) is returned. |
| 377 | * |
| 378 | * @return the required type of the context item |
| 379 | * @since 9.3 |
| 380 | */ |
| 381 | |
| 382 | public ItemType getRequiredContextItemType() { |
| 383 | return requiredContextItemType; |
| 384 | } |
| 385 | |
| 386 | /** |
| 387 | * Declare the default collation |
| 388 | * |
| 389 | * @param uri the absolute URI of the default collation. This URI must identify a known collation; |
| 390 | * either one that has been explicitly declared, or one that is recognized implicitly, |
| 391 | * such as a UCA collation |
| 392 | * @throws IllegalStateException if the collation URI is not recognized as a known collation |
| 393 | * @since 9.4 |
| 394 | */ |
| 395 | |
| 396 | public void declareDefaultCollation(String uri) { |
| 397 | StringCollator c; |
| 398 | try { |
| 399 | c = getProcessor().getUnderlyingConfiguration().getCollation(uri); |
| 400 | } catch (XPathException e) { |
| 401 | c = null; |
| 402 | } |
| 403 | if (c == null) { |
| 404 | throw new IllegalStateException("Unknown collation " + uri); |
| 405 | } |
| 406 | env.setDefaultCollationName(uri); |
| 407 | } |
| 408 | |
| 409 | |
| 410 | /** |
| 411 | * Say whether the compiler should maintain a cache of compiled expressions. |
| 412 | * |
| 413 | * @param caching if set to true, caching of compiled expressions is enabled. |
| 414 | * If set to false, any existing cache is cleared, and future compiled expressions |
| 415 | * will not be cached until caching is re-enabled. The cache is also cleared |
| 416 | * (but without disabling future caching) |
| 417 | * if any method is called that changes the static context for compiling |
| 418 | * expressions, for example {@link #declareVariable(QName)} or |
| 419 | * {@link #declareNamespace(String, String)}. |
| 420 | * @since 9.3 |
| 421 | */ |
| 422 | |
| 423 | public void setCaching(boolean caching) { |
| 424 | if (caching) { |
| 425 | if (cache == null) { |
| 426 | cache = new ConcurrentHashMap<>(); |
| 427 | } |
| 428 | } else { |
| 429 | cache = null; |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | /** |
| 434 | * Ask whether the compiler is maintaining a cache of compiled expressions |
| 435 | * |
| 436 | * @return true if a cache is being maintained |
| 437 | * @since 9.3 |
| 438 | */ |
| 439 | |
| 440 | public boolean isCaching() { |
| 441 | return cache != null; |
| 442 | } |
| 443 | |
| 444 | /** |
| 445 | * Request fast compilation. Fast compilation will generally be achieved at the expense of run-time performance |
| 446 | * and quality of diagnostics. Fast compilation is a good trade-off if (a) the expression is known to be correct, |
| 447 | * and (b) once compiled, it is only executed once against a document of modest size. |
| 448 | * @param fast set to true to request fast compilation; set to false to revert to the optimization options |
| 449 | * defined in the Configuration. |
| 450 | * |
| 451 | * @since 9.9 |
| 452 | */ |
| 453 | |
| 454 | public void setFastCompilation(boolean fast) { |
| 455 | if (fast) { |
| 456 | env.setOptimizerOptions(new OptimizerOptions(0)); |
| 457 | } else { |
| 458 | env.setOptimizerOptions(getProcessor().getUnderlyingConfiguration().getOptimizerOptions()); |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * Ask if fast compilation has been enabled. |
| 464 | * @return true if fast compilation has been enabled |
| 465 | * @since 9.9 |
| 466 | */ |
| 467 | |
| 468 | public boolean isFastCompilation() { |
| 469 | return env.getOptimizerOptions().getOptions() == 0; |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * Compile an XPath expression, supplied as a character string. |
| 474 | * |
| 475 | * @param source A non-null string containing the source text of the XPath expression |
| 476 | * @return An XPathExecutable which represents the compiled xpath expression object. |
| 477 | * The XPathExecutable may be run as many times as required, in the same or a different thread. |
| 478 | * The XPathExecutable is not affected by any changes made to the XPathCompiler once it has been compiled. |
| 479 | * @throws SaxonApiException if any static error is detected while analyzing the expression. |
| 480 | * <p>Note: prior to Saxon 9.7, static errors were also notified to the ErrorListener associated |
| 481 | * with the containing Processor/Configuration. This is no longer the case.</p> |
| 482 | */ |
| 483 | |
| 484 | public XPathExecutable compile(String source) throws SaxonApiException { |
| 485 | Objects.requireNonNull(source); |
| 486 | if (cache != null) { |
| 487 | synchronized(this) { |
| 488 | XPathExecutable expr = cache.get(source); |
| 489 | if (expr == null) { |
| 490 | expr = internalCompile(source); |
| 491 | cache.put(source, expr); |
| 492 | } |
| 493 | return expr; |
| 494 | } |
| 495 | } else { |
| 496 | return internalCompile(source); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | private XPathExecutable internalCompile(String source) throws SaxonApiException { |
| 501 | try { |
| 502 | env.getDecimalFormatManager().checkConsistency(); |
| 503 | } catch (net.sf.saxon.trans.XPathException e) { |
| 504 | throw new SaxonApiException(e); |
| 505 | } |
| 506 | XPathEvaluator eval = evaluator; |
| 507 | IndependentContext ic = env; |
| 508 | if (ic.isAllowUndeclaredVariables()) { |
| 509 | // self-declaring variables modify the static context. The XPathCompiler must not change state |
| 510 | // as the result of compiling an expression, so we need to copy the static context. |
| 511 | eval = new XPathEvaluator(processor.getUnderlyingConfiguration()); |
| 512 | ic = new IndependentContext(env); |
| 513 | eval.setStaticContext(ic); |
| 514 | for (Iterator iter = env.iterateExternalVariables(); iter.hasNext(); ) { |
| 515 | XPathVariable var = (XPathVariable) iter.next(); |
| 516 | XPathVariable var2 = ic.declareVariable(var.getVariableQName()); |
| 517 | var2.setRequiredType(var.getRequiredType()); |
| 518 | } |
| 519 | } |
| 520 | try { |
| 521 | XPathExpression cexp = eval.createExpression(source); |
| 522 | return new XPathExecutable(cexp, processor, ic); |
| 523 | } catch (XPathException e) { |
| 524 | throw new SaxonApiException(e); |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /** |
| 529 | * Compile and evaluate an XPath expression, supplied as a character string, with a given |
| 530 | * context item. |
| 531 | * |
| 532 | * @param expression A non-null string containing the source text of the XPath expression |
| 533 | * @param contextItem The context item to be used for evaluating the expression. This |
| 534 | * may be null if the expression is to be evaluated with no context item. |
| 535 | * @return the result of evaluating the XPath expression with this context item. Note that |
| 536 | * the result is an {@link Iterable}, so that it can be used in a "for-each" loop such as |
| 537 | * <code>for (XdmItem item : xpath.evaluate("//x", doc) {...}</code> |
| 538 | * @throws SaxonApiException if any static error is detected while analyzing the expression, |
| 539 | * or if any dynamic error is detected while evaluating it. |
| 540 | * @since 9.3 |
| 541 | */ |
| 542 | |
| 543 | public XdmValue evaluate(String expression, /*@Nullable*/ XdmItem contextItem) throws SaxonApiException { |
| 544 | Objects.requireNonNull(expression); |
| 545 | XPathSelector selector = compile(expression).load(); |
| 546 | if (contextItem != null) { |
| 547 | selector.setContextItem(contextItem); |
| 548 | } |
| 549 | return selector.evaluate(); |
| 550 | } |
| 551 | |
| 552 | /** |
| 553 | * Compile and evaluate an XPath expression whose result is expected to be |
| 554 | * a single item, with a given context item. The expression is supplied as |
| 555 | * a character string. |
| 556 | * |
| 557 | * @param expression A non-null string containing the source text of the XPath expression |
| 558 | * @param contextItem The context item to be used for evaluating the expression. This |
| 559 | * may be null if the expression is to be evaluated with no context item. |
| 560 | * @return the result of evaluating the XPath expression with this context item. |
| 561 | * If the result is a singleton it is returned as an XdmItem; if it is an empty |
| 562 | * sequence, the return value is null. If the expression returns a sequence of more than one item, |
| 563 | * any items after the first are ignored. |
| 564 | * @throws SaxonApiException if any static error is detected while analyzing the expression, |
| 565 | * or if any dynamic error is detected while evaluating it. |
| 566 | * @since 9.3 |
| 567 | */ |
| 568 | |
| 569 | public XdmItem evaluateSingle(String expression, XdmItem contextItem) throws SaxonApiException { |
| 570 | Objects.requireNonNull(expression); |
| 571 | XPathSelector selector = compile(expression).load(); |
| 572 | if (contextItem != null) { |
| 573 | selector.setContextItem(contextItem); |
| 574 | } |
| 575 | return selector.evaluateSingle(); |
| 576 | } |
| 577 | |
| 578 | /** |
| 579 | * Compile an XSLT 2.0 pattern, supplied as a character string. The compiled pattern behaves as a boolean |
| 580 | * expression which, when evaluated in a particular context, returns true if the context node matches |
| 581 | * the pattern, and false if it does not. An error is reported if there is no context item or it the context |
| 582 | * item is not a node. |
| 583 | * |
| 584 | * @param source A non-null string conforming to the syntax of XSLT 2.0 patterns |
| 585 | * @return An XPathExecutable representing an expression which evaluates to true when the context node matches |
| 586 | * the pattern, and false when it does not. |
| 587 | * @throws SaxonApiException if the pattern contains static errors: for example, if its syntax is incorrect, |
| 588 | * or if it refers to undeclared variables or namespaces |
| 589 | * @since 9.1 |
| 590 | */ |
| 591 | |
| 592 | public XPathExecutable compilePattern(String source) throws SaxonApiException { |
| 593 | Objects.requireNonNull(source); |
| 594 | try { |
| 595 | env.getDecimalFormatManager().checkConsistency(); |
| 596 | } catch (XPathException e) { |
| 597 | throw new SaxonApiException(e); |
| 598 | } |
| 599 | |
| 600 | try { |
| 601 | XPathExpression cexp = evaluator.createPattern(source); |
| 602 | return new XPathExecutable(cexp, processor, env); |
| 603 | } catch (XPathException e) { |
| 604 | throw new SaxonApiException(e); |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | /** |
| 609 | * Registers the required decimal format properties |
| 610 | * |
| 611 | * @param format The name of the decimal format |
| 612 | * @param property The decimal symbols name to update, for example {@code "grouping-separator"} |
| 613 | * @param value The value to update the decimal symbol property |
| 614 | * @throws SaxonApiException if there are two conflicting definitions of the named decimal-format |
| 615 | * @since 9.4 |
| 616 | */ |
| 617 | public void setDecimalFormatProperty(QName format, String property, String value) throws SaxonApiException { |
| 618 | DecimalFormatManager dfm = env.getDecimalFormatManager(); |
| 619 | if (dfm == null) { |
| 620 | dfm = new DecimalFormatManager(Configuration.XPATH, env.getXPathVersion()); |
| 621 | env.setDecimalFormatManager(dfm); |
| 622 | } |
| 623 | |
| 624 | DecimalSymbols symbols = dfm.obtainNamedDecimalFormat(format.getStructuredQName()); |
| 625 | |
| 626 | try { |
| 627 | switch (property) { |
| 628 | case "decimal-separator": |
| 629 | symbols.setDecimalSeparator(value); |
| 630 | break; |
| 631 | case "grouping-separator": |
| 632 | symbols.setGroupingSeparator(value); |
| 633 | break; |
| 634 | case "exponent-separator": |
| 635 | symbols.setExponentSeparator(value); |
| 636 | break; |
| 637 | case "infinity": |
| 638 | symbols.setInfinity(value); |
| 639 | break; |
| 640 | case "NaN": |
| 641 | symbols.setNaN(value); |
| 642 | break; |
| 643 | case "minus-sign": |
| 644 | symbols.setMinusSign(value); |
| 645 | break; |
| 646 | case "percent": |
| 647 | symbols.setPercent(value); |
| 648 | break; |
| 649 | case "per-mille": |
| 650 | symbols.setPerMille(value); |
| 651 | break; |
| 652 | case "zero-digit": |
| 653 | symbols.setZeroDigit(value); |
| 654 | break; |
| 655 | case "digit": |
| 656 | symbols.setDigit(value); |
| 657 | break; |
| 658 | case "pattern-separator": |
| 659 | symbols.setPatternSeparator(value); |
| 660 | break; |
| 661 | default: |
| 662 | throw new IllegalArgumentException("Unknown decimal format attribute " + property); |
| 663 | } |
| 664 | } catch (XPathException e) { |
| 665 | throw new SaxonApiException(e); |
| 666 | } |
| 667 | |
| 668 | } |
| 669 | |
| 670 | |
| 671 | /** |
| 672 | * Escape-hatch method to get the underlying static context object used by the implementation. |
| 673 | * |
| 674 | * @return the underlying static context object. In the current implementation this will always |
| 675 | * be an instance of {@link IndependentContext}. |
| 676 | * <p>This method provides an escape hatch to internal Saxon implementation objects that offer a finer and |
| 677 | * lower-level degree of control than the s9api classes and methods. Some of these classes and methods may change |
| 678 | * from release to release.</p> |
| 679 | * @since 9.1 |
| 680 | */ |
| 681 | |
| 682 | public StaticContext getUnderlyingStaticContext() { |
| 683 | return env; |
| 684 | } |
| 685 | } |
| 686 |