| 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.event.*; |
| 13 | import net.sf.saxon.expr.Component; |
| 14 | import net.sf.saxon.expr.XPathContextMajor; |
| 15 | import net.sf.saxon.expr.instruct.GlobalParameterSet; |
| 16 | import net.sf.saxon.expr.instruct.UserFunction; |
| 17 | import net.sf.saxon.expr.instruct.UserFunctionParameter; |
| 18 | import net.sf.saxon.expr.parser.ExplicitLocation; |
| 19 | import net.sf.saxon.expr.parser.RoleDiagnostic; |
| 20 | import net.sf.saxon.lib.NamespaceConstant; |
| 21 | import net.sf.saxon.om.*; |
| 22 | import net.sf.saxon.serialize.SerializationProperties; |
| 23 | import net.sf.saxon.trans.SymbolicName; |
| 24 | import net.sf.saxon.trans.Visibility; |
| 25 | import net.sf.saxon.trans.XPathException; |
| 26 | import net.sf.saxon.trans.XsltController; |
| 27 | |
| 28 | import javax.xml.transform.Source; |
| 29 | import javax.xml.transform.TransformerException; |
| 30 | import javax.xml.transform.dom.DOMSource; |
| 31 | import java.io.File; |
| 32 | import java.io.OutputStream; |
| 33 | import java.io.Writer; |
| 34 | import java.util.HashMap; |
| 35 | import java.util.Map; |
| 36 | import java.util.Objects; |
| 37 | |
| 38 | /** |
| 39 | * An <code>Xslt30Transformer</code> represents a compiled and loaded stylesheet ready for execution. |
| 40 | * The <code>Xslt30Transformer</code> holds details of the dynamic evaluation context for the stylesheet. |
| 41 | * <p>The <code>Xslt30Transformer</code> differs from {@link XsltTransformer} is supporting new options |
| 42 | * for invoking a stylesheet, corresponding to facilities defined in the XSLT 3.0 specification. However, |
| 43 | * it is not confined to use with XSLT 3.0, and most of the new invocation facilities (for example, |
| 44 | * calling a stylesheet-defined function directly) work equally well with XSLT 2.0 and in some cases |
| 45 | * XSLT 1.0 stylesheets.</p> |
| 46 | * <p>An <code>Xslt30Transformer</code> must not be used concurrently in multiple threads. |
| 47 | * It is safe, however, to reuse the object within a single thread to run the same |
| 48 | * stylesheet several times. Running the stylesheet does not change the context |
| 49 | * that has been established.</p> |
| 50 | * <p>An <code>Xslt30Transformer</code> is always constructed by running the <code>Load30</code> |
| 51 | * method of an {@link XsltExecutable}.</p> |
| 52 | * <p>Unlike <code>XsltTransformer</code>, an <code>Xslt30Transformer</code> is not a <code>Destination</code>. |
| 53 | * To pipe the results of one transformation into another, the target should be an <code>XsltTransfomer</code> |
| 54 | * rather than an <code>Xslt30Transformer</code>.</p> |
| 55 | * <p>Evaluation of an Xslt30Transformer proceeds in a number of phases:</p> |
| 56 | * <ol> |
| 57 | * <li>First, values may be supplied for stylesheet parameters and for the global context item. The |
| 58 | * global context item is used when initializing global variables. Unlike earlier transformation APIs, |
| 59 | * the global context item is quite independent of the "principal Source document".</li> |
| 60 | * <li>The stylesheet may now be repeatedly invoked. Each invocation takes one of three forms: |
| 61 | * <ol> |
| 62 | * <li>Invocation by applying templates. In this case, the information required is (i) an initial |
| 63 | * mode (which defaults to the unnamed mode), (ii) an initial match sequence, which is any |
| 64 | * XDM value, which is used as the effective "select" expression of the implicit apply-templates |
| 65 | * call, and (iii) optionally, values for the tunnel and non-tunnel parameters defined on the |
| 66 | * templates that get invoked (equivalent to using <code>xsl:with-param</code> on the implicit |
| 67 | * <code>apply-templates</code> call).</li> |
| 68 | * <li>Invocation by calling a named template. In this case, the information required is |
| 69 | * (i) the name of the initial template (which defaults to "xsl:initial-template"), and |
| 70 | * (ii) optionally, values for the tunnel and non-tunnel parameters defined on the |
| 71 | * templates that get invoked (equivalent to using <code>xsl:with-param</code> on the implicit |
| 72 | * <code>call-template</code> instruction).</li> |
| 73 | * <li>Invocation by calling a named function. In this case, the information required is |
| 74 | * the sequence of arguments to the function call.</li> |
| 75 | * </ol> |
| 76 | * </li> |
| 77 | * <li>Whichever invocation method is chosen, the result may either be returned directly, as an arbitrary |
| 78 | * XDM value, or it may effectively be wrapped in an XML document. If it is wrapped in an XML document, |
| 79 | * that document can be processed in a number of ways, for example it can be materialized as a tree in |
| 80 | * memory, it can be serialized as XML or HTML, or it can be subjected to further transformation.</li> |
| 81 | * </ol> |
| 82 | * <p>Once the stylesheet has been invoked (using any of these methods), the values of the global context |
| 83 | * item and stylesheet parameters cannot be changed. If it is necessary to run another transformation with |
| 84 | * a different context item or different stylesheet parameters, a new <code>Xslt30Transformer</code> |
| 85 | * should be created from the original <code>XsltExecutable</code>.</p> |
| 86 | * |
| 87 | * @since 9.6 |
| 88 | */ |
| 89 | public class Xslt30Transformer extends AbstractXsltTransformer { |
| 90 | |
| 91 | private GlobalParameterSet globalParameterSet; |
| 92 | private boolean primed = false; |
| 93 | private Item globalContextItem = null; |
| 94 | private boolean alreadyStripped; |
| 95 | |
| 96 | /** |
| 97 | * Protected constructor |
| 98 | * |
| 99 | * @param processor the S9API processor |
| 100 | * @param controller the Saxon controller object |
| 101 | * @param staticParameters the static parameters supplied at stylesheet compile time |
| 102 | */ |
| 103 | |
| 104 | protected Xslt30Transformer(Processor processor, XsltController controller, GlobalParameterSet staticParameters) { |
| 105 | super(processor, controller); |
| 106 | globalParameterSet = new GlobalParameterSet(/*staticParameters*/); |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Supply the context item to be used when evaluating global variables and parameters. A call on |
| 111 | * <code>setGlobalContextItem(node)</code> is equivalent to a call on <code>setGlobalContextItem(node, false)</code>: |
| 112 | * that is, it is assumed that stripping of type annotations and whitespace text nodes has not yet been |
| 113 | * performed. |
| 114 | * |
| 115 | * <p>Note: It is more efficient to do whitespace stripping while constructing the source tree. This can be |
| 116 | * achieved by building the source tree using a {@link DocumentBuilder} initialized using |
| 117 | * {@link DocumentBuilder#setWhitespaceStrippingPolicy(WhitespaceStrippingPolicy)}, supplying a |
| 118 | * {@link WhitespaceStrippingPolicy} obtained by calling {@link XsltExecutable#getWhitespaceStrippingPolicy()}.</p> |
| 119 | * |
| 120 | * @param globalContextItem the item to be used as the context item within the initializers |
| 121 | * of global variables and parameters. This argument can be null if no context item is to be |
| 122 | * supplied. |
| 123 | * @throws IllegalStateException if the transformation has already been evaluated by calling one of the methods |
| 124 | * <code>applyTemplates</code>, <code>callTemplate</code>, or <code>callFunction</code> |
| 125 | * @throws SaxonApiException if a required parameter is not present; if a parameter cannot be converted |
| 126 | * to the required type; if the context item cannot be converted to the required type. |
| 127 | */ |
| 128 | |
| 129 | public void setGlobalContextItem(XdmItem globalContextItem) throws SaxonApiException { |
| 130 | setGlobalContextItem(globalContextItem, false); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Supply the context item to be used when evaluating global variables and parameters. |
| 135 | * |
| 136 | * @param globalContextItem the item to be used as the context item within the initializers |
| 137 | * of global variables and parameters. This argument can be null if no context item is to be |
| 138 | * supplied. |
| 139 | * @param alreadyStripped true if any stripping of type annotations or whitespace text nodes specified |
| 140 | * by the stylesheet has already taken place |
| 141 | * @throws IllegalStateException if the transformation has already been evaluated by calling one of the methods |
| 142 | * <code>applyTemplates</code>, <code>callTemplate</code>, or <code>callFunction</code> |
| 143 | * @throws SaxonApiException Not thrown, but retained in the method signature for compatibility reasons. |
| 144 | */ |
| 145 | |
| 146 | public void setGlobalContextItem(XdmItem globalContextItem, boolean alreadyStripped) throws SaxonApiException { |
| 147 | if (primed) { |
| 148 | throw new IllegalStateException("Stylesheet has already been evaluated"); |
| 149 | } |
| 150 | this.globalContextItem = globalContextItem == null ? null : globalContextItem.getUnderlyingValue(); |
| 151 | this.alreadyStripped = alreadyStripped; |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Set the initial context node for the transformation. |
| 156 | * |
| 157 | * @param node the initial context node, or null if there is to be no initial context node |
| 158 | * @deprecated since 9.7.0.1 - use {@link #setGlobalContextItem} |
| 159 | */ |
| 160 | |
| 161 | public void setInitialContextNode(XdmNode node) { |
| 162 | if (primed) { |
| 163 | throw new IllegalStateException("Stylesheet has already been evaluated"); |
| 164 | } |
| 165 | this.globalContextItem = node.getUnderlyingNode(); |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Set the initial context item for the transformation. |
| 170 | * |
| 171 | * @param item the initial context item, or null if there is to be no initial context item |
| 172 | * @deprecated since 9.8 - use {@link #setGlobalContextItem} |
| 173 | */ |
| 174 | |
| 175 | public void setInitialContextItem(XdmItem item) { |
| 176 | if (primed) { |
| 177 | throw new IllegalStateException("Stylesheet has already been evaluated"); |
| 178 | } |
| 179 | this.globalContextItem = item.getUnderlyingValue(); |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Supply the values of global stylesheet parameters. |
| 184 | * |
| 185 | * <p>If a value is supplied for a parameter with a particular name, and the stylesheet does not declare |
| 186 | * a parameter with that name, then the value is simply ignored.</p> |
| 187 | * |
| 188 | * <p>If a value is supplied for a parameter with a particular name, and the stylesheet declaration of |
| 189 | * that parameter declares a required type, then the supplied value will be checked against that type |
| 190 | * when the value of the parameter is first used (and any error will be reported only then). Parameter |
| 191 | * values are converted to the required type using the function conversion rules.</p> |
| 192 | * |
| 193 | * <p>If a value is supplied for a parameter with a particular name, and the stylesheet declaration of |
| 194 | * that parameter declares it with the attribute <code>static="yes"</code>, then an error will be reported |
| 195 | * when the transformation is initiated.</p> |
| 196 | * |
| 197 | * <p>If a value is supplied for a parameter with a particular name, and a parameter with the same |
| 198 | * name was supplied at compile time using {@link XsltCompiler#setParameter(QName, XdmValue)}, |
| 199 | * then an error will be reported with the transformation is initiated.</p> |
| 200 | * |
| 201 | * @param parameters a map whose keys are QNames identifying global stylesheet parameters, |
| 202 | * and whose corresponding values are the values to be assigned to those parameters. |
| 203 | * The contents of the supplied map are copied by this method, |
| 204 | * so subsequent changes to the map have no effect. |
| 205 | * @throws IllegalStateException if the transformation has already been evaluated by calling one of the methods |
| 206 | * <code>applyTemplates</code>, <code>callTemplate</code>, or <code>callFunction</code> |
| 207 | * @throws SaxonApiException currently occurs only if the supplied value of a parameter cannot be evaluated |
| 208 | */ |
| 209 | |
| 210 | public <T extends XdmValue> void setStylesheetParameters(Map<QName, T> parameters) throws SaxonApiException { |
| 211 | if (primed) { |
| 212 | throw new IllegalStateException("Stylesheet has already been evaluated"); |
| 213 | } |
| 214 | if (globalParameterSet == null) { |
| 215 | globalParameterSet = new GlobalParameterSet(); |
| 216 | } |
| 217 | for (Map.Entry<QName, T> param : parameters.entrySet()) { |
| 218 | StructuredQName name = param.getKey().getStructuredQName(); |
| 219 | try { |
| 220 | globalParameterSet.put(name, |
| 221 | ((Sequence<?>) param.getValue().getUnderlyingValue()).materialize()); |
| 222 | } catch (XPathException e) { |
| 223 | throw new SaxonApiException(e); |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | |
| 229 | private void prime() throws SaxonApiException { |
| 230 | if (!primed) { |
| 231 | if (globalParameterSet == null) { |
| 232 | globalParameterSet = new GlobalParameterSet(); |
| 233 | } |
| 234 | try { |
| 235 | controller.setGlobalContextItem(globalContextItem, alreadyStripped); |
| 236 | controller.initializeController(globalParameterSet); |
| 237 | } catch (XPathException e) { |
| 238 | throw new SaxonApiException(e); |
| 239 | } |
| 240 | } |
| 241 | primed = true; |
| 242 | } |
| 243 | |
| 244 | |
| 245 | /** |
| 246 | * Set parameters to be passed to the initial template. These are used |
| 247 | * whether the transformation is invoked by applying templates to an initial source item, |
| 248 | * or by invoking a named template. The parameters in question are the xsl:param elements |
| 249 | * appearing as children of the xsl:template element. |
| 250 | * <p>The parameters are supplied in the form of a map; the key is a QName which must |
| 251 | * match the name of the parameter; the associated value is an XdmValue containing the |
| 252 | * value to be used for the parameter. If the initial template defines any required |
| 253 | * parameters, the map must include a corresponding value. If the initial template defines |
| 254 | * any parameters that are not present in the map, the default value is used. If the map |
| 255 | * contains any parameters that are not defined in the initial template, these values |
| 256 | * are silently ignored.</p> |
| 257 | * <p>The supplied values are converted to the required type using the function conversion |
| 258 | * rules. If conversion is not possible, a run-time error occurs (not now, but later, when |
| 259 | * the transformation is actually run).</p> |
| 260 | * <p>The <code>XsltTransformer</code> retains a reference to the supplied map, so parameters can be added or |
| 261 | * changed until the point where the transformation is run.</p> |
| 262 | * <p>The XSLT 3.0 specification makes provision for supplying parameters to the initial |
| 263 | * template, as well as global stylesheet parameters. Although there is no similar provision |
| 264 | * in the XSLT 1.0 or 2.0 specifications, this method works for all stylesheets, regardless whether |
| 265 | * XSLT 3.0 is enabled or not.</p> |
| 266 | * |
| 267 | * @param parameters the parameters to be used for the initial template |
| 268 | * @param tunnel true if these values are to be used for setting tunnel parameters; |
| 269 | * false if they are to be used for non-tunnel parameters |
| 270 | * @throws SaxonApiException not currently used, but retained in the method signature for compatibility reasons |
| 271 | */ |
| 272 | |
| 273 | public <T extends XdmValue> void setInitialTemplateParameters(Map<QName, T> parameters, boolean tunnel) throws SaxonApiException { |
| 274 | Map<StructuredQName, Sequence<?>> templateParams = new HashMap<>(); |
| 275 | for (Map.Entry<QName, T> entry : parameters.entrySet()) { |
| 276 | templateParams.put(entry.getKey().getStructuredQName(), entry.getValue().getUnderlyingValue()); |
| 277 | } |
| 278 | controller.setInitialTemplateParameters(templateParams, tunnel); |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Invoke the stylesheet by applying templates to a supplied Source document, sending the results (wrapped |
| 283 | * in a document node) to a given Destination. The invocation uses any initial mode set using {@link #setInitialMode(QName)}, |
| 284 | * and any template parameters set using {@link #setInitialTemplateParameters(java.util.Map, boolean)}. |
| 285 | * |
| 286 | * <p>This method does not set the global context item for the transformation. If that is required, it |
| 287 | * can be done separately using the method {@link #setGlobalContextItem(XdmItem)}.</p> |
| 288 | * |
| 289 | * @param source the source document. For streamed processing, this must be a SAXSource or StreamSource. |
| 290 | * <p>Note: supplying a <code>DOMSource</code> is allowed, but is much less efficient than using a |
| 291 | * <code>StreamSource</code> or <code>SAXSource</code> and leaving Saxon to build the tree in its own |
| 292 | * internal format. To apply more than one transformation to the same source document, the source document |
| 293 | * tree can be pre-built using a {@link DocumentBuilder}.</p> |
| 294 | * @param destination the destination of the principal result of the transformation. |
| 295 | * If the destination is a {@link Serializer}, then the serialization |
| 296 | * parameters set in the serializer are combined with those defined in the stylesheet |
| 297 | * (the parameters set in the serializer take precedence). |
| 298 | * @throws SaxonApiException if the transformation fails |
| 299 | */ |
| 300 | |
| 301 | public void applyTemplates(Source source, Destination destination) throws SaxonApiException { |
| 302 | |
| 303 | Objects.requireNonNull(destination); |
| 304 | if (source == null) { |
| 305 | XPathException err = new XPathException("No initial match selection supplied", "XTDE0044"); |
| 306 | throw new SaxonApiException(err); |
| 307 | } |
| 308 | prime(); |
| 309 | try { |
| 310 | Receiver sOut = getDestinationReceiver(controller, destination); |
| 311 | applyTemplatesToSource(source, sOut); |
| 312 | destination.closeAndNotify(); |
| 313 | } catch (XPathException e) { |
| 314 | if (!e.hasBeenReported()) { |
| 315 | try { |
| 316 | getErrorListener().fatalError(e); |
| 317 | } catch (TransformerException e1) { |
| 318 | // ignore secondary error |
| 319 | } |
| 320 | } |
| 321 | throw new SaxonApiException(e); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | /** |
| 326 | * Invoke the stylesheet by applying templates to a supplied Source document, returning the raw results |
| 327 | * as an {@link XdmValue}. The invocation uses any initial mode set using {@link #setInitialMode(QName)}, |
| 328 | * and any template parameters set using {@link #setInitialTemplateParameters(java.util.Map, boolean)}. |
| 329 | * |
| 330 | * @param source the source document. For streamed processing, this must be a SAXSource or StreamSource. |
| 331 | * <p>Note: supplying a <code>DOMSource</code> is allowed, but is much less efficient than using a |
| 332 | * <code>StreamSource</code> or <code>SAXSource</code> and leaving Saxon to build the tree in its own |
| 333 | * internal format. To apply more than one transformation to the same source document, the source document |
| 334 | * tree can be pre-built using a {@link DocumentBuilder}.</p> |
| 335 | * @return the raw result of processing the supplied Source using the selected template rule, without |
| 336 | * wrapping the returned sequence in a document node |
| 337 | * @throws SaxonApiException if the transformation fails |
| 338 | */ |
| 339 | |
| 340 | public XdmValue applyTemplates(Source source) throws SaxonApiException { |
| 341 | Objects.requireNonNull(source); |
| 342 | RawDestination raw = new RawDestination(); |
| 343 | applyTemplates(source, raw); |
| 344 | return raw.getXdmValue(); |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Invoke the stylesheet by applying templates to a supplied Source document, sending the results |
| 349 | * to a given Destination. The invocation uses the initial mode set using {@link #setInitialMode(QName)} |
| 350 | * (defaulting to the default mode defined in the stylesheet itself, which by default is the unnamed mode). |
| 351 | * It also uses any template parameters set using {@link #setInitialTemplateParameters(java.util.Map, boolean)}. |
| 352 | * |
| 353 | * <p>The document supplied in the <code>source</code> argument also acts as the global |
| 354 | * context item for the transformation. Any item previously supplied using {@link #setGlobalContextItem(XdmItem)} |
| 355 | * is ignored.</p> |
| 356 | * |
| 357 | * <p>Because this method sets the global context item to the root node of the supplied <code>source</code>, |
| 358 | * it cannot be used when the stylesheet is designed to process streamed input. For streamed processing, |
| 359 | * use {@link #applyTemplates(Source, Destination)} instead.</p> |
| 360 | * |
| 361 | * @param source the source document. |
| 362 | * <p>Note: supplying a <code>DOMSource</code> is allowed, but is much less efficient than using a |
| 363 | * <code>StreamSource</code> or <code>SAXSource</code> and leaving Saxon to build the tree in its own |
| 364 | * internal format. To apply more than one transformation to the same source document, the source document |
| 365 | * tree can be pre-built using a {@link DocumentBuilder}.</p> |
| 366 | * @param destination the destination of the principal result of the transformation. |
| 367 | * If the destination is a {@link Serializer}, then the serialization |
| 368 | * parameters set in the serializer are combined with those defined in the stylesheet |
| 369 | * (the parameters set in the serializer take precedence). |
| 370 | * @throws SaxonApiException if the transformation fails, or if the initial mode in the stylesheet is |
| 371 | * declared to be streamable. |
| 372 | * @since 9.9.1.1 |
| 373 | */ |
| 374 | |
| 375 | public void transform(Source source, Destination destination) throws SaxonApiException { |
| 376 | |
| 377 | Objects.requireNonNull(destination); |
| 378 | if (source == null) { |
| 379 | XPathException err = new XPathException("No initial match selection supplied", "XTDE0044"); |
| 380 | throw new SaxonApiException(err); |
| 381 | } |
| 382 | if (controller.getInitialMode().isDeclaredStreamable()) { |
| 383 | throw new SaxonApiException("Cannot use the transform() method when the initial mode is streamable"); |
| 384 | } |
| 385 | prime(); |
| 386 | try { |
| 387 | NodeInfo sourceNode; |
| 388 | if (source instanceof NodeInfo) { |
| 389 | controller.setGlobalContextItem((NodeInfo)source); |
| 390 | sourceNode = (NodeInfo) source; |
| 391 | } else if (source instanceof DOMSource) { |
| 392 | sourceNode = controller.prepareInputTree(source); |
| 393 | controller.setGlobalContextItem(sourceNode); |
| 394 | } else { |
| 395 | sourceNode = controller.makeSourceTree(source, getSchemaValidationMode().getNumber()); |
| 396 | controller.setGlobalContextItem(sourceNode); |
| 397 | } |
| 398 | |
| 399 | Receiver sOut = getDestinationReceiver(controller, destination); |
| 400 | controller.applyTemplates(sourceNode, sOut); |
| 401 | destination.closeAndNotify(); |
| 402 | } catch (XPathException e) { |
| 403 | if (!e.hasBeenReported()) { |
| 404 | try { |
| 405 | getErrorListener().fatalError(e); |
| 406 | } catch (TransformerException e1) { |
| 407 | // ignore secondary error |
| 408 | } |
| 409 | } |
| 410 | throw new SaxonApiException(e); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | |
| 415 | /** |
| 416 | * Invoke the stylesheet by applying templates to a supplied input sequence, sending the results (wrapped |
| 417 | * in a document node) to a given Destination. The invocation uses any initial mode set using {@link #setInitialMode(QName)}, |
| 418 | * and any template parameters set using {@link #setInitialTemplateParameters(java.util.Map, boolean)}. |
| 419 | * |
| 420 | * @param selection the initial value to which templates are to be applied (equivalent to the <code>select</code> |
| 421 | * attribute of <code>xsl:apply-templates</code>) |
| 422 | * @param destination the destination for the result document. In most cases this causes the raw result of |
| 423 | * the transformation to be wrapped in a document node. However, if the destination |
| 424 | * is a Serializer and the output method is "json" or "adaptive", then |
| 425 | * no wrapping takes place. |
| 426 | * @throws SaxonApiException if the transformation fails |
| 427 | * @since 9.6. Changed in 9.7.0.1 so that if a Serializer is supplied as the Destination, it will not |
| 428 | * be modified by this method to set output properties from the stylesheet; instead, the Serializer |
| 429 | * should be initialized by calling the <code>newSerializer</code> method on this <code>Xslt30Transformer</code> |
| 430 | */ |
| 431 | |
| 432 | public void applyTemplates(XdmValue selection, Destination destination) throws SaxonApiException { |
| 433 | Objects.requireNonNull(selection); |
| 434 | Objects.requireNonNull(destination); |
| 435 | prime(); |
| 436 | try { |
| 437 | Receiver sOut = getDestinationReceiver(controller, destination); |
| 438 | if (baseOutputUriWasSet) { |
| 439 | sOut.setSystemId(getBaseOutputURI()); |
| 440 | } |
| 441 | controller.applyTemplates(selection.getUnderlyingValue(), sOut); |
| 442 | destination.closeAndNotify(); |
| 443 | } catch (XPathException e) { |
| 444 | if (!e.hasBeenReported()) { |
| 445 | try { |
| 446 | getErrorListener().fatalError(e); |
| 447 | } catch (TransformerException e1) { |
| 448 | // ignore secondary error |
| 449 | } |
| 450 | } |
| 451 | throw new SaxonApiException(e); |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | /** |
| 456 | * Invoke the stylesheet by applying templates to a supplied input sequence, returning the raw results. |
| 457 | * as an {@link XdmValue}. The invocation uses any initial mode set using {@link #setInitialMode(QName)}, |
| 458 | * and any template parameters set using {@link #setInitialTemplateParameters(java.util.Map, boolean)}. |
| 459 | * |
| 460 | * @param selection the initial value to which templates are to be applied (equivalent to the <code>select</code> |
| 461 | * attribute of <code>xsl:apply-templates</code>) |
| 462 | * @return the raw result of applying templates to the supplied selection value, without wrapping in |
| 463 | * a document node or serializing the result. If there is more that one item in the selection, the result |
| 464 | * is the concatenation of the results of applying templates to each item in turn. |
| 465 | * @throws SaxonApiException if the transformation fails |
| 466 | */ |
| 467 | |
| 468 | public XdmValue applyTemplates(XdmValue selection) throws SaxonApiException { |
| 469 | Objects.requireNonNull(selection); |
| 470 | RawDestination raw = new RawDestination(); |
| 471 | applyTemplates(selection, raw); |
| 472 | return raw.getXdmValue(); |
| 473 | } |
| 474 | |
| 475 | /** |
| 476 | * Invoke a transformation by calling a named template. The results of calling |
| 477 | * the template are wrapped in a document node, which is then sent to the specified |
| 478 | * destination. If {@link #setInitialTemplateParameters(java.util.Map, boolean)} has been |
| 479 | * called, then the parameters supplied are made available to the called template (no error |
| 480 | * occurs if parameters are supplied that are not used). |
| 481 | * |
| 482 | * @param templateName the name of the initial template. This must match the name of a |
| 483 | * public named template in the stylesheet. If the value is null, |
| 484 | * the QName <code>xsl:initial-template</code> is used. |
| 485 | * @param destination the destination for the result document. |
| 486 | * @throws SaxonApiException if there is no named template with this name, or if any dynamic |
| 487 | * error occurs during the transformation |
| 488 | * @since 9.6. Changed in 9.7.0.1 so that if a Serializer is supplied as the Destination, it will not |
| 489 | * be modified by this method to set output properties from the stylesheet; instead, the Serializer |
| 490 | * should be initialized by calling the <code>newSerializer</code> method on this <code>Xslt30Transformer</code> |
| 491 | */ |
| 492 | |
| 493 | public void callTemplate(QName templateName, Destination destination) throws SaxonApiException { |
| 494 | Objects.requireNonNull(destination); |
| 495 | prime(); |
| 496 | if (templateName == null) { |
| 497 | templateName = new QName("xsl", NamespaceConstant.XSLT, "initial-template"); |
| 498 | } |
| 499 | try { |
| 500 | Receiver sOut = getDestinationReceiver(controller, destination); |
| 501 | if (baseOutputUriWasSet) { |
| 502 | sOut.setSystemId(getBaseOutputURI()); |
| 503 | } |
| 504 | //sOut.open(); |
| 505 | controller.callTemplate(templateName.getStructuredQName(), sOut); |
| 506 | //sOut.close(); |
| 507 | destination.closeAndNotify(); |
| 508 | } catch (XPathException e) { |
| 509 | destination.closeAndNotify(); |
| 510 | if (!e.hasBeenReported()) { |
| 511 | try { |
| 512 | getErrorListener().fatalError(e); |
| 513 | } catch (TransformerException e1) { |
| 514 | // ignore secondary error |
| 515 | } |
| 516 | } |
| 517 | throw new SaxonApiException(e); |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | private void setBuildTreeConditionally(Destination destination) { |
| 522 | // controller.setBuildTree( |
| 523 | // destination.isRequiresTree(controller.getExecutable().getDefaultOutputProperties())); |
| 524 | } |
| 525 | |
| 526 | /** |
| 527 | * Invoke a transformation by calling a named template. The results of calling |
| 528 | * the template are returned as a raw value, without wrapping in a document node |
| 529 | * or serializing. |
| 530 | * |
| 531 | * @param templateName the name of the initial template. This must match the name of a |
| 532 | * public named template in the stylesheet. If the value is null, |
| 533 | * the QName <code>xsl:initial-template</code> is used. |
| 534 | * @return the raw results of the called template, without wrapping in a document node |
| 535 | * or serialization. |
| 536 | * @throws SaxonApiException if there is no named template with this name, or if any dynamic |
| 537 | * error occurs during the transformation |
| 538 | */ |
| 539 | |
| 540 | |
| 541 | public XdmValue callTemplate(QName templateName) throws SaxonApiException { |
| 542 | RawDestination dest = new RawDestination(); |
| 543 | callTemplate(templateName, dest); |
| 544 | return dest.getXdmValue(); |
| 545 | } |
| 546 | |
| 547 | /** |
| 548 | * Call a public user-defined function in the stylesheet. |
| 549 | * |
| 550 | * @param function The name of the function to be called |
| 551 | * @param arguments The values of the arguments to be supplied to the function. These |
| 552 | * will be converted if necessary to the type as defined in the function signature, using |
| 553 | * the function conversion rules. |
| 554 | * @return the result of calling the function. This is the raw result, without wrapping in a document |
| 555 | * node and without serialization. |
| 556 | * @throws SaxonApiException if no function has been defined with the given name and arity; |
| 557 | * or if any of the arguments does not match its required type according to the function |
| 558 | * signature; or if a dynamic error occurs in evaluating the function. |
| 559 | */ |
| 560 | |
| 561 | public XdmValue callFunction(QName function, XdmValue[] arguments) throws SaxonApiException { |
| 562 | Objects.requireNonNull(function); |
| 563 | Objects.requireNonNull(arguments); |
| 564 | prime(); |
| 565 | try { |
| 566 | Component f = getFunctionComponent(function, arguments); |
| 567 | UserFunction uf = (UserFunction) f.getActor(); |
| 568 | Sequence[] vr = typeCheckFunctionArguments(uf, arguments); |
| 569 | |
| 570 | XPathContextMajor context = controller.newXPathContext(); |
| 571 | context.setCurrentComponent(f); |
| 572 | context.setTemporaryOutputState(StandardNames.XSL_FUNCTION); |
| 573 | context.setCurrentOutputUri(null); |
| 574 | Sequence<?> result = uf.call(context, vr); |
| 575 | result = result.materialize(); |
| 576 | return XdmValue.wrap(result); |
| 577 | } catch (XPathException e) { |
| 578 | if (!e.hasBeenReported()) { |
| 579 | try { |
| 580 | getErrorListener().fatalError(e); |
| 581 | } catch (TransformerException e1) { |
| 582 | // ignore secondary error |
| 583 | } |
| 584 | } |
| 585 | throw new SaxonApiException(e); |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | private Component getFunctionComponent(QName function, XdmValue[] arguments) throws XPathException { |
| 590 | SymbolicName fName = new SymbolicName.F(function.getStructuredQName(), arguments.length); |
| 591 | PreparedStylesheet pss = (PreparedStylesheet) controller.getExecutable(); |
| 592 | Component f = pss.getComponent(fName); |
| 593 | if (f == null) { |
| 594 | throw new XPathException("No public function with name " + function.getClarkName() + |
| 595 | " and arity " + arguments.length + " has been declared in the stylesheet", "XTDE0041"); |
| 596 | } else if (f.getVisibility() != Visibility.FINAL && f.getVisibility() != Visibility.PUBLIC) { |
| 597 | throw new XPathException("Cannot invoke " + fName + " externally, because it is not public", "XTDE0041"); |
| 598 | } |
| 599 | return f; |
| 600 | } |
| 601 | |
| 602 | private Sequence[] typeCheckFunctionArguments(UserFunction uf, XdmValue[] arguments) throws XPathException { |
| 603 | Configuration config = processor.getUnderlyingConfiguration(); |
| 604 | UserFunctionParameter[] params = uf.getParameterDefinitions(); |
| 605 | GroundedValue<?>[] vr = |
| 606 | (GroundedValue<?>[])new GroundedValue[arguments.length]; |
| 607 | for (int i = 0; i < arguments.length; i++) { |
| 608 | net.sf.saxon.value.SequenceType type = params[i].getRequiredType(); |
| 609 | vr[i] = arguments[i].getUnderlyingValue(); |
| 610 | if (!type.matches(vr[i], config.getTypeHierarchy())) { |
| 611 | RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.FUNCTION, uf.getFunctionName().getDisplayName(), i); |
| 612 | Sequence<?> converted = config.getTypeHierarchy().applyFunctionConversionRules(vr[i], type, role, ExplicitLocation.UNKNOWN_LOCATION); |
| 613 | vr[i] = converted.materialize(); |
| 614 | } |
| 615 | } |
| 616 | return vr; |
| 617 | } |
| 618 | |
| 619 | /** |
| 620 | * Call a public user-defined function in the stylesheet, wrapping the result in an XML document, and sending |
| 621 | * this document to a specified destination |
| 622 | * |
| 623 | * @param function The name of the function to be called |
| 624 | * @param arguments The values of the arguments to be supplied to the function. These |
| 625 | * will be converted if necessary to the type as defined in the function signature, using |
| 626 | * the function conversion rules. |
| 627 | * @param destination the destination of the result document produced by wrapping the result of the apply-templates |
| 628 | * call in a document node. |
| 629 | * @throws SaxonApiException in the event of a dynamic error |
| 630 | * @since 9.6. Changed in 9.7.0.1 so that if a Serializer is supplied as the Destination, it will not |
| 631 | * be modified by this method to set output properties from the stylesheet; instead, the Serializer |
| 632 | * should be initialized by calling the <code>newSerializer</code> method on this <code>Xslt30Transformer</code> |
| 633 | */ |
| 634 | |
| 635 | public void callFunction(QName function, XdmValue[] arguments, Destination destination) throws SaxonApiException { |
| 636 | prime(); |
| 637 | try { |
| 638 | Component f = getFunctionComponent(function, arguments); |
| 639 | UserFunction uf = (UserFunction) f.getActor(); |
| 640 | Sequence[] vr = typeCheckFunctionArguments(uf, arguments); |
| 641 | |
| 642 | XPathContextMajor context = controller.newXPathContext(); |
| 643 | context.setCurrentComponent(f); |
| 644 | context.setTemporaryOutputState(StandardNames.XSL_FUNCTION); |
| 645 | context.setCurrentOutputUri(null); |
| 646 | |
| 647 | SerializationProperties params = controller.getExecutable().getPrimarySerializationProperties(); |
| 648 | Receiver receiver = destination.getReceiver(controller.makePipelineConfiguration(), params); |
| 649 | receiver.open(); |
| 650 | if (!(receiver instanceof SequenceReceiver)) { |
| 651 | receiver = new TreeReceiver(receiver); |
| 652 | } |
| 653 | context.setReceiver(receiver); |
| 654 | uf.process(vr, context); |
| 655 | receiver.close(); |
| 656 | |
| 657 | } catch (XPathException e) { |
| 658 | if (!e.hasBeenReported()) { |
| 659 | try { |
| 660 | getErrorListener().fatalError(e); |
| 661 | } catch (TransformerException e1) { |
| 662 | // ignore secondary error |
| 663 | } |
| 664 | } |
| 665 | throw new SaxonApiException(e); |
| 666 | } |
| 667 | |
| 668 | destination.closeAndNotify(); |
| 669 | } |
| 670 | |
| 671 | /** |
| 672 | * Construct a {@link Destination} object whose effect is to perform this transformation |
| 673 | * on any input that is sent to that {@link Destination}: for example, it allows this transformation |
| 674 | * to post-process the results of another transformation. |
| 675 | * <p> |
| 676 | * This method allows a pipeline of transformations to be created in which |
| 677 | * one transformation is used as the destination of another. The transformations |
| 678 | * may use streaming, in which case intermediate results will not be materialized |
| 679 | * in memory. If a transformation does not use streaming, then its input will |
| 680 | * first be assembled in memory as a node tree. |
| 681 | * <p> |
| 682 | * The {@link Destination} returned by this method performs <em>sequence normalization</em> |
| 683 | * as defined in the serialization specification: that is, the raw result of the transformation |
| 684 | * sent to this destination is wrapped into a document node. Any item-separator present in |
| 685 | * any serialization parameters is ignored (adjacent atomic values are separated by whitespace). |
| 686 | * This makes the method unsuitable for passing intermediate results other than XML document |
| 687 | * nodes. |
| 688 | * |
| 689 | * @return a {@link Destination} which accepts an XML document (typically as a stream |
| 690 | * of events) and which transforms this supplied XML document (possibly using streaming) |
| 691 | * as defined by the stylesheet from which which this {@code Xslt30Transformer} was generated, |
| 692 | * sending the principal result of the transformation to the supplied {@code finalDestination}. |
| 693 | * The transformation is performed as if by the {@link #applyTemplates(Source, Destination)} |
| 694 | * method: that is, by applying templates to the root node of the supplied XML document. |
| 695 | * @since 9.9 |
| 696 | */ |
| 697 | |
| 698 | public Destination asDocumentDestination(Destination finalDestination) { |
| 699 | return new AbstractDestination() { |
| 700 | |
| 701 | Receiver r; |
| 702 | @Override |
| 703 | public Receiver getReceiver(PipelineConfiguration pipe, SerializationProperties params) throws SaxonApiException { |
| 704 | Receiver rt = getReceivingTransformer(controller, globalParameterSet, finalDestination); |
| 705 | rt = new SequenceNormalizerWithSpaceSeparator(rt); |
| 706 | rt.setPipelineConfiguration(pipe); |
| 707 | return r =rt; |
| 708 | } |
| 709 | |
| 710 | @Override |
| 711 | public void close() throws SaxonApiException { |
| 712 | try { |
| 713 | r.close(); |
| 714 | } catch (XPathException e) { |
| 715 | throw new SaxonApiException(e); |
| 716 | } |
| 717 | } |
| 718 | }; |
| 719 | } |
| 720 | |
| 721 | /** |
| 722 | * Create a serializer initialised to use the default output parameters defined in the stylesheet. |
| 723 | * These serialization parameters can be overridden by use of |
| 724 | * {@link Serializer#setOutputProperty(Serializer.Property, String)}. |
| 725 | * |
| 726 | * @since 9.7.0.1 |
| 727 | */ |
| 728 | |
| 729 | public Serializer newSerializer() { |
| 730 | Serializer serializer = processor.newSerializer(); |
| 731 | serializer.setOutputProperties(controller.getExecutable().getPrimarySerializationProperties()); |
| 732 | return serializer; |
| 733 | } |
| 734 | |
| 735 | /** |
| 736 | * Create a serializer initialised to use the default output parameters defined in the stylesheet. |
| 737 | * These serialization parameters can be overridden by use of |
| 738 | * {@link Serializer#setOutputProperty(Serializer.Property, String)}. |
| 739 | * |
| 740 | * @param file the output file to which the serializer will write its output. As well as initializing |
| 741 | * the serializer to write to this output file, this method sets the base output URI of this |
| 742 | * Xslt30Transformer to be the URI of this file. |
| 743 | * @since 9.7.0.1 |
| 744 | */ |
| 745 | |
| 746 | public Serializer newSerializer(File file) { |
| 747 | Serializer serializer = processor.newSerializer(file); |
| 748 | serializer.setOutputProperties(controller.getExecutable().getPrimarySerializationProperties()); |
| 749 | setBaseOutputURI(file.toURI().toString()); |
| 750 | return serializer; |
| 751 | } |
| 752 | |
| 753 | /** |
| 754 | * Create a serializer initialised to use the default output parameters defined in the stylesheet. |
| 755 | * These serialization parameters can be overridden by use of |
| 756 | * {@link Serializer#setOutputProperty(Serializer.Property, String)}. |
| 757 | * |
| 758 | * @param writer the Writer to which the serializer will write |
| 759 | * @since 9.7.0.1 |
| 760 | */ |
| 761 | |
| 762 | public Serializer newSerializer(Writer writer) { |
| 763 | Serializer serializer = newSerializer(); |
| 764 | serializer.setOutputWriter(writer); |
| 765 | return serializer; |
| 766 | } |
| 767 | |
| 768 | /** |
| 769 | * Create a serializer initialised to use the default output parameters defined in the stylesheet. |
| 770 | * These serialization parameters can be overridden by use of |
| 771 | * {@link Serializer#setOutputProperty(Serializer.Property, String)}. |
| 772 | * |
| 773 | * @param stream the output stream to which the serializer will write |
| 774 | * @since 9.7.0.1 |
| 775 | */ |
| 776 | |
| 777 | public Serializer newSerializer(OutputStream stream) { |
| 778 | Serializer serializer = newSerializer(); |
| 779 | serializer.setOutputStream(stream); |
| 780 | return serializer; |
| 781 | } |
| 782 | |
| 783 | |
| 784 | |
| 785 | |
| 786 | } |
| 787 |