XSLT Saxon
Since Camel 3.0
Only producer is supported
The XSLT Saxon component allows you to process a message using an XSLT template using Saxon. This can be ideal when using Templating to generate responses for requests.
URI format
xslt-saxon:templateName[?options]
The URI format contains templateName, which can be one of the following:
-
the classpath-local URI of the template to invoke
-
the complete URL of the remote template.
You can append query options to the URI in the following format:
?option=value&option=value&…
| URI | Description |
|---|---|
| Refers to the file |
| Refers to the file |
| Refers to the remote http resource |
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The XSLT Saxon component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether a message can replace the stylesheet of the endpoint with the CamelXsltResourceUri header (the URI of another stylesheet) or the CamelXsltStylesheet header (the stylesheet itself, compiled for each message). Enable it only when these headers are set by the route, not taken from incoming messages. | false | boolean | |
Whether the endpoints load and compile their stylesheet once, at startup, and reuse it for every message. When false, the stylesheet is loaded and compiled again for each message, which picks up changes during development. A cached stylesheet can be reloaded at runtime with the JMX operation clearCachedStylesheet. | true | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
A custom Saxon configuration (net.sf.saxon.Configuration) for the endpoints of this component that do not set their own. The secureProcessing option is applied to this configuration, which Saxon uses by reference, so endpoints that share the same configuration must use the same secureProcessing value. | Configuration | ||
Saxon configuration properties to set on the Saxon configuration of each endpoint, as feature names (the URIs of net.sf.saxon.lib.Feature, such as http://saxon.sf.net/feature/allow-external-functions) mapped to their values. They are applied after secureProcessing and can override it. | Map | ||
Saxon integrated extension functions (net.sf.saxon.lib.ExtensionFunctionDefinition) to register on the Saxon configuration of each endpoint, so that the stylesheets can call them. Refer to the beans in the registry by name, separated by commas. | String | ||
The fully qualified class name of the javax.xml.transform.TransformerFactory implementation to compile the stylesheets with, for the endpoints that do not set their own. | String | ||
A strategy that configures the javax.xml.transform.TransformerFactory, for example its features or attributes, before the stylesheet is compiled with it. Used by the endpoints that do not set their own. | TransformerFactoryConfigurationStrategy | ||
A custom javax.xml.transform.URIResolver for the endpoints of this component that do not set their own: it loads the stylesheet, its xsl:include and xsl:import references, and the documents of the document() function. When set, uriResolverFactory is not used. | URIResolver | ||
A custom factory (org.apache.camel.component.xslt.XsltUriResolverFactory) that creates the javax.xml.transform.URIResolver of each endpoint from the resource URI of the endpoint, for example to resolve references relative to the stylesheet. Not used when uriResolver is set. | XsltUriResolverFactory | ||
The maximum total number of XPath operators in a stylesheet, set as the jdk.xml.xpathTotalOpLimit attribute on the TransformerFactory of each endpoint that does not set its own; a stylesheet that exceeds it fails to compile. 0 or less keeps the setting of the JDK, 10000 by default. A TransformerFactory that does not support this attribute, such as the one of Saxon, ignores it. | 10000 | int | |
Whether to enable XML secure processing (javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING) on the Saxon TransformerFactory of each endpoint, and to parse an input that is still to be parsed without access to external resources. With secure processing, Saxon does not allow xsl:result-document and calls of Java methods from the stylesheet (the reflexive extension functions of Saxon-PE and Saxon-EE); the integrated extension functions of saxonExtensionFunctions remain available. With a saxonConfiguration, the feature is set on that configuration, so endpoints that share the same configuration must use the same secureProcessing value. | true | boolean |
Endpoint Options
The XSLT Saxon endpoint is configured using URI syntax:
xslt-saxon:resourceUri
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The stylesheet to transform with. Camel’s default URI resolver loads it from the classpath when it has no scheme, and also supports file:, http:, https:, ref: (a resource in the registry) and bean: (the result of a bean method, such as bean:myBean.myMethod). The xsl:include and xsl:import references of the stylesheet are resolved relative to it. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Whether the transformer may read the input as a javax.xml.transform.stax.StAXSource. The endpoint converts the message body to a StAXSource when it can; when false, such a StAXSource is turned into a javax.xml.transform.sax.SAXSource before the transformation, for a TransformerFactory that does not support StAXSource. | true | boolean | |
Whether a message can replace the stylesheet of the endpoint with the CamelXsltResourceUri header (the URI of another stylesheet) or the CamelXsltStylesheet header (the stylesheet itself, compiled for each message). Enable it only when these headers are set by the route, not taken from incoming messages. | false | boolean | |
Whether to load and compile the stylesheet once, at startup, and reuse it for every message. When false, the stylesheet is loaded and compiled again for each message, which picks up changes during development. A cached stylesheet can be reloaded at runtime with the JMX operation clearCachedStylesheet. | true | boolean | |
Whether to delete the file named in the CamelXsltFileName header when the exchange is done, whether it completed or failed. Use it with output=file when the result file is only needed during routing. | false | boolean | |
Whether to fail when the input is null or cannot be converted to a javax.xml.transform.Source. When false, an empty XML document is transformed instead. | true | boolean | |
The type of the message body that holds the result: string (java.lang.String), bytes (byte[]), DOM (org.w3c.dom.Document) or file. With file, the transformer writes the result to the file named in the CamelXsltFileName header and the body becomes that java.io.File. The JDK XSLT processor fails when the parent directory of the file does not exist; Saxon creates it. Enum values:
| string | XsltOutput | |
Where to read the input from instead of the message body: header:name for a header, exchangeProperty:name (or property:name) for an exchange property, or variable:name for a variable. A name without a prefix is a variable. When empty, the message body is used. | String | ||
The number of javax.xml.transform.Transformer instances to keep for reuse, so that a message does not need a new Transformer from the compiled stylesheet (Templates.newTransformer()). 0 creates a new Transformer for each message. | 0 | int | |
Whether the message body is JSON. When enabled, the body is converted to the XML representation of JSON of the XPath 3.1 function json-to-xml() (map, array, string, number, boolean and null elements in the namespace http://www.w3.org/2005/xpath-functions), which the stylesheet then transforms. A body that cannot be converted is read as XML. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
A custom org.xml.sax.EntityResolver that resolves the external entities of the input document. It is set on the XMLReader of the input only when the input reaches the transformer as a javax.xml.transform.sax.SAXSource. | EntityResolver | ||
A custom javax.xml.transform.ErrorListener for the warnings and errors of the stylesheet compilation and of the transformation. It replaces the default listener, which logs the compilation errors and, during the transformation, stores the warnings and errors on the exchange as the properties CamelXsltWarning, CamelXsltError and CamelXsltFatalError and fails the exchange on an error. | ErrorListener | ||
A custom org.apache.camel.component.xslt.ResultHandlerFactory that creates, for each message, the javax.xml.transform.Result the transformer writes to and sets the message body from it. Used instead of the output option. | ResultHandlerFactory | ||
A custom Saxon configuration (net.sf.saxon.Configuration) for the Saxon TransformerFactory that the endpoint creates. The secureProcessing option is applied to this configuration, which Saxon uses by reference, so endpoints that share the same configuration must use the same secureProcessing value. | Configuration | ||
Saxon integrated extension functions (net.sf.saxon.lib.ExtensionFunctionDefinition) to register on the Saxon configuration, so that the stylesheet can call them. Refer to the beans in the registry by name, separated by commas. | String | ||
A custom javax.xml.transform.TransformerFactory to compile the stylesheet with. When set, transformerFactoryClass is not used. | TransformerFactory | ||
The fully qualified class name of the javax.xml.transform.TransformerFactory implementation to compile the stylesheet with. Not used when transformerFactory is set. The endpoint option takes precedence over the component option. | String | ||
A strategy that configures the javax.xml.transform.TransformerFactory, for example its features or attributes, before the stylesheet is compiled with it. The endpoint option takes precedence over the component option. | TransformerFactoryConfigurationStrategy | ||
A custom javax.xml.transform.URIResolver to load the stylesheet (resourceUri), its xsl:include and xsl:import references, and the documents of the document() function. Camel’s default resolver loads them as Camel resources (classpath:, file:, http:, ref: or bean:), relative to the stylesheet. | URIResolver | ||
The maximum total number of XPath operators in the stylesheet, set as the jdk.xml.xpathTotalOpLimit attribute on the TransformerFactory of the endpoint; a stylesheet that exceeds it fails to compile. 0 or less keeps the setting of the JDK, 10000 by default. The endpoint option takes precedence over the component option. A TransformerFactory that does not support this attribute, such as the one of Saxon, ignores it. | 10000 | int | |
A consumer (org.apache.camel.component.xslt.XsltMessageLogger) for the text that the xsl:message instructions of the stylesheet output during the transformation. Only the xslt-saxon component passes this text to it; the xslt component does not use it. | XsltMessageLogger | ||
Whether to enable XML secure processing (javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING) on the Saxon TransformerFactory, and to parse an input that is still to be parsed without access to external resources. With secure processing, Saxon does not allow xsl:result-document and calls of Java methods from the stylesheet (the reflexive extension functions of Saxon-PE and Saxon-EE); the integrated extension functions of saxonExtensionFunctions remain available. With a saxonConfiguration, the feature is set on that configuration, so endpoints that share the same configuration must use the same secureProcessing value. | true | boolean |
Message Headers
The XSLT Saxon component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelXsltResourceUri (producer) Constant: | The URI of a stylesheet to use for this message instead of the one of the endpoint, in the same format as the resourceUri option. Used only when allowTemplateFromHeader is enabled. It takes precedence over CamelXsltStylesheet, and it is removed from the message. | String | |
CamelXsltStylesheet (producer) Constant: | The stylesheet (the XSLT text) to use for this message instead of the one of the endpoint. It is compiled for each message. Used only when allowTemplateFromHeader is enabled. | String | |
| Constant: | The name of the file to write the result to when the output option is file. It is also the file that the deleteOutputFile option deletes. | String |
Message Body
The message body at each side of the XSLT Saxon component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| The XML to transform: text, bytes, a stream, a file, a DOM or another javax.xml.transform.Source; JSON text with useJsonBody. A Map, a List or no body fails.
Not known when |
Producer output |
| The result of the transformation.
Not known when |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Using XSLT endpoints
The following format is an example of using an XSLT template to formulate a response for a message for InOut message exchanges (where there is a JMSReplyTo header)
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("xslt-saxon:com/acme/mytransform.xsl"); <route>
<from uri="activemq:My.Queue"/>
<to uri="xslt-saxon:com/acme/mytransform.xsl"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: xslt-saxon:com/acme/mytransform.xsl If you want to use InOnly and consume the message and send it to another destination, you could use the following route:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("xslt-saxon:com/acme/mytransform.xsl")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="xslt-saxon:com/acme/mytransform.xsl"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: xslt-saxon:com/acme/mytransform.xsl
- to:
uri: activemq:Another.Queue Getting Usable Parameters into the XSLT
By default, all headers and variables are added as parameters which are then available in the XSLT.
To make the parameters usable, you will need to declare them.
-
Header
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("myParam", constant("42"))
.to("xslt-saxon:MyTransform.xsl"); <route>
<from uri="direct:start"/>
<setHeader name="myParam"><constant>42</constant></setHeader>
<to uri="xslt-saxon:MyTransform.xsl"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: myParam
constant: "42"
- to:
uri: xslt-saxon:MyTransform.xsl -
Variable
-
Java
-
XML
-
YAML
from("direct:start")
.setVariable("myParam", constant("42"))
.to("xslt-saxon:MyTransform.xsl"); <route>
<from uri="direct:start"/>
<setVariable name="myParam"><constant>42</constant></setVariable>
<to uri="xslt-saxon:MyTransform.xsl"/>
</route> - route:
from:
uri: direct:start
steps:
- setVariable:
name: myParam
constant: "42"
- to:
uri: xslt-saxon:MyTransform.xsl The parameter also needs to be declared in the top level of the XSLT for it to be available:
<xsl: ...... >
<xsl:param name="myParam"/>
<xsl:template ...> | The |
Spring XML versions
To use the above examples in Spring XML, you would use something like the following code:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("xslt-saxon:org/apache/camel/spring/processor/example.xsl")
.to("activemq:Another.Queue"); <camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="activemq:My.Queue"/>
<to uri="xslt-saxon:org/apache/camel/spring/processor/example.xsl"/>
<to uri="activemq:Another.Queue"/>
</route>
</camelContext> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: xslt-saxon:org/apache/camel/spring/processor/example.xsl
- to:
uri: activemq:Another.Queue Using xsl:include
Camel provides its own implementation of URIResolver. This allows Camel to load included files from the classpath.
For example, the included file in the following code will be located relative to the starting endpoint.
<xsl:include href="staff_template.xsl"/> This means that Camel will locate the file in the classpath as org/apache/camel/component/xslt/staff_template.xsl
You can use classpath: or file: to instruct Camel to look either in the classpath or file system. If you omit the prefix, then Camel uses the prefix from the endpoint configuration. If no prefix is specified in the endpoint configuration, the default is classpath:.
You can also refer backwards in the included paths. In the following example, the XSL file will be resolved under org/apache/camel/component.
<xsl:include href="../staff_other_template.xsl"/> Using xsl:include and default prefix
Camel will use the prefix from the endpoint configuration as the default prefix.
You can explicitly specify file: or classpath: loading. The two loading types can be mixed in an XSLT script, if necessary.
Using Saxon extension functions
Since Saxon 9.2, writing extension functions has been supplemented by a new mechanism, referred to as extension functions you can now easily use camel as shown in the below example:
SimpleRegistry registry = new SimpleRegistry();
registry.put("function1", new MyExtensionFunction1());
registry.put("function2", new MyExtensionFunction2());
from("direct:start")
.to("xslt-saxon:org/apache/camel/component/xslt/extensions/extensions.xslt?saxonExtensionFunctions=#function1,#function2"); With Spring XML:
<bean id="function1" class="org.apache.camel.component.xslt.extensions.MyExtensionFunction1"/>
<bean id="function2" class="org.apache.camel.component.xslt.extensions.MyExtensionFunction2"/>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:extensions"/>
<to uri="xslt-saxon:org/apache/camel/component/xslt/extensions/extensions.xslt?saxonExtensionFunctions=#function1,#function2"/>
</route>
</camelContext> Dynamic stylesheets
To provide a dynamic stylesheet at runtime, you can either:
-
Define a dynamic URI. See toD EIP.
-
Use header with the stylesheet.
When using a header for dynamic stylesheet, then you can either refer to the stylesheet as a file or classpath with the header CamelXsltResourceUri, such as:
-
Java
-
XML
-
YAML
from("direct:transform")
.setHeader("CamelXsltResourceUri", simple("file:styles/${header.region}.xsl"))
.to("xslt-saxon:template.xsl?allowTemplateFromHeader=true"); <route>
<from uri="direct:transform"/>
<setHeader name="CamelXsltResourceUri">
<simple>file:styles/${header.region}.xsl</simple>
</setHeader>
<to uri="xslt-saxon:template.xsl?allowTemplateFromHeader=true"/>
</route> - route:
from:
uri: direct:transform
steps:
- setHeader:
name: CamelXsltResourceUri
simple: "file:styles/${header.region}.xsl"
- to:
uri: xslt-saxon:template.xsl
parameters:
allowTemplateFromHeader: true Here we set the CamelXsltResourceUri header to refer to a stylesheet to be loaded from the file system, with a dynamic name that is computed from another header (region).
Notice how the allowTemplateFromHeader must be set to true on the XSLT endpoint to support dynamic templates.
You can also use the header CamelXsltStylesheet which instead should contain the content of the stylesheet to use, instead of referring to a file as the example from above.
You can set contentCache=false and refer to a non-existing template, such as "xslt-saxon:dummy.xsl?contentCache=false&allowTemplateFromHeader=true" as this will tell Camel to not load dummy.xsl on startup but to load the stylesheet on demand. And because you provide the stylesheet via headers, then it is fully dynamic. |
Accessing warnings, errors and fatalErrors from XSLT ErrorListener
Any warning/error or fatalError is stored on the current Exchange as a property with the keys Exchange.XSLT_ERROR, Exchange.XSLT_FATAL_ERROR, or Exchange.XSLT_WARNING which allows end users to get hold of any errors happening during transformation.
For example, in the stylesheet below, we want to determinate whether a staff has an empty dob field. And to include a custom error message using xsl:message.
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="staff/programmer">
<p>Name: <xsl:value-of select="name"/><br />
<xsl:if test="dob=''">
<xsl:message terminate="yes">Error: DOB is an empty string!</xsl:message>
</xsl:if>
</p>
</xsl:for-each>
</body>
</html>
</xsl:template> The exception is stored on the Exchange as a warning with the key Exchange.XSLT_WARNING.
Consume JSON body
By default, the input body is assumed as XML. You can set useJsonBody=true to consume JSON data from Camel Message body.
-
Java
-
XML
-
YAML
from("direct:transform")
.to("xslt-saxon:template.xsl?useJsonBody=true"); <route>
<from uri="direct:transform"/>
<to uri="xslt-saxon:template.xsl?useJsonBody=true"/>
</route> - route:
from:
uri: direct:transform
steps:
- to:
uri: xslt-saxon:template.xsl
parameters:
useJsonBody: true If useJsonBody=true is set, the JSON body is transformed into XML representation of JSON defined in XSLT 3.0 specification.
For example, when we have following JSON data
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"zipcode": "10001"
},
"hobbies": ["reading", "cycling", "swimming"]
} XSLT 3.0 XML representation of JSON is
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="name">John Doe</string>
<number key="age">30</number>
<string key="email">john.doe@example.com</string>
<map key="address">
<string key="street">123 Main St</string>
<string key="city">New York</string>
<string key="zipcode">10001</string>
</map>
<array key="hobbies">
<string>reading</string>
<string>cycling</string>
<string>swimming</string>
</array>
</map>