| 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.PreparedStylesheet; |
| 12 | import net.sf.saxon.expr.parser.OptimizerOptions; |
| 13 | import net.sf.saxon.lib.ErrorGatherer; |
| 14 | import net.sf.saxon.lib.StringCollator; |
| 15 | import net.sf.saxon.om.NodeInfo; |
| 16 | import net.sf.saxon.om.Sequence; |
| 17 | import net.sf.saxon.style.*; |
| 18 | import net.sf.saxon.trace.XSLTTraceCodeInjector; |
| 19 | import net.sf.saxon.trans.CompilerInfo; |
| 20 | import net.sf.saxon.trans.XPathException; |
| 21 | import net.sf.saxon.trans.packages.IPackageLoader; |
| 22 | import net.sf.saxon.trans.packages.PackageDetails; |
| 23 | import net.sf.saxon.trans.packages.PackageLibrary; |
| 24 | import net.sf.saxon.trans.packages.VersionedPackageName; |
| 25 | import net.sf.saxon.tree.linked.DocumentImpl; |
| 26 | |
| 27 | import javax.xml.transform.ErrorListener; |
| 28 | import javax.xml.transform.Source; |
| 29 | import javax.xml.transform.URIResolver; |
| 30 | import javax.xml.transform.stream.StreamSource; |
| 31 | import java.io.InputStream; |
| 32 | import java.net.URI; |
| 33 | import java.util.ArrayList; |
| 34 | import java.util.Comparator; |
| 35 | import java.util.List; |
| 36 | import java.util.Objects; |
| 37 | |
| 38 | /** |
| 39 | * An XsltCompiler object allows XSLT 2.0 and XSLT 3.0 stylesheets to be compiled. The compiler holds information that |
| 40 | * represents the static context for the compilation. |
| 41 | * <p>To construct an XsltCompiler, use the factory method {@link Processor#newXsltCompiler} on the Processor object.</p> |
| 42 | * <p>An XsltCompiler may be used repeatedly to compile multiple queries. Any changes made to the |
| 43 | * XsltCompiler (that is, to the static context) do not affect queries that have already been compiled. |
| 44 | * An XsltCompiler may in principle be used concurrently in multiple threads, but in practice this |
| 45 | * is best avoided because all instances will share the same ErrorListener and it may therefore be |
| 46 | * difficult to establish which error messages are associated with each compilation.</p> |
| 47 | * <p>If JIT compilation is enabled (this is the default for Saxon-EE), then static errors in template |
| 48 | * rules might be detected not during execution of the <code>compile()</code> method, but rather |
| 49 | * when the relevant code is first executed. In this situation the <code>compile()</code> method will |
| 50 | * not throw an exception, but the errors will still (eventually) be notified to the <code>ErrorListener</code> |
| 51 | * associated with the compiler.</p> |
| 52 | * <p>To avoid problems with error reporting, it is recommended that: |
| 53 | * <ul> |
| 54 | * <li>When code is under development and static errors are therefore likely, a new |
| 55 | * {@code XsltCompiler} should be created for each compilation (and JIT should preferably |
| 56 | * be disabled, so that all static errors are detected.)</li> |
| 57 | * <li>When production code is being loaded, and errors are therefore unlikely, |
| 58 | * it is safe to use the same {@code XsltCompiler} for all compilations, and to |
| 59 | * enable JIT for maximum performance.</li> |
| 60 | * </ul> |
| 61 | * |
| 62 | * @since 9.0 |
| 63 | */ |
| 64 | public class XsltCompiler { |
| 65 | |
| 66 | private Processor processor; |
| 67 | private Configuration config; |
| 68 | private CompilerInfo compilerInfo; |
| 69 | |
| 70 | |
| 71 | /** |
| 72 | * Protected constructor. The public way to create an <tt>XsltCompiler</tt> is by using the factory method |
| 73 | * {@link Processor#newXsltCompiler} . |
| 74 | * |
| 75 | * @param processor the Saxon processor |
| 76 | */ |
| 77 | |
| 78 | protected XsltCompiler(Processor processor) { |
| 79 | this.processor = processor; |
| 80 | this.config = processor.getUnderlyingConfiguration(); |
| 81 | compilerInfo = new CompilerInfo(config.getDefaultXsltCompilerInfo()); |
| 82 | compilerInfo.setGenerateByteCode(config.isGenerateByteCode(Configuration.XSLT)); |
| 83 | compilerInfo.setTargetEdition(config.getEditionCode()); |
| 84 | compilerInfo.setJustInTimeCompilation(config.isJITEnabled()); |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Get the Processor from which this XsltCompiler was constructed |
| 89 | * |
| 90 | * @return the Processor to which this XsltCompiler belongs |
| 91 | * @since 9.3 |
| 92 | */ |
| 93 | |
| 94 | public Processor getProcessor() { |
| 95 | return processor; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Set the URIResolver to be used during stylesheet compilation. This URIResolver, despite its name, |
| 100 | * is <b>not</b> used for resolving relative URIs against a base URI; it is used for dereferencing |
| 101 | * an absolute URI (after resolution) to return a {@link javax.xml.transform.Source} representing the |
| 102 | * location where a stylesheet module can be found. |
| 103 | * <p>This URIResolver is used to dereference the URIs appearing in <code>xsl:import</code>, |
| 104 | * <code>xsl:include</code>, and <code>xsl:import-schema</code> declarations. It is not used |
| 105 | * for resolving the URI supplied for the main stylesheet module (as supplied to the |
| 106 | * {@link #compile(javax.xml.transform.Source)} or {@link #compilePackage(javax.xml.transform.Source)} methods. |
| 107 | * It is not used at run-time for resolving requests to the <code>document()</code> or similar functions. |
| 108 | * (Instead, such functions use the run-time URIResolver passed to the {@link XsltTransformer} |
| 109 | * or {@link Xslt30Transformer}).</p> |
| 110 | * |
| 111 | * @param resolver the URIResolver to be used during stylesheet compilation. |
| 112 | */ |
| 113 | |
| 114 | public void setURIResolver(URIResolver resolver) { |
| 115 | compilerInfo.setURIResolver(resolver); |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Set the value of a stylesheet parameter. Static (compile-time) parameters must be provided using |
| 120 | * this method on the XsltCompiler object, prior to stylesheet compilation. Non-static parameters |
| 121 | * may also be provided using this method if their values will not vary from one transformation |
| 122 | * to another. |
| 123 | * |
| 124 | * @param name the qualified name identifying the parameter, as declared in a global <code><xsl:param></code> |
| 125 | * element in the stylesheet |
| 126 | * @param value the value of the parameter |
| 127 | * @throws SaxonApiUncheckedException if the value is lazily evaluated, and evaluation fails |
| 128 | */ |
| 129 | public void setParameter(QName name, XdmValue value) { |
| 130 | try { |
| 131 | compilerInfo.setParameter(name.getStructuredQName(), |
| 132 | ((Sequence<?>) value.getUnderlyingValue()).materialize()); |
| 133 | } catch (XPathException e) { |
| 134 | throw new SaxonApiUncheckedException(e); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /** |
| 139 | * Clear the values of all stylesheet parameters previously set using {@link #setParameter(QName, XdmValue)}. |
| 140 | * This resets the parameters to their initial ("undeclared") state |
| 141 | */ |
| 142 | |
| 143 | public void clearParameters() { |
| 144 | compilerInfo.clearParameters(); |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Get the URIResolver to be used during stylesheet compilation. |
| 149 | * |
| 150 | * @return the URIResolver used during stylesheet compilation. Returns null if no user-supplied |
| 151 | * URIResolver has been set. |
| 152 | */ |
| 153 | |
| 154 | public URIResolver getURIResolver() { |
| 155 | return compilerInfo.getURIResolver(); |
| 156 | } |
| 157 | |
| 158 | /** |
| 159 | * Set the ErrorListener to be used during this compilation episode |
| 160 | * |
| 161 | * @param listener The error listener to be used. This is notified of all errors detected during the |
| 162 | * compilation. |
| 163 | */ |
| 164 | |
| 165 | public void setErrorListener(ErrorListener listener) { |
| 166 | compilerInfo.setErrorListener(listener); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Get the ErrorListener being used during this compilation episode |
| 171 | * |
| 172 | * @return listener The error listener in use. This is notified of all errors detected during the |
| 173 | * compilation. Returns null if no user-supplied ErrorListener has been set. |
| 174 | */ |
| 175 | |
| 176 | public ErrorListener getErrorListener() { |
| 177 | return compilerInfo.getErrorListener(); |
| 178 | } |
| 179 | |
| 180 | /** |
| 181 | * Say that the stylesheet must be compiled to be schema-aware, even if it contains no |
| 182 | * xsl:import-schema declarations. Normally a stylesheet is treated as schema-aware |
| 183 | * only if it contains one or more xsl:import-schema declarations. If it is not schema-aware, |
| 184 | * then all input documents must be untyped, and validation of temporary trees is disallowed |
| 185 | * (though validation of the final result tree is permitted). Setting the argument to true |
| 186 | * means that schema-aware code will be compiled regardless. |
| 187 | * |
| 188 | * @param schemaAware If true, the stylesheet will be compiled with schema-awareness |
| 189 | * enabled even if it contains no xsl:import-schema declarations. If false, the stylesheet |
| 190 | * is treated as schema-aware only if it contains one or more xsl:import-schema declarations. |
| 191 | * @since 9.2 |
| 192 | */ |
| 193 | |
| 194 | public void setSchemaAware(boolean schemaAware) { |
| 195 | compilerInfo.setSchemaAware(schemaAware); |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Ask whether schema-awareness has been requested by means of a call on |
| 200 | * {@link #setSchemaAware} |
| 201 | * |
| 202 | * @return true if schema-awareness has been requested |
| 203 | * @since 9.2 |
| 204 | */ |
| 205 | |
| 206 | public boolean isSchemaAware() { |
| 207 | return compilerInfo.isSchemaAware(); |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Ask whether any package produced by this compiler can be deployed to a different location, with a different base URI |
| 212 | * |
| 213 | * @return if true then static-base-uri() represents the deployed location of the package, |
| 214 | * rather than its compile time location |
| 215 | * @since 9.8 |
| 216 | */ |
| 217 | |
| 218 | public boolean isRelocatable() { |
| 219 | return compilerInfo.isRelocatable(); |
| 220 | } |
| 221 | |
| 222 | /** |
| 223 | * Say whether any package produced by this compiler can be deployed to a different location, with a different base URI |
| 224 | * |
| 225 | * @param relocatable if true then static-base-uri() represents the deployed location of the package, |
| 226 | * rather than its compile time location |
| 227 | * @since 9.8 |
| 228 | * */ |
| 229 | |
| 230 | public void setRelocatable(boolean relocatable) { |
| 231 | compilerInfo.setRelocatable(relocatable); |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Set the target edition under which the stylesheet will be executed. |
| 236 | * |
| 237 | * @param edition the Saxon edition for the run-time environment. One of "EE", "PE", "HE", "JS", or "JS2". |
| 238 | * @since 9.7.0.5. Experimental and subject to change. |
| 239 | */ |
| 240 | |
| 241 | public void setTargetEdition(String edition) { |
| 242 | if (!("EE".equals(edition) || "PE".equals(edition) || "HE".equals(edition) || "JS".equals(edition) || "JS2".equals(edition))) { |
| 243 | throw new IllegalArgumentException("Unknown Saxon edition " + edition); |
| 244 | } |
| 245 | compilerInfo.setTargetEdition(edition); |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Get the target edition under which the stylesheet will be executed. |
| 250 | * |
| 251 | * @return the Saxon edition for the run-time environment. One of "EE", "PE", "HE", "JS", or "JS2". |
| 252 | * @since 9.7.0.5. Experimental and subject to change. |
| 253 | */ |
| 254 | |
| 255 | public String getTargetEdition() { |
| 256 | return compilerInfo.getTargetEdition(); |
| 257 | } |
| 258 | |
| 259 | /** |
| 260 | * Declare the default collation |
| 261 | * |
| 262 | * @param uri the absolute URI of the default collation. Either this URI must have been bound to a collation |
| 263 | * using the method {@link Configuration#registerCollation(String, StringCollator)}, or it must be a |
| 264 | * collation that is recognized implicitly, such as a UCA collation |
| 265 | * @throws IllegalStateException if the collation URI is not a recognized collation |
| 266 | * @since 9.5 |
| 267 | */ |
| 268 | |
| 269 | public void declareDefaultCollation(String uri) { |
| 270 | StringCollator c; |
| 271 | try { |
| 272 | c = getProcessor().getUnderlyingConfiguration().getCollation(uri); |
| 273 | } catch (XPathException e) { |
| 274 | c = null; |
| 275 | } |
| 276 | if (c == null) { |
| 277 | throw new IllegalStateException("Unknown collation " + uri); |
| 278 | } |
| 279 | compilerInfo.setDefaultCollation(uri); |
| 280 | } |
| 281 | |
| 282 | /** |
| 283 | * Get the default collation |
| 284 | * |
| 285 | * @return the URI of the default collation if one has been set, or the URI of the codepoint collation otherwise |
| 286 | * @since 9.7.0.2 |
| 287 | */ |
| 288 | |
| 289 | public String getDefaultCollation() { |
| 290 | return compilerInfo.getDefaultCollation(); |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * Set the XSLT (and XPath) language level to be supported by the processor. This has no effect |
| 295 | * from Saxon 9.8: the processor is an XSLT 3.0 processor regardless of the language level |
| 296 | * requested. |
| 297 | * |
| 298 | * @param version the language level to be supported. The value is ignored. |
| 299 | * @throws IllegalArgumentException if the value is not equal to 0.0, 2.0, or 3.0 |
| 300 | * @deprecated Has no effect from Saxon 9.8. |
| 301 | * @since 9.3. Has no effect from Saxon 9.8. |
| 302 | */ |
| 303 | |
| 304 | public void setXsltLanguageVersion(String version) { |
| 305 | } |
| 306 | |
| 307 | /** |
| 308 | * Get the XSLT (and XPath) language level supported by the processor. |
| 309 | * |
| 310 | * @return the language level supported. From Saxon 9.8 this always returns "3.0". |
| 311 | * @since 9.3 |
| 312 | */ |
| 313 | |
| 314 | public String getXsltLanguageVersion() { |
| 315 | return "3.0"; |
| 316 | } |
| 317 | |
| 318 | /** |
| 319 | * Ask whether assertions (xsl:assert instructions) should be enabled. By default |
| 320 | * they are disabled. If assertions are enabled at compile time, then by |
| 321 | * default they will also be enabled at run time; but they can be |
| 322 | * disabled at run time by specific request |
| 323 | * |
| 324 | * @return true if assertions are enabled at compile time |
| 325 | * @since 9.7 |
| 326 | */ |
| 327 | |
| 328 | public boolean isAssertionsEnabled() { |
| 329 | return compilerInfo.isAssertionsEnabled(); |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Say whether assertions (xsl:assert instructions) should be enabled. By default |
| 334 | * they are disabled. If assertions are enabled at compile time, then by |
| 335 | * default they will also be enabled at run time; but they can be |
| 336 | * disabled at run time by specific request |
| 337 | * |
| 338 | * @param enabled true if assertions are enabled at compile time |
| 339 | * @since 9.7 |
| 340 | */ |
| 341 | |
| 342 | |
| 343 | public void setAssertionsEnabled(boolean enabled) { |
| 344 | compilerInfo.setAssertionsEnabled(enabled); |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Request fast compilation. Fast compilation will generally be achieved at the expense of run-time performance |
| 349 | * and quality of diagnostics. Fast compilation is a good trade-off if (a) the stylesheet is known to be correct, |
| 350 | * and (b) once compiled, it is only executed once against a document of modest size. |
| 351 | * <p>Fast compilation may result in static errors going unreported, especially if they occur in code |
| 352 | * that is never executed.</p> |
| 353 | * <p><i>The current implementation is equivalent to switching off all optimizations other than just-in-time |
| 354 | * compilation of template rules. Setting this option, however, indicates an intent rather than a mechanism, |
| 355 | * and the implementation details may change in future to reflect the intent.</i></p> |
| 356 | * |
| 357 | * @param fast set to true to request fast compilation; set to false to revert to the optimization options |
| 358 | * defined in the Configuration. |
| 359 | * @since 9.9 |
| 360 | */ |
| 361 | |
| 362 | public void setFastCompilation(boolean fast) { |
| 363 | if (fast) { |
| 364 | // The only optimizer option that speeds up compilation is JIT. |
| 365 | compilerInfo.setOptimizerOptions(new OptimizerOptions(OptimizerOptions.JIT)); |
| 366 | } else { |
| 367 | compilerInfo.setOptimizerOptions(getProcessor().getUnderlyingConfiguration().getOptimizerOptions()); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | /** |
| 372 | * Ask if fast compilation has been enabled. |
| 373 | * |
| 374 | * @return true if fast compilation has been enabled (technically, this returns true if the only |
| 375 | * optimizer option that has been enabled is JIT compilation of template rules). |
| 376 | * @since 9.9 |
| 377 | */ |
| 378 | |
| 379 | public boolean isFastCompilation() { |
| 380 | return compilerInfo.getOptimizerOptions().getOptions() == OptimizerOptions.JIT; |
| 381 | } |
| 382 | |
| 383 | |
| 384 | /** |
| 385 | * Set whether trace hooks are to be included in the compiled code. To use tracing, it is necessary |
| 386 | * both to compile the code with trace hooks included, and to supply a TraceListener at run-time |
| 387 | * |
| 388 | * @param option true if trace code is to be compiled in, false otherwise |
| 389 | * @since 9.3 |
| 390 | */ |
| 391 | |
| 392 | public void setCompileWithTracing(boolean option) { |
| 393 | if (option) { |
| 394 | compilerInfo.setCodeInjector(new XSLTTraceCodeInjector()); |
| 395 | } else { |
| 396 | compilerInfo.setCodeInjector(null); |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /** |
| 401 | * Ask whether trace hooks are included in the compiled code. |
| 402 | * |
| 403 | * @return true if trace hooks are included, false if not. |
| 404 | * @since 9.3 |
| 405 | */ |
| 406 | |
| 407 | public boolean isCompileWithTracing() { |
| 408 | return compilerInfo.isCompileWithTracing(); |
| 409 | } |
| 410 | |
| 411 | /** |
| 412 | * Set whether bytecode should be generated for the compiled stylesheet. This option |
| 413 | * is available only with Saxon-EE. The default depends on the setting in the configuration |
| 414 | * at the time the XsltCompiler is instantiated, and by default is true for Saxon-EE. |
| 415 | * |
| 416 | * @param option true if bytecode is to be generated, false otherwise |
| 417 | * @since 9.6 |
| 418 | */ |
| 419 | |
| 420 | public void setGenerateByteCode(boolean option) { |
| 421 | compilerInfo.setGenerateByteCode(option); |
| 422 | } |
| 423 | |
| 424 | /** |
| 425 | * Ask whether bytecode is to be generated in the compiled code. |
| 426 | * |
| 427 | * @return true if bytecode is to be generated, false if not. |
| 428 | * @since 9.6 |
| 429 | */ |
| 430 | |
| 431 | public boolean isGenerateByteCode() { |
| 432 | return compilerInfo.isGenerateByteCode(); |
| 433 | } |
| 434 | |
| 435 | |
| 436 | /** |
| 437 | * Import a compiled XQuery library. This makes pre-compiled XQuery library modules available |
| 438 | * to the <code>saxon:import-query</code> declaration. |
| 439 | * @param queryCompiler An XQueryCompiler that has been used to compile a library of XQuery functions |
| 440 | * (by using one of the overloaded methods named <code>compileLibrary</code>). |
| 441 | */ |
| 442 | |
| 443 | public void importXQueryEnvironment(XQueryCompiler queryCompiler) { |
| 444 | compilerInfo.setXQueryLibraries(queryCompiler.getUnderlyingStaticContext().getCompiledLibraries()); |
| 445 | } |
| 446 | |
| 447 | |
| 448 | /** |
| 449 | * Get the stylesheet associated |
| 450 | * via the xml-stylesheet processing instruction (see |
| 451 | * http://www.w3.org/TR/xml-stylesheet/) with the document |
| 452 | * document specified in the source parameter, and that match |
| 453 | * the given criteria. If there are several suitable xml-stylesheet |
| 454 | * processing instructions, then the returned Source will identify |
| 455 | * a synthesized stylesheet module that imports all the referenced |
| 456 | * stylesheet module. |
| 457 | * <p>The returned Source will have an absolute URI, created by resolving |
| 458 | * any relative URI against the base URI of the supplied source document, |
| 459 | * and redirected if necessary by using the URIResolver associated with this |
| 460 | * <code>XsltCompiler</code>.</p> |
| 461 | * |
| 462 | * @param source The XML source document. Note that if the source document |
| 463 | * is available as an instance of {@link XdmNode}, a corresponding <code>Source</code> |
| 464 | * can be obtained using the method {@link net.sf.saxon.s9api.XdmNode#asSource()}. |
| 465 | * If the source is a StreamSource or SAXSource, it will be read only as far as the |
| 466 | * xml-stylesheet processing instruction (but the Source will be consumed and must not |
| 467 | * be re-used). |
| 468 | * @param media The media attribute to be matched. May be null, in which |
| 469 | * case the prefered templates will be used (i.e. alternate = no). |
| 470 | * Note that Saxon does not implement the complex CSS3-based syntax for |
| 471 | * media queries. By default, the media value is simply ignored. An algorithm for |
| 472 | * comparing the requested media with the declared media can be defined using |
| 473 | * the method {@link Configuration#setMediaQueryEvaluator(Comparator)}. |
| 474 | * @param title The value of the title attribute to match. May be null. |
| 475 | * @param charset The value of the charset attribute to match. May be null. |
| 476 | * @return A Source object suitable for passing to {@link #compile(javax.xml.transform.Source)}. |
| 477 | * @throws SaxonApiException if any problems occur, including the case where no matching |
| 478 | * xml-stylesheet processing instruction is found. |
| 479 | * @since 9.6 |
| 480 | */ |
| 481 | |
| 482 | |
| 483 | public Source getAssociatedStylesheet(Source source, String media, String title, String charset) |
| 484 | throws SaxonApiException { |
| 485 | try { |
| 486 | return StylesheetModule.getAssociatedStylesheet(config, compilerInfo.getURIResolver(), source, media, title, charset); |
| 487 | } catch (XPathException e) { |
| 488 | throw new SaxonApiException(e); |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | |
| 493 | /** |
| 494 | * Compile a library package. |
| 495 | * <p>The source argument identifies an XML file containing an <xsl:package> element. Any packages |
| 496 | * on which this package depends must have been made available to the <code>XsltCompiler</code> |
| 497 | * by importing them using {@link #importPackage}.</p> |
| 498 | * |
| 499 | * |
| 500 | * @param source identifies an XML document holding the the XSLT package to be compiled |
| 501 | * @return the XsltPackage that results from the compilation. Note that this package |
| 502 | * is not automatically imported to this <code>XsltCompiler</code>; if the package is required |
| 503 | * for use in subsequent compilations then it must be explicitly imported. |
| 504 | * @throws SaxonApiException if the source cannot be read or if static errors are found during the |
| 505 | * compilation. Any such errors will have been notified to the registered <code>ErrorListener</code> |
| 506 | * if there is one, or reported on the <code>System.err</code> output stream otherwise. |
| 507 | * @since 9.6 |
| 508 | * @see #compile(Source) - especially the notes regarding error handling and just-in-time compilation. |
| 509 | */ |
| 510 | |
| 511 | public XsltPackage compilePackage(Source source) throws SaxonApiException { |
| 512 | try { |
| 513 | Compilation compilation; |
| 514 | if (source instanceof DocumentImpl && ((DocumentImpl)source).getDocumentElement() instanceof StyleElement) { |
| 515 | compilation = ((StyleElement)((DocumentImpl) source).getDocumentElement()).getCompilation(); |
| 516 | } else { |
| 517 | compilation = new Compilation(config, new CompilerInfo(compilerInfo)); |
| 518 | } |
| 519 | compilation.setLibraryPackage(true); |
| 520 | XsltPackage pack = new XsltPackage(this, compilation.compilePackage(source).getStylesheetPackage()); |
| 521 | int errors = compilation.getErrorCount(); |
| 522 | if (errors > 0) { |
| 523 | String count = errors == 1 ? "one error" : errors + " errors"; |
| 524 | throw new SaxonApiException("Package compilation failed: " + count + " reported"); |
| 525 | } |
| 526 | return pack; |
| 527 | } catch (XPathException e) { |
| 528 | throw new SaxonApiException(e); |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | private PackageLibrary getPackageLibrary() { |
| 533 | return compilerInfo.getPackageLibrary(); |
| 534 | } |
| 535 | |
| 536 | |
| 537 | /** |
| 538 | * Compile a list of packages. |
| 539 | * |
| 540 | * @param sources the collection of packages to be compiled, in the form of an Iterable |
| 541 | * @return the collection of compiled packages, in the form of an Iterable. |
| 542 | * @throws UnsupportedOperationException - always. This method is no longer available |
| 543 | * from Saxon 9.8 |
| 544 | * @since 9.6 |
| 545 | * @deprecated since 9.8. Multiple packages may be supplied in the form of a {@link PackageLibrary} registered |
| 546 | * with the underlying {@link CompilerInfo}, or may be listed in the configuration file. Alternatively they |
| 547 | * can be imported explicitly (taking care over the order of importing) using {@link #importPackage(XsltPackage)}. |
| 548 | */ |
| 549 | public Iterable<XsltPackage> compilePackages(Iterable<Source> sources) { |
| 550 | throw new UnsupportedOperationException("XsltCompiler#compilePackages() was dropped in Saxon 9.8"); |
| 551 | } |
| 552 | |
| 553 | /** |
| 554 | * Add new packages to a package library. |
| 555 | * @param sources Sources for the packages |
| 556 | * @param link Link each of the packages when loaded if true |
| 557 | * @return the collection of compiled packages, in the form of an Iterable |
| 558 | * ..... note that unless link = true these will probably require link() processing before execution. |
| 559 | * @since 9.6 |
| 560 | * @deprecated since 9.8. Multiple packages may be supplied in the form of a {@link PackageLibrary} registered |
| 561 | * with the underlying {@link CompilerInfo}, or may be listed in the configuration file. Alternatively they |
| 562 | * can be imported explicitly (taking care over the order of importing) using {@link #importPackage(XsltPackage)}. |
| 563 | */ |
| 564 | public Iterable<XsltPackage> addCompilePackages(Iterable<Source> sources, boolean link) { |
| 565 | throw new UnsupportedOperationException("XsltCompiler.addCompilePackages is dropped from Saxon 9.8"); |
| 566 | } |
| 567 | |
| 568 | /** |
| 569 | * Load a compiled package from a file or from a remote location. |
| 570 | * <p>The supplied URI represents the location of a resource which must have been originally |
| 571 | * created using {@link XsltPackage#save(java.io.File)}.</p> |
| 572 | * <p>The result of loading the package is returned as an <code>XsltPackage</code> object. |
| 573 | * Note that this package is not automatically imported to this <code>XsltCompiler</code>; |
| 574 | * if the package is required for use in subsequent compilations then it must be explicitly |
| 575 | * imported.</p> |
| 576 | * |
| 577 | * @param location the location from which the package is to be loaded, as a URI |
| 578 | * @return the compiled package loaded from the supplied file or remote location |
| 579 | * @throws SaxonApiException if no resource can be loaded from the supplied location or if the |
| 580 | * resource that is loaded is not a compiled package, or if the compiled package is not |
| 581 | * consistent with this <code>XsltCompiler</code> (for example, if it was created using an |
| 582 | * incompatible Saxon version). |
| 583 | * @since 9.7 |
| 584 | */ |
| 585 | |
| 586 | public XsltPackage loadLibraryPackage(URI location) throws SaxonApiException { |
| 587 | try { |
| 588 | Source input = new StreamSource(location.toString()); |
| 589 | IPackageLoader loader = processor.getUnderlyingConfiguration().makePackageLoader(); |
| 590 | if(loader != null){ |
| 591 | StylesheetPackage pack = loader.loadPackage(input); |
| 592 | return new XsltPackage(this, pack); |
| 593 | } |
| 594 | throw new SaxonApiException("Loading library package requires Saxon PE or higher"); |
| 595 | } catch (XPathException e) { |
| 596 | throw new SaxonApiException(e); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | /** |
| 601 | * Load a compiled package from a file or from a remote location, with the intent to use this as a complete |
| 602 | * executable stylesheet, not as a library package. |
| 603 | * <p>The supplied URI represents the location of a resource which must have been originally |
| 604 | * created using {@link XsltPackage#save(java.io.File)} or some equivalent.</p> |
| 605 | * <p>The result of loading the package is returned as an <code>XsltExecutable</code> object.</p> |
| 606 | * |
| 607 | * @param location the location from which the package is to be loaded, as a URI |
| 608 | * @return the compiled package loaded from the supplied file or remote location |
| 609 | * @throws SaxonApiException if no resource can be loaded from the supplied location or if the |
| 610 | * resource that is loaded is not a compiled package, or if the compiled package is not |
| 611 | * consistent with this <code>XsltCompiler</code> (for example, if it was created using an |
| 612 | * incompatible Saxon version). |
| 613 | * @since 9.7 |
| 614 | */ |
| 615 | |
| 616 | public XsltExecutable loadExecutablePackage(URI location) throws SaxonApiException { |
| 617 | return loadLibraryPackage(location).link(); |
| 618 | } |
| 619 | |
| 620 | /** |
| 621 | * Import a library package. Calling this method makes the supplied package available for reference |
| 622 | * in the <code>xsl:use-package</code> declarations of subsequent compilations performed using this |
| 623 | * <code>XsltCompiler</code>. |
| 624 | * |
| 625 | * @param thePackage the package to be imported |
| 626 | * @throws SaxonApiException if the imported package was created under a different {@link Processor} |
| 627 | * @since 9.6 |
| 628 | */ |
| 629 | |
| 630 | public void importPackage(XsltPackage thePackage) throws SaxonApiException { |
| 631 | if (thePackage.getProcessor() != processor) { |
| 632 | throw new SaxonApiException( |
| 633 | "The imported package and the XsltCompiler must belong to the same Processor"); |
| 634 | } |
| 635 | compilerInfo.getPackageLibrary().addPackage(thePackage.getUnderlyingPreparedPackage()); |
| 636 | } |
| 637 | |
| 638 | /** |
| 639 | * Import a library package, changing the package name and/or version. Calling this method |
| 640 | * makes the supplied package available for reference in the <code>xsl:use-package</code> |
| 641 | * declaration of subsequent compilations performed using the <code>XsltCompiler</code>. The |
| 642 | * supplied package name and version are used in place of the name and version used in the XSLT |
| 643 | * source code. This provides a level of indirection: for example the same source package can |
| 644 | * be compiled twice, with different settings for the static parameter values, and the two |
| 645 | * different compiled versions can then be selected from xsl:use-package declarations. distinguishing |
| 646 | * them by the new package name and/or version. |
| 647 | * |
| 648 | * @param thePackage the package to be imported |
| 649 | * @param packageName the new package name to be used. If null, the original package name is used |
| 650 | * unchanged |
| 651 | * @param version the new package version number to be used. If null, the original package version |
| 652 | * number is used unchanged |
| 653 | * @throws SaxonApiException if the imported package was created under a different {@link Processor}, |
| 654 | * or if the supplied version number is invalid |
| 655 | * @since 9.8 |
| 656 | */ |
| 657 | |
| 658 | public void importPackage(XsltPackage thePackage, String packageName, String version) throws SaxonApiException { |
| 659 | try { |
| 660 | if (thePackage.getProcessor() != processor) { |
| 661 | throw new SaxonApiException("The imported package and the XsltCompiler must belong to the same Processor"); |
| 662 | } |
| 663 | PackageDetails details = new PackageDetails(); |
| 664 | if (packageName == null) { |
| 665 | packageName = thePackage.getName(); |
| 666 | } |
| 667 | if (version == null) { |
| 668 | version = thePackage.getVersion(); |
| 669 | } |
| 670 | details.nameAndVersion = new VersionedPackageName(packageName, version); |
| 671 | details.loadedPackage = thePackage.getUnderlyingPreparedPackage(); |
| 672 | compilerInfo.getPackageLibrary().addPackage(details); |
| 673 | } catch (XPathException e) { |
| 674 | throw new SaxonApiException(e); |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | /** |
| 679 | * Import a named package, together with all the packages on which it depends, recursively. |
| 680 | * The package must be identified in the package library for this {@code XsltCompiler}, which defaults |
| 681 | * to the package library defined in the {@link Configuration}, typically set up by loading a configuration |
| 682 | * file. |
| 683 | * @param packageName the name of the required package. This is the name under which it is registered |
| 684 | * in the package library, which is not necessarily the same as the name appearing |
| 685 | * in the XSLT source code. |
| 686 | * @param versionRange the required version of the package, or range of versions, in the format |
| 687 | * of the package-version attribute of xsl:use-package. |
| 688 | * @return the best matching package if there is one, or null otherwise. The name of the package |
| 689 | * must match; if there are multiple versions, then the version chosen is based first on the |
| 690 | * priority attached to this package/version in the library, and if the priorities are equal (or |
| 691 | * there are no explicit priorities) then the one with highest version number is taken. |
| 692 | * @since 9.8 |
| 693 | */ |
| 694 | |
| 695 | public XsltPackage obtainPackage(String packageName, String versionRange) throws SaxonApiException { |
| 696 | try { |
| 697 | PackageVersionRanges pvr = new PackageVersionRanges(versionRange); |
| 698 | PackageDetails details = getPackageLibrary().findPackage(packageName, pvr); |
| 699 | if (details != null) { |
| 700 | if (details.loadedPackage != null) { |
| 701 | return new XsltPackage(this, details.loadedPackage); |
| 702 | } else if (details.sourceLocation != null) { |
| 703 | XsltPackage pack = compilePackage(details.sourceLocation); |
| 704 | details.loadedPackage = pack.getUnderlyingPreparedPackage(); |
| 705 | return pack; |
| 706 | } |
| 707 | } |
| 708 | return null; |
| 709 | } catch (XPathException e) { |
| 710 | throw new SaxonApiException(e); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /** |
| 715 | * Import a package from the configuration file (or more generally, from the packageLibrary |
| 716 | * of this XsltCompiler) given an alias used to identify it |
| 717 | * @param alias the alias of the package/version in the configuration file |
| 718 | * @return the referenced package |
| 719 | * @throws SaxonApiException the package does not exist, or if compiling the package fails |
| 720 | */ |
| 721 | |
| 722 | public XsltPackage obtainPackageWithAlias(String alias) throws SaxonApiException { |
| 723 | PackageDetails details = getPackageLibrary().findDetailsForAlias(alias); |
| 724 | if (details == null) { |
| 725 | throw new SaxonApiException("No package with alias " + alias + " found in package library"); |
| 726 | } |
| 727 | try { |
| 728 | StylesheetPackage pack = getPackageLibrary().obtainLoadedPackage(details, new ArrayList<>()); |
| 729 | return new XsltPackage(this, pack); |
| 730 | } catch (XPathException e) { |
| 731 | throw new SaxonApiException(e); |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | /** |
| 736 | * Compile a stylesheet. |
| 737 | * <p><i>Note: the term "compile" here indicates that the stylesheet is converted into an executable |
| 738 | * form. There is no implication that this involves code generation.</i></p> |
| 739 | * <p>The source argument identifies the XML document holding the principal stylesheet module. Other |
| 740 | * modules will be located relative to this module by resolving relative URIs found in <code><xsl:include></code> |
| 741 | * and <code><xsl:import></code> declarations against the base URI that is defined |
| 742 | * as the {@code systemId} property of the supplied {@code Source}.</p> |
| 743 | * <p>The following kinds of {@link javax.xml.transform.Source} are recognized:</p> |
| 744 | * <ul> |
| 745 | * <li>{@link javax.xml.transform.stream.StreamSource}, allowing the stylesheet to be supplied as a |
| 746 | * URI, as a {@link java.io.File}, as an {@link java.io.InputStream}, or as a {@link java.io.Reader}</li> |
| 747 | * <li>{@link javax.xml.transform.sax.SAXSource}, allowing the stylesheet to be supplied as a stream |
| 748 | * of SAX events from a SAX2-compliant XML parser (or any other source of SAX events)</li> |
| 749 | * <li>{@link javax.xml.transform.dom.DOMSource}, allowing the stylesheet to be supplied as a |
| 750 | * DOM tree</li> |
| 751 | * <li>Document wrappers for XOM, JDOM, DOM4J, or AXIOM trees</li> |
| 752 | * <li>A Saxon {@link NodeInfo}, representing the root of a tree in any of the native tree formats supported |
| 753 | * by Saxon</li> |
| 754 | * </ul> |
| 755 | * <p>The compilation uses a snapshot of the properties of the <code>XsltCompiler</code> at the |
| 756 | * time this method is invoked. This is relevant when JIT compilation is enabled (which is the default |
| 757 | * under Saxon-EE). Under JIT compilation, templates are compiled when first executed, which will typically be after |
| 758 | * the <code>compile()</code> method has returned. Subsequent changes to the properties of the <code>XsltCompiler</code>, |
| 759 | * for example, setting a new <code>ErrorListener</code>, have no effect on the delayed compilation of |
| 760 | * template rules at execution time.</p> |
| 761 | * <p>If JIT compilation is enabled (this is the default for Saxon-EE), then static errors in template |
| 762 | * rules might be detected not during execution of the <code>compile()</code> method, but rather |
| 763 | * when the relevant code is first executed. In this situation the <code>compile()</code> method will |
| 764 | * not throw an exception, but the errors will still (eventually) be notified to the <code>ErrorListener</code> |
| 765 | * or <code>ErrorList</code> associated with the compiler: more specifically, the <code>ErrorListener</code> |
| 766 | * or <code>ErrorList</code> that was associated with the <code>XsltCompiler</code> at the time |
| 767 | * <code>compile()</code> was invoked.</p> |
| 768 | * |
| 769 | * @param source Source object representing the principal stylesheet module to be compiled. |
| 770 | * Must not be null. If the {@code Source} wraps a resource such as a {@link java.io.Reader} |
| 771 | * or {@link InputStream} then the resource will be consumed by the method. |
| 772 | * @return an {@code XsltExecutable}, which represents the compiled stylesheet. The {@code XsltExecutable} |
| 773 | * is immutable and thread-safe; it may be used to run multiple transformations, in series or concurrently. |
| 774 | * @throws SaxonApiException if the stylesheet contains static errors or if it cannot be read. Note that |
| 775 | * the exception that is thrown will <b>not</b> contain details of the actual errors found in the stylesheet. These |
| 776 | * will instead be notified to the registered {@code ErrorListener} or {@code ErrorList}. |
| 777 | * The default {@code ErrorListener} displays error messages on the standard error output. |
| 778 | * |
| 779 | */ |
| 780 | |
| 781 | public XsltExecutable compile(Source source) throws SaxonApiException { |
| 782 | Objects.requireNonNull(source); |
| 783 | try { |
| 784 | CompilerInfo ci2 = new CompilerInfo(compilerInfo); |
| 785 | PreparedStylesheet pss = Compilation.compileSingletonPackage(config, ci2, source); |
| 786 | return new XsltExecutable(processor, pss); |
| 787 | } catch (XPathException e) { |
| 788 | throw new SaxonApiException(e); |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | /** |
| 793 | * Get the underlying {@link CompilerInfo} object, which provides more detailed (but less stable) control |
| 794 | * over some compilation options |
| 795 | * |
| 796 | * @return the underlying {@code CompilerInfo} object, which holds compilation-time options. The methods on |
| 797 | * the {@code CompilerInfo} object are not guaranteed stable from release to release. |
| 798 | */ |
| 799 | |
| 800 | public CompilerInfo getUnderlyingCompilerInfo() { |
| 801 | return compilerInfo; |
| 802 | } |
| 803 | |
| 804 | /** |
| 805 | * Supply a (typically empty) {@code List} which will be populated with information about any static errors |
| 806 | * encountered during the transformation. |
| 807 | * <p>Calling this method overwrites the effect of any previous call on {@link #setErrorListener(ErrorListener)} |
| 808 | * as well as previous calls on {@code setErrorList}.</p> |
| 809 | * |
| 810 | * @param errorList a List (typically empty) to which information will be appended about |
| 811 | * static errors found during the compilation. Each such error is represented by a |
| 812 | * {@link StaticError} object. |
| 813 | * @since 9.9 |
| 814 | */ |
| 815 | |
| 816 | public void setErrorList(List<StaticError> errorList) { |
| 817 | compilerInfo.setErrorListener(new ErrorGatherer(errorList)); |
| 818 | } |
| 819 | |
| 820 | /** |
| 821 | * Say whether just-in-time compilation of template rules should be used. |
| 822 | * @param jit true if just-in-time compilation is to be enabled. With this option enabled, |
| 823 | * static analysis of a template rule is deferred until the first time that the |
| 824 | * template is matched. This can improve performance when many template |
| 825 | * rules are rarely used during the course of a particular transformation; however, |
| 826 | * it means that static errors in the stylesheet will not necessarily cause the |
| 827 | * {@link #compile(Source)} method to throw an exception (errors in code that is |
| 828 | * actually executed will still be notified to the registered <code>ErrorListener</code> |
| 829 | * or <code>ErrorList</code>, but this may happen after the {@link #compile(Source)} |
| 830 | * method returns). This option is enabled by default in Saxon-EE, and is not available |
| 831 | * in Saxon-HE or Saxon-PE. |
| 832 | * <p><b>Recommendation:</b> disable this option unless you are confident that the |
| 833 | * stylesheet you are compiling is error-free.</p> |
| 834 | * @throws UnsupportedOperationException if the argument is set to <code>true</code> and the |
| 835 | * configuration is not a licensed Saxon-EE configuration. |
| 836 | */ |
| 837 | |
| 838 | public void setJustInTimeCompilation(boolean jit){ |
| 839 | if (jit && !config.isLicensedFeature(Configuration.LicenseFeature.ENTERPRISE_XSLT)){ |
| 840 | throw new UnsupportedOperationException("XSLT just-in-time compilation requires a Saxon-EE license"); |
| 841 | } |
| 842 | compilerInfo.setJustInTimeCompilation(jit); |
| 843 | } |
| 844 | |
| 845 | /** |
| 846 | * Ask whether just-in-time compilation of template rules should be used. |
| 847 | * |
| 848 | * @return true if just-in-time compilation is enabled. With this option enabled, |
| 849 | * static analysis of a template rule is deferred until the first time that the |
| 850 | * template is matched. This can improve performance when many template |
| 851 | * rules are rarely used during the course of a particular transformation; however, |
| 852 | * it means that static errors in the stylesheet may go undetected. |
| 853 | */ |
| 854 | |
| 855 | public boolean isJustInTimeCompilation(){ |
| 856 | return compilerInfo.isJustInTimeCompilation(); |
| 857 | } |
| 858 | |
| 859 | } |
| 860 |