Class XsltTransformer

  • All Implemented Interfaces:
    Destination

    public class XsltTransformer
    extends java.lang.Object
    implements Destination
    An XsltTransformer represents a compiled and loaded stylesheet ready for execution. The XsltTransformer holds details of the dynamic evaluation context for the stylesheet.

    An XsltTransformer must not be used concurrently in multiple threads. It is safe, however, to reuse the object within a single thread to run the same stylesheet several times. Running the stylesheet does not change the context that has been established. Some of the public methods are synchronized: this is not because multi-threaded execution is supported, rather it is to reduce the damage if multi-threaded execution is attempted.

    An XsltTransformer is always constructed by running the Load method of an XsltExecutable.

    An XsltTransformer is itself a Destination. This means it is possible to use one XsltTransformer as the destination to receive the results of another transformation, this providing a simple way for transformations to be chained into a pipeline. Note however that a when the input to a transformation is supplied in this way, it will always be built as a tree in memory, rather than the transformation being streamed. As a Destination, the transformer performs Sequence Normalization on its input; that is, it converts the input to a single document node. (The main reason for this is that when chaining XSLT transformations, the raw output of the first stylesheet is often an element node, but the second stylesheet traditionally expects a document node.)

    Since:
    9.0
    • Field Detail

      • baseOutputUriWasSet

        protected boolean baseOutputUriWasSet
    • Constructor Detail

      • XsltTransformer

        protected XsltTransformer​(Processor processor,
                                  XsltController controller,
                                  GlobalParameterSet staticParameters)
        Protected constructor
        Parameters:
        processor - the S9API processor
        controller - the Saxon controller object
        staticParameters - the static parameters supplied at stylesheet compile time
    • Method Detail

      • setDestinationBaseURI

        public void setDestinationBaseURI​(java.net.URI baseURI)
        Set the base URI of the resource being written to this destination
        Specified by:
        setDestinationBaseURI in interface Destination
        Parameters:
        baseURI - the base URI to be used
      • getDestinationBaseURI

        public java.net.URI getDestinationBaseURI()
        Get the base URI of the resource being written to this destination
        Specified by:
        getDestinationBaseURI in interface Destination
        Returns:
        the baseURI, or null if none is known
      • onClose

        public void onClose​(Action listener)
        Description copied from interface: Destination
        Register a listener to be notified when a Outputter linked to this destination is closed.

        Example: destination.onClose(() -> System.out.println("Finished writing to " + uri)

        The method must be called before the call on Destination.getReceiver(PipelineConfiguration, SerializationProperties); the effect of calling it after getting a Receiver, but before closing the Outputter, is undefined.

        Specified by:
        onClose in interface Destination
        Parameters:
        listener - an object to be notified when writing to the destination is successfully completed
      • closeAndNotify

        public void closeAndNotify()
                            throws SaxonApiException
        Description copied from interface: Destination
        Close the destination and notify all registered listeners that it has been closed. This method is intended for internal use by Saxon. The method first calls Destination.close() to close the destination, then it calls Consumer.accept(T) on each of the listeners in turn to notify the fact that it has been closed.
        Specified by:
        closeAndNotify in interface Destination
        Throws:
        SaxonApiException - if the close() method throws SaxonApiException.
      • setInitialTemplate

        public void setInitialTemplate​(QName templateName)
        Set the initial named template for the transformation
        Parameters:
        templateName - the name of the initial template, or null to indicate that there should be no initial named template. Changed in 9.9: the method no longer checks that the named template exists.
      • getInitialTemplate

        public QName getInitialTemplate()
        Get the initial named template for the transformation, if one has been set
        Returns:
        the name of the initial template, or null if none has been set
      • setSource

        public void setSource​(javax.xml.transform.Source source)
        Set the source document for the transformation.

        If the source is an instance of NodeInfo, the supplied node is used directly as the initial context item of the transformation.

        If the source is an instance of DOMSource, the DOM node identified by the DOMSource is wrapped as a Saxon node, and this is then used as the context item.

        In other cases a new Saxon tree will be built by the transformation engine when the transformation starts, unless it is a Saxon-EE streaming transformation, in which case the document is processed in streaming fashion as it is being parsed.

        To run a transformation in streaming mode, the source should be supplied as an instance of StreamSource or SAXSource.

        Some kinds of Source (for example StreamSource and SAXSourceare consumed by use; others (such as DOMSource) are immutable. In the general case, therefore, the Source object that is supplied by this method does not survive a call on transform().

        Parameters:
        source - the principal source document for the transformation
      • setInitialContextNode

        public void setInitialContextNode​(XdmNode node)
                                   throws SaxonApiUncheckedException
        Set the initial context node for the transformation.

        In XSLT 3.0 terms, this sets the initial match selection (the sequence to which the initial implicit call of xsl:applyTemplates is applied). It also determines how the global context item for evaluating global variables is set: following the XSLT 1.0 and 2.0 rules (XSLT 2.0 section 9.5): "For a global variable or the default value of a stylesheet parameter, the expression or sequence constructor specifying the variable value is evaluated with a singleton focus based on the root node of the tree containing the initial context node."

        This value is ignored in the case where the XsltTransformer is used as the Destination of another process. In that case the initial context node will always be the document node of the document that is being streamed to this destination.

        Calling this method has the side-effect of setting the initial source to null.

        Parameters:
        node - the initial context node, or null if there is to be no initial context node
        Throws:
        SaxonApiUncheckedException - if the node is unsuitable, for example if it was built using the wrong Configuration
      • getInitialContextNode

        public XdmNode getInitialContextNode()
        Get the initial context node for the transformation, if one has been set
        Returns:
        the initial context node, or null if none has been set. This will not necessarily be the same XdmNode instance as was supplied, but it will be an XdmNode object that represents the same underlying node.
      • setParameter

        public void setParameter​(QName name,
                                 XdmValue value)
        Set the value of a stylesheet parameter.

        If the stylesheet does not have a parameter with this name, then the supplied value will simply be ignored (no error occurs)

        If the stylesheet has a parameter with this name, and the supplied value does not match the required type, then no error will be reported at this stage, but a dynamic error will occur when the parameter value is first used. Supplied values are converted to the required type using the function conversion rules.

        If the stylesheet has a parameter with this name, and the parameter is declared with static="yes", or if a parameter with the same name was supplied to the XsltCompiler, then no error will be reported at this stage, but an error will be reported when the transformation is initiated. Static parameters must be initialized using XsltCompiler.setParameter(QName, XdmValue).

        Parameters:
        name - the name of the stylesheet parameter, as a QName
        value - the value of the stylesheet parameter, or null to clear a previously set value
        Throws:
        SaxonApiUncheckedException - if the value is lazily evaluated, and evaluation fails
      • clearParameters

        public void clearParameters()
        Clear the values of all parameters that have been set
      • getParameter

        public XdmValue getParameter​(QName name)
        Get the value that has been set for a stylesheet parameter
        Parameters:
        name - the parameter whose name is required
        Returns:
        the value that has been set for the parameter, or null if no value has been set
      • setDestination

        public void setDestination​(Destination destination)
        Set the destination to be used for the result of the transformation.

        This method can be used to chain transformations into a pipeline, by using one XsltTransformer as the destination of another

        The Destination object will generally be modified by a transformation (that is, by a call on transform()), and in general a Destination cannot be used more than once. Therefore, if this XsltTransformer is used for multiple transformations then a new Destination should be set for each one.

        Parameters:
        destination - the destination to be used for the result of this transformation
      • transform

        public void transform()
                       throws SaxonApiException
        Perform the transformation. If this method is used, a destination must have been supplied previously.

        Calling this method will in general consume any Source and Destination that have been supplied, so a new Source and Destination are needed for each transformation. Other properties of this XsltTransformer (for example, the values of parameters, the initial template, and initial mode) are left unchanged after the transformation completes.

        If no source has been supplied (using setSource(Source)), then the method looks to see whether an initial named template has been supplied (using setInitialTemplate(QName), and if so, the transformation starts with that named template. In the absence of an initial named template, it looks to see if the stylesheet includes a template named xsl:initial-template, and if so, uses that as the entry point. If there is no source and no initial template, the method fails.

        Throws:
        SaxonApiException - if any dynamic error occurs during the transformation
        java.lang.IllegalStateException - if no destination has been supplied
      • getReceiver

        public Receiver getReceiver​(PipelineConfiguration pipe,
                                    SerializationProperties params)
                             throws SaxonApiException
        Return a Receiver which can be used to supply the principal source document for the transformation. This method is intended primarily for internal use, though it can also be called by a user application that wishes to feed events into the transformation engine.

        Saxon calls this method to obtain a Receiver, to which it then sends a sequence of events representing the content of an XML document. This method is provided so that XsltTransformer implements Destination, allowing one transformation to receive the results of another in a pipeline.

        Before calling this method, the setDestination(net.sf.saxon.s9api.Destination) method must be called to supply a destination for the transformation.

        Note that when an XsltTransformer is used as a Destination, the initial context node set on that XsltTransformer using setInitialContextNode(XdmNode) is ignored, as is the source set using setSource(javax.xml.transform.Source).

        Specified by:
        getReceiver in interface Destination
        Parameters:
        pipe - The Saxon configuration. This is supplied so that the destination can use information from the configuration (for example, a reference to the name pool) to construct or configure the returned Receiver.
        params - serialization parameters (not relevant here since we aren't serializing; except possibly for the item-separator property)
        Returns:
        the Receiver to which events are to be sent.
        Throws:
        SaxonApiException - if the Receiver cannot be created
        java.lang.IllegalStateException - if no Destination has been supplied
      • close

        public void close()
        Close this destination, allowing resources to be released. Used when this XsltTransformer is acting as the destination of another transformation. Saxon calls this method when it has finished writing to the destination.
        Specified by:
        close in interface Destination
      • setBaseOutputURI

        public void setBaseOutputURI​(java.lang.String uri)
        Set the base output URI.

        This defaults to the base URI of the Destination for the principal output of the transformation if a destination is supplied and its base URI is known.

        If a base output URI is supplied using this method then it takes precedence over any base URI defined in the supplied Destination object, and it may cause the base URI of the Destination object to be modified in situ.

        The base output URI is used for resolving relative URIs in the href attribute of the xsl:result-document instruction; it is accessible to XSLT stylesheet code using the XPath current-output-uri() function

        Parameters:
        uri - the base output URI
      • getBaseOutputURI

        public java.lang.String getBaseOutputURI()
        Get the base output URI.

        This returns the value set using the setBaseOutputURI(java.lang.String) method. If no value has been set explicitly, then the method returns null if called before the transformation, or the computed default base output URI if called after the transformation.

        The base output URI is used for resolving relative URIs in the href attribute of the xsl:result-document instruction.

        Returns:
        the base output URI
      • setURIResolver

        public void setURIResolver​(javax.xml.transform.URIResolver resolver)
        Set an object that will be used to resolve URIs used in fn:doc() and related functions.
        Parameters:
        resolver - An object that implements the URIResolver interface, or null.
      • getURIResolver

        public javax.xml.transform.URIResolver getURIResolver()
        Get the URI resolver.
        Returns:
        the user-supplied URI resolver if there is one, or null otherwise
      • setErrorListener

        public void setErrorListener​(javax.xml.transform.ErrorListener listener)
        Set the ErrorListener to be used during this transformation
        Parameters:
        listener - The error listener to be used. This is notified of all dynamic errors detected during the transformation.
      • getErrorListener

        public javax.xml.transform.ErrorListener getErrorListener()
        Get the ErrorListener being used during this transformation
        Returns:
        listener The error listener in use. This is notified of all dynamic errors detected during the transformation. If no user-supplied ErrorListener has been set the method will return a system-supplied ErrorListener. If an explicit ErrorListener has been set using setErrorListener(ErrorListener), then that ErrorListener will generally be returned, unless the internal ErrorListener has been changed by some other mechanism.
      • setErrorReporter

        public void setErrorReporter​(ErrorReporter reporter)
        Set a callback that will be used when reporting a dynamic error or warning
      • setResultDocumentHandler

        public void setResultDocumentHandler​(java.util.function.Function<java.net.URI,​Destination> handler)
        Set a callback function that will be used when xsl:result-document is evaluated. The argument is a function that takes a URI as input (specifically, the value of the href argument to xsl:result-document, resolved against the base output URI of the transformation), and returns a Destination, which will be used as the destination for the result document.

        If the href argument of the xsl:result-document instruction is absent or if it is set to a zero length string, then the callback function is not normally called; instead a Receiver for the secondary output is obtained by making a second call on Destination.getReceiver(PipelineConfiguration, SerializationProperties) for the principal destination of the transformation. In that situation, this result document handler is invoked only if the call on Destination.getReceiver(PipelineConfiguration, SerializationProperties) returns null.

        If the base output URI is absent (perhaps because the principal output destination for the transformation was supplied as a OutputStream or Writer with no associated URI or systemId), then the value of the href attribute is used as is if it is an absolute URI; if it is a relative URI (including the case where it is absent or zero-length) then the callback function is not called; instead a dynamic error is raised (code SaxonErrorCode.SXRD0002).

        If the callback function throws a SaxonApiUncheckedException, this will result in the xsl:result-document instruction failing with a dynamic error, which can be caught using xsl:try/xsl:catch. The error code, by default, will be "err:SXRD0001".

        The application can request to be notified when the Destination is closed by setting a Destination.onClose(Action) callback on the Destination object.

        Parameters:
        handler - the callback function to be invoked whenever an xsl:result-document instruction is evaluated.
      • setMessageListener

        public void setMessageListener​(MessageListener listener)
        Deprecated.
        Set the MessageListener to be notified whenever the stylesheet evaluates an xsl:message instruction. If no MessageListener is nominated, the output of xsl:message instructions will be serialized and sent to the standard error stream.
        Parameters:
        listener - the MessageListener to be used
      • setMessageListener

        public void setMessageListener​(MessageListener2 listener)
        Set the MessageListener to be notified whenever the stylesheet evaluates an xsl:message instruction. If no MessageListener is nominated, the output of xsl:message instructions will be serialized and sent to the standard error stream.

        The MessageListener2 interface differs from MessageListener in allowing the error code supplied to xsl:message to be notified.

        Parameters:
        listener - the MessageListener to be used
      • getMessageListener

        public MessageListener getMessageListener()
        Get the MessageListener to be notified whenever the stylesheet evaluates an xsl:message instruction. If no MessageListener has been nominated, return null
        Returns:
        the user-supplied MessageListener, or null if none has been supplied
      • getMessageListener2

        public MessageListener2 getMessageListener2()
        Get the MessageListener2 to be notified whenever the stylesheet evaluates an xsl:message instruction. If no MessageListener2 has been nominated, return null
        Returns:
        the user-supplied MessageListener2, or null if none has been supplied
      • setAssertionsEnabled

        public void setAssertionsEnabled​(boolean enabled)
        Say whether assertions (xsl:assert instructions) should be enabled at run time. By default they are disabled at compile time. If assertions are enabled at compile time, then by default they will also be enabled at run time; but they can be disabled at run time by specific request. At compile time, assertions can be enabled for some packages and disabled for others; at run-time, they can only be enabled or disabled globally.
        Parameters:
        enabled - true if assertions are to be enabled at run time; this has no effect if assertions were disabled (for a particular package) at compile time
        Since:
        9.7
      • isAssertionsEnabled

        public boolean isAssertionsEnabled()
        Ask whether assertions (xsl:assert instructions) have been enabled at run time. By default they are disabled at compile time. If assertions are enabled at compile time, then by default they will also be enabled at run time; but they can be disabled at run time by specific request. At compile time, assertions can be enabled for some packages and disabled for others; at run-time, they can only be enabled or disabled globally.
        Returns:
        true if assertions are enabled at run time
        Since:
        9.7
      • setTraceListener

        public void setTraceListener​(TraceListener listener)
        Set a TraceListener to be notified of all events occurring during the transformation. This will only be effective if the stylesheet was compiled with trace code enabled (see XsltCompiler.setCompileWithTracing(boolean))
        Parameters:
        listener - the TraceListener to be used. Note that the TraceListener has access to interal Saxon interfaces which may vary from one release to the next. It is also possible that the TraceListener interface itself may be changed in future releases.
      • getTraceListener

        public TraceListener getTraceListener()
        Get the TraceListener to be notified of all events occurring during the transformation. If no TraceListener has been nominated, return null
        Returns:
        the user-supplied TraceListener, or null if none has been supplied
      • setTraceFunctionDestination

        public void setTraceFunctionDestination​(Logger stream)
        Set the destination for output from the fn:trace() function. By default, the destination is System.err. If a TraceListener is in use, this is ignored, and the trace() output is sent to the TraceListener.
        Parameters:
        stream - the PrintStream to which trace output will be sent. If set to null, trace output is suppressed entirely. It is the caller's responsibility to close the stream after use.
      • getTraceFunctionDestination

        public Logger getTraceFunctionDestination()
        Get the destination for output from the fn:trace() function.
        Returns:
        the Logger to which trace output will be sent. If no explicitly destination has been set, returns System.err. If the destination has been set to null to suppress trace output, returns null.
      • isStreamableSource

        protected boolean isStreamableSource​(javax.xml.transform.Source source)
      • setSchemaValidationMode

        public void setSchemaValidationMode​(ValidationMode mode)
        Set the schema validation mode for the transformation. This indicates how source documents loaded specifically for this transformation will be handled. This applies to the principal source document if supplied as a SAXSource or StreamSource, and to all documents loaded during the transformation using the doc(), document(), or collection() functions.
        Parameters:
        mode - the validation mode. Passing null causes no change to the existing value. Passing ValidationMode.DEFAULT resets to the initial value, which determines the validation requirements from the Saxon Configuration.
      • getSchemaValidationMode

        public ValidationMode getSchemaValidationMode()
        Get the schema validation mode for the transformation. This indicates how source documents loaded specifically for this transformation will be handled. This applies to the principal source document if supplied as a SAXSource or StreamSource, and to all documents loaded during the transformation using the doc(), document(), or collection() functions.
        Returns:
        the validation mode.
      • setInitialMode

        public void setInitialMode​(QName modeName)
                            throws java.lang.IllegalArgumentException
        Set the initial mode for the transformation
        Parameters:
        modeName - the name of the initial mode. Two special values are recognized, in the reserved XSLT namespace: xsl:unnamed to indicate the mode with no name, and xsl:default to indicate the mode defined in the stylesheet header as the default mode. The value null also indicates the default mode (which defaults to the unnamed mode, but can be set differently in an XSLT 3.0 stylesheet).
        Throws:
        java.lang.IllegalArgumentException - if the requested mode is not defined in the stylesheet
        Since:
        changed in 9.6 to throw an exception if the mode is not defined in the stylesheet. Chaned in 9.7 so that null means the default mode, not necessarily the unnamed mode.
      • getInitialMode

        public QName getInitialMode()
        Get the name of the initial mode for the transformation, if one has been set.
        Returns:
        the initial mode for the transformation. Returns null if no mode has been set, or if the mode was set to null to represent the default (unnamed) mode
      • getUnderlyingController

        public XsltController getUnderlyingController()
        Get the underlying Controller used to implement this XsltTransformer. This provides access to lower-level methods not otherwise available in the s9api interface. Note that classes and methods obtained by this route cannot be guaranteed stable from release to release.
        Returns:
        the underlying Controller
      • getDestinationReceiver

        public Receiver getDestinationReceiver​(XsltController controller,
                                               Destination destination)
                                        throws SaxonApiException
        Get a Receiver corresponding to the chosen Destination for the transformation
        Parameters:
        destination - the destination for the results of this transformation
        Returns:
        a receiver that sends the results to this destination
        Throws:
        SaxonApiException - if anything goes wrong
      • getReceivingTransformer

        protected Receiver getReceivingTransformer​(XsltController controller,
                                                   GlobalParameterSet parameters,
                                                   Destination finalDestination)
                                            throws SaxonApiException
        Return a Receiver which can be used to supply the principal source document for the transformation. This method is intended primarily for internal use, though it can also be called by a user application that wishes to feed events into the transformation engine.

        Saxon calls this method to obtain a Receiver, to which it then sends a sequence of events representing the content of an XML document. This method is provided so that XsltTransformer implements Destination, allowing one transformation to receive the results of another in a pipeline.

        Returns:
        the Receiver to which events are to be sent.
        Throws:
        SaxonApiException - if the Receiver cannot be created
        java.lang.IllegalStateException - if no Destination has been supplied