| 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.event.PipelineConfiguration; |
| 11 | import net.sf.saxon.event.Receiver; |
| 12 | import net.sf.saxon.event.SequenceNormalizerWithSpaceSeparator; |
| 13 | import net.sf.saxon.expr.instruct.GlobalContextRequirement; |
| 14 | import net.sf.saxon.expr.instruct.GlobalParameterSet; |
| 15 | import net.sf.saxon.lib.NamespaceConstant; |
| 16 | import net.sf.saxon.om.Item; |
| 17 | import net.sf.saxon.om.NodeInfo; |
| 18 | import net.sf.saxon.om.Sequence; |
| 19 | import net.sf.saxon.serialize.SerializationProperties; |
| 20 | import net.sf.saxon.trans.XPathException; |
| 21 | import net.sf.saxon.trans.XsltController; |
| 22 | import net.sf.saxon.tree.linked.DocumentImpl; |
| 23 | |
| 24 | import javax.xml.transform.Source; |
| 25 | import javax.xml.transform.TransformerException; |
| 26 | import javax.xml.transform.dom.DOMSource; |
| 27 | import java.net.URI; |
| 28 | |
| 29 | /** |
| 30 | * An {@code XsltTransformer} represents a compiled and loaded stylesheet ready for execution. |
| 31 | * The {@code XsltTransformer} holds details of the dynamic evaluation context for the stylesheet. |
| 32 | * <p> |
| 33 | * An {@code XsltTransformer} must not be used concurrently in multiple threads. |
| 34 | * It is safe, however, to reuse the object within a single thread to run the same |
| 35 | * stylesheet several times. Running the stylesheet does not change the context |
| 36 | * that has been established. |
| 37 | * <p> |
| 38 | * An {@code XsltTransformer} is always constructed by running the {@code Load} |
| 39 | * method of an {@link XsltExecutable}. |
| 40 | * <p> |
| 41 | * An {@code XsltTransformer} is itself a {@link Destination}. This means it is possible to use |
| 42 | * one {@code XsltTransformer} as the destination to receive the results of another transformation, |
| 43 | * this providing a simple way for transformations to be chained into a pipeline. Note however that a |
| 44 | * when the input to a transformation is supplied in this way, it will always be built as a tree in |
| 45 | * memory, rather than the transformation being streamed. As a {@code Destination}, the transformer |
| 46 | * performs <i>Sequence Normalization</i> on its input; that is, it converts the input to a single |
| 47 | * document node. (The main reason for this is that when chaining XSLT transformations, the raw |
| 48 | * output of the first stylesheet is often an element node, but the second stylesheet traditionally |
| 49 | * expects a document node.) |
| 50 | * |
| 51 | * @since 9.0 |
| 52 | */ |
| 53 | public class XsltTransformer extends AbstractXsltTransformer implements Destination { |
| 54 | |
| 55 | private QName initialTemplateName; |
| 56 | private GlobalParameterSet parameters; |
| 57 | private Source initialSource; |
| 58 | private Destination destination; |
| 59 | private DestinationHelper destinationHelper = new DestinationHelper(this); |
| 60 | private URI destinationBaseUri; |
| 61 | |
| 62 | /** |
| 63 | * Protected constructor |
| 64 | * |
| 65 | * @param processor the S9API processor |
| 66 | * @param controller the Saxon controller object |
| 67 | * @param staticParameters the static parameters supplied at stylesheet compile time |
| 68 | */ |
| 69 | |
| 70 | protected XsltTransformer(Processor processor, XsltController controller, GlobalParameterSet staticParameters) { |
| 71 | super(processor, controller); |
| 72 | parameters = new GlobalParameterSet(/*staticParameters*/); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Set the base URI of the resource being written to this destination |
| 77 | * |
| 78 | * @param baseURI the base URI to be used |
| 79 | */ |
| 80 | |
| 81 | public void setDestinationBaseURI(URI baseURI) { |
| 82 | this.destinationBaseUri = baseURI; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Get the base URI of the resource being written to this destination |
| 87 | * |
| 88 | * @return the baseURI, or null if none is known |
| 89 | */ |
| 90 | |
| 91 | public URI getDestinationBaseURI() { |
| 92 | return destinationBaseUri; |
| 93 | } |
| 94 | |
| 95 | @Override |
| 96 | public void onClose(Action listener) { |
| 97 | destinationHelper.onClose(listener); |
| 98 | } |
| 99 | |
| 100 | @Override |
| 101 | public void closeAndNotify() throws SaxonApiException { |
| 102 | destinationHelper.closeAndNotify(); |
| 103 | } |
| 104 | |
| 105 | /** |
| 106 | * Set the initial named template for the transformation |
| 107 | * |
| 108 | * @param templateName the name of the initial template, or null to indicate |
| 109 | * that there should be no initial named template. Changed |
| 110 | * in 9.9: the method no longer checks that the named |
| 111 | * template exists. |
| 112 | */ |
| 113 | |
| 114 | public void setInitialTemplate(QName templateName) { |
| 115 | initialTemplateName = templateName; |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Get the initial named template for the transformation, if one has been set |
| 120 | * |
| 121 | * @return the name of the initial template, or null if none has been set |
| 122 | */ |
| 123 | |
| 124 | public QName getInitialTemplate() { |
| 125 | return initialTemplateName; |
| 126 | } |
| 127 | |
| 128 | |
| 129 | /** |
| 130 | * Set the source document for the transformation. |
| 131 | * <p>If the source is an instance of {@link net.sf.saxon.om.NodeInfo}, the supplied node is used |
| 132 | * directly as the initial context item of the transformation.</p> |
| 133 | * <p>If the source is an instance of {@link javax.xml.transform.dom.DOMSource}, the DOM node identified |
| 134 | * by the DOMSource is wrapped as a Saxon node, and this is then used as the context item.</p> |
| 135 | * <p>In other cases a new Saxon tree will be built by the transformation engine when the |
| 136 | * transformation starts, unless it is a Saxon-EE streaming transformation, in which case the |
| 137 | * document is processed in streaming fashion as it is being parsed.</p> |
| 138 | * <p>To run a transformation in streaming mode, the source should be supplied as an instance |
| 139 | * of {@link javax.xml.transform.stream.StreamSource} or {@link javax.xml.transform.sax.SAXSource}. |
| 140 | * </p> |
| 141 | * <p>Some kinds of {@code Source} (for example {@code StreamSource} and |
| 142 | * {@code SAXSource}are consumed by use; others (such as {@code DOMSource}) are immutable. |
| 143 | * In the general case, therefore, the {@code Source} object that is supplied by this method |
| 144 | * does not survive a call on {@link #transform()}.</p> |
| 145 | * |
| 146 | * @param source the principal source document for the transformation |
| 147 | */ |
| 148 | |
| 149 | public void setSource(Source source) { |
| 150 | if (source instanceof NodeInfo) { |
| 151 | setInitialContextNode(new XdmNode((NodeInfo) source)); |
| 152 | } else if (source instanceof DOMSource) { |
| 153 | if (((DOMSource)source).getNode() == null) { |
| 154 | DocumentImpl doc = new DocumentImpl(); |
| 155 | doc.setConfiguration(controller.getConfiguration()); |
| 156 | setInitialContextNode(new XdmNode(doc)); |
| 157 | } else { |
| 158 | NodeInfo n = processor.getUnderlyingConfiguration().unravel(source); |
| 159 | setInitialContextNode(new XdmNode(n)); |
| 160 | } |
| 161 | } else { |
| 162 | initialSource = source; |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Set the initial context node for the transformation. |
| 168 | * <p>In XSLT 3.0 terms, this sets the initial match selection (the sequence to which the |
| 169 | * initial implicit call of xsl:applyTemplates is applied). It also determines how the |
| 170 | * global context item for evaluating global variables is set: following the XSLT 1.0 and 2.0 rules |
| 171 | * (XSLT 2.0 section 9.5): "For a global variable or the default value of a stylesheet parameter, |
| 172 | * the expression or sequence constructor specifying the variable value is evaluated with a singleton |
| 173 | * focus based on the root node of the tree containing the initial context node." </p> |
| 174 | * <p>This value is ignored in the case where the {@link XsltTransformer} is used as the |
| 175 | * {@link Destination} of another process. In that case the initial context node will always |
| 176 | * be the document node of the document that is being streamed to this destination.</p> |
| 177 | * <p>Calling this method has the side-effect of setting the initial source to null.</p> |
| 178 | * |
| 179 | * @param node the initial context node, or null if there is to be no initial context node |
| 180 | * @throws SaxonApiUncheckedException if the node is unsuitable, for example if it was |
| 181 | * built using the wrong Configuration |
| 182 | */ |
| 183 | |
| 184 | public void setInitialContextNode(XdmNode node) throws SaxonApiUncheckedException { |
| 185 | try { |
| 186 | if (node == null) { |
| 187 | initialSource = null; |
| 188 | controller.setGlobalContextItem(null); |
| 189 | } else { |
| 190 | initialSource = node.getUnderlyingNode(); |
| 191 | controller.setGlobalContextItem(node.getUnderlyingNode().getRoot()); |
| 192 | } |
| 193 | } catch (XPathException e) { |
| 194 | throw new SaxonApiUncheckedException(e); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Get the initial context node for the transformation, if one has been set |
| 200 | * |
| 201 | * @return the initial context node, or null if none has been set. This will not necessarily |
| 202 | * be the same {@link XdmNode} instance as was supplied, but it will be an XdmNode object that represents |
| 203 | * the same underlying node. |
| 204 | */ |
| 205 | |
| 206 | public XdmNode getInitialContextNode() { |
| 207 | if (initialSource instanceof NodeInfo) { |
| 208 | return (XdmNode) XdmValue.wrap((NodeInfo) initialSource); |
| 209 | } else { |
| 210 | return null; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /** |
| 215 | * Set the value of a stylesheet parameter. |
| 216 | * |
| 217 | * <p>If the stylesheet does not have a parameter with this name, then the supplied value will |
| 218 | * simply be ignored (no error occurs)</p> |
| 219 | * |
| 220 | * <p>If the stylesheet has a parameter with this name, and the supplied value does not match the |
| 221 | * required type, then no error will be reported at this stage, but a dynamic error will occur |
| 222 | * when the parameter value is first used. Supplied values are converted to the required type |
| 223 | * using the function conversion rules.</p> |
| 224 | * |
| 225 | * <p>If the stylesheet has a parameter with this name, and the parameter is declared |
| 226 | * with <code>static="yes"</code>, or if a parameter with the same name was supplied to the |
| 227 | * {@link XsltCompiler}, then no error will be reported at this stage, but an error |
| 228 | * will be reported when the transformation is initiated. Static parameters must be initialized |
| 229 | * using {@link XsltCompiler#setParameter(QName, XdmValue)}.</p> |
| 230 | * |
| 231 | * @param name the name of the stylesheet parameter, as a QName |
| 232 | * @param value the value of the stylesheet parameter, or null to clear a previously set value |
| 233 | * @throws SaxonApiUncheckedException if the value is lazily evaluated, and evaluation fails |
| 234 | */ |
| 235 | |
| 236 | public void setParameter(QName name, XdmValue value) { |
| 237 | try { |
| 238 | parameters.put(name.getStructuredQName(), |
| 239 | value == null ? null : ((Sequence<?>) value.getUnderlyingValue()).materialize()); |
| 240 | } catch (XPathException e) { |
| 241 | throw new SaxonApiUncheckedException(e); |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Clear the values of all parameters that have been set |
| 247 | */ |
| 248 | |
| 249 | public void clearParameters() { |
| 250 | parameters = new GlobalParameterSet(); |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Get the value that has been set for a stylesheet parameter |
| 255 | * |
| 256 | * @param name the parameter whose name is required |
| 257 | * @return the value that has been set for the parameter, or null if no value has been set |
| 258 | */ |
| 259 | |
| 260 | public XdmValue getParameter(QName name) { |
| 261 | Sequence<?> oval = parameters.get(name.getStructuredQName()); |
| 262 | return oval == null ? null : XdmValue.wrap(oval); |
| 263 | } |
| 264 | |
| 265 | /** |
| 266 | * Set the destination to be used for the result of the transformation. |
| 267 | * <p> |
| 268 | * This method can be used to chain transformations into a pipeline, by using one |
| 269 | * {@link XsltTransformer} as the destination of another |
| 270 | * <p> |
| 271 | * The {@code Destination} object will generally be modified by a transformation |
| 272 | * (that is, by a call on {@link #transform()}), and in general a {@code Destination} |
| 273 | * cannot be used more than once. Therefore, if this {@code XsltTransformer} is used |
| 274 | * for multiple transformations then a new {@code Destination} should be set for each one. |
| 275 | * |
| 276 | * @param destination the destination to be used for the result of this transformation |
| 277 | */ |
| 278 | |
| 279 | public void setDestination(Destination destination) { |
| 280 | this.destination = destination; |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Get the destination that was specified in a previous call of {@link #setDestination} |
| 285 | * |
| 286 | * @return the destination, or null if none has been supplied |
| 287 | */ |
| 288 | |
| 289 | public Destination getDestination() { |
| 290 | return destination; |
| 291 | } |
| 292 | |
| 293 | /** |
| 294 | * Perform the transformation. If this method is used, a destination must have been supplied |
| 295 | * previously. |
| 296 | * |
| 297 | * <p>Calling this method will in general consume any {@code Source} and {@code Destination} |
| 298 | * that have been supplied, so a new {@code Source} and {@code Destination} are needed for each |
| 299 | * transformation. Other properties of this {@code XsltTransformer} (for example, the values |
| 300 | * of parameters, the initial template, and initial mode) are left unchanged after the |
| 301 | * transformation completes.</p> |
| 302 | * |
| 303 | * <p>If a named template has been supplied as the entry point (using {@link #setInitialTemplate(QName)}, |
| 304 | * then that is used; if a source has also been supplied (using {@link #setSource(Source)}) then that |
| 305 | * is used to provide the global context item.</p> |
| 306 | * |
| 307 | * <p>If no named template has been supplied, then (a) if a source has been supplied |
| 308 | * (using {@link #setSource(Source)}), then that is used as both the global context item and the initial |
| 309 | * match selection; (b) if no source has been supplied, the code looks to see if the stylesheet includes |
| 310 | * a template named {@code xsl:initial-template}, and if so, uses that as the entry point. If there is |
| 311 | * no source and no initial template, the method fails.</p> |
| 312 | * |
| 313 | * @throws SaxonApiException if any dynamic error occurs during the transformation |
| 314 | * @throws IllegalStateException if no destination has been supplied |
| 315 | */ |
| 316 | |
| 317 | public void transform() throws SaxonApiException { |
| 318 | Source initialSelection = initialSource; |
| 319 | boolean reset = false; |
| 320 | if (destination == null) { |
| 321 | throw new IllegalStateException("No destination has been supplied"); |
| 322 | } |
| 323 | |
| 324 | try { |
| 325 | Receiver out = getDestinationReceiver(controller, destination); |
| 326 | GlobalContextRequirement gcr = controller.getExecutable().getGlobalContextRequirement(); |
| 327 | if ((gcr == null || !gcr.isAbsentFocus()) && initialSelection != null) { |
| 328 | if (initialSelection instanceof NodeInfo) { |
| 329 | reset = maybeSetGlobalContextItem((NodeInfo) initialSelection); |
| 330 | } else if (initialSelection instanceof DOMSource) { |
| 331 | NodeInfo node = controller.prepareInputTree(initialSelection); |
| 332 | reset = maybeSetGlobalContextItem(node); |
| 333 | initialSelection = node; |
| 334 | } else { |
| 335 | NodeInfo node = controller.makeSourceTree(initialSelection, getSchemaValidationMode().getNumber()); |
| 336 | reset = maybeSetGlobalContextItem(node); |
| 337 | initialSelection = node; |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | if (baseOutputUriWasSet) { |
| 342 | out.setSystemId(getBaseOutputURI()); |
| 343 | } |
| 344 | controller.initializeController(parameters); |
| 345 | |
| 346 | if (initialTemplateName != null) { |
| 347 | controller.callTemplate(initialTemplateName.getStructuredQName(), out); |
| 348 | } else if (initialSelection != null) { |
| 349 | applyTemplatesToSource(initialSelection, out); |
| 350 | } else { |
| 351 | QName entryPoint = new QName("xsl", NamespaceConstant.XSLT, "initial-template"); |
| 352 | controller.callTemplate(entryPoint.getStructuredQName(), out); |
| 353 | } |
| 354 | destination.closeAndNotify(); |
| 355 | |
| 356 | } catch (XPathException e) { |
| 357 | if (!e.hasBeenReported()) { |
| 358 | try { |
| 359 | getErrorListener().error(e); |
| 360 | } catch (TransformerException e1) { |
| 361 | // no action |
| 362 | } |
| 363 | } |
| 364 | throw new SaxonApiException(e); |
| 365 | } finally { |
| 366 | if (reset) { |
| 367 | controller.clearGlobalContextItem(); |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | private boolean maybeSetGlobalContextItem(Item item) throws XPathException { |
| 373 | if (controller.getGlobalContextItem() == null) { |
| 374 | controller.setGlobalContextItem(item, true); |
| 375 | return true; |
| 376 | } else { |
| 377 | return false; |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | /** |
| 382 | * Return a Receiver which can be used to supply the principal source document for the transformation. |
| 383 | * This method is intended primarily for internal use, though it can also |
| 384 | * be called by a user application that wishes to feed events into the transformation engine. |
| 385 | * <p> |
| 386 | * Saxon calls this method to obtain a Receiver, to which it then sends |
| 387 | * a sequence of events representing the content of an XML document. This method is provided so that |
| 388 | * {@code XsltTransformer} implements {@code Destination}, allowing one transformation |
| 389 | * to receive the results of another in a pipeline. |
| 390 | * <p> |
| 391 | * Before calling this method, the {@link #setDestination} method must be called to supply a destination |
| 392 | * for the transformation. |
| 393 | * <p> |
| 394 | * Note that when an {@code XsltTransformer} is used as a {@code Destination}, the initial |
| 395 | * context node set on that {@code XsltTransformer} using {@link #setInitialContextNode(XdmNode)} is ignored, |
| 396 | * as is the source set using {@link #setSource(javax.xml.transform.Source)}. |
| 397 | * |
| 398 | * @param pipe The Saxon configuration. This is supplied so that the destination can |
| 399 | * use information from the configuration (for example, a reference to the name pool) |
| 400 | * to construct or configure the returned Receiver. |
| 401 | * @param params serialization parameters (not relevant here since we aren't serializing; except |
| 402 | * possibly for the item-separator property) |
| 403 | * @return the Receiver to which events are to be sent. |
| 404 | * @throws SaxonApiException if the Receiver cannot be created |
| 405 | * @throws IllegalStateException if no Destination has been supplied |
| 406 | */ |
| 407 | |
| 408 | public Receiver getReceiver(PipelineConfiguration pipe, SerializationProperties params) throws SaxonApiException { |
| 409 | if (destination == null) { |
| 410 | throw new IllegalStateException("No destination has been supplied"); |
| 411 | } |
| 412 | Receiver rt = getReceivingTransformer(controller, parameters, destination); |
| 413 | rt = new SequenceNormalizerWithSpaceSeparator(rt); |
| 414 | rt.setPipelineConfiguration(pipe); |
| 415 | return rt; |
| 416 | } |
| 417 | |
| 418 | /** |
| 419 | * Close this destination, allowing resources to be released. Used when this XsltTransformer is acting |
| 420 | * as the destination of another transformation. Saxon calls this method when it has finished writing |
| 421 | * to the destination. |
| 422 | */ |
| 423 | |
| 424 | public void close() { |
| 425 | |
| 426 | } |
| 427 | |
| 428 | } |
| 429 |