Camel Components

XSLT

Since Camel 1.3

Only producer is supported

The XSLT component allows you to process a message using an XSLT template. This can be ideal when using Templating to generate response for requests.

URI format

xslt: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&…​

Table 1. Example URIs
URI Description

xslt:com/acme/mytransform.xsl

Refers to the file com/acme/mytransform.xsl on the classpath

xslt:file:///foo/bar.xsl

Refers to the file /foo/bar.xsl

xslt:http://acme.com/cheese/foo.xsl

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, *.yaml files, 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 component supports the following options which are listed below.

Name Description Default Type

allowTemplateFromHeader (producer)

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

contentCache (producer)

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

lazyStartProducer (producer)

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

autowiredEnabled (advanced)

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

transformerFactoryClass (advanced)

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

transformerFactoryConfigurationStrategy (advanced)

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

uriResolver (advanced)

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

uriResolverFactory (advanced)

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

xpathTotalOpLimit (advanced)

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

Endpoint Options

The XSLT endpoint is configured using URI syntax:

xslt:resourceUri

With the following path and query parameters:

Path Parameters

Name Description Default Type

resourceUri (producer)

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

allowTemplateFromHeader (producer)

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

contentCache (producer)

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

deleteOutputFile (producer)

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

failOnNullBody (producer)

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

output (producer)

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

  • bytes

  • DOM

  • file

string

XsltOutput

source (producer)

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

transformerCacheSize (producer)

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

lazyStartProducer (producer (advanced))

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

entityResolver (advanced)

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

errorListener (advanced)

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

resultHandlerFactory (advanced)

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

transformerFactory (advanced)

A custom javax.xml.transform.TransformerFactory to compile the stylesheet with. When set, transformerFactoryClass is not used.

TransformerFactory

transformerFactoryClass (advanced)

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

transformerFactoryConfigurationStrategy (advanced)

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

uriResolver (advanced)

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

xpathTotalOpLimit (advanced)

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

xsltMessageLogger (advanced)

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

Message Headers

The XSLT component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelXsltResourceUri (producer)

Constant: XSLT_RESOURCE_URI

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: XSLT_STYLESHEET

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

CamelXsltFileName (producer)

Constant: XSLT_FILE_NAME

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 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

text, bytes, stream, file or pojo, as xml

The XML to transform: text, bytes, a stream, a file, a DOM or another javax.xml.transform.Source. A Map, a List or no body fails.

  • With failOnNullBody=false: null, text, bytes, stream, file or pojo

Not known when source is set.

Producer output

text (java.lang.String)

The result of the transformation.

  • With output=bytes: bytes (byte[])

  • With output=DOM: pojo (org.w3c.dom.Document)

  • With output=file: file (java.io.File)

Not known when resultHandlerFactory is set.

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.

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:com/acme/mytransform.xsl");
<route>
  <from uri="activemq:My.Queue"/>
  <to uri="xslt:com/acme/mytransform.xsl"/>
</route>
- route:
    from:
      uri: activemq:My.Queue
      steps:
        - to:
            uri: xslt: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:com/acme/mytransform.xsl")
    .to("activemq:Another.Queue");
<route>
  <from uri="activemq:My.Queue"/>
  <to uri="xslt:com/acme/mytransform.xsl"/>
  <to uri="activemq:Another.Queue"/>
</route>
- route:
    from:
      uri: activemq:My.Queue
      steps:
        - to:
            uri: xslt: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:MyTransform.xsl");
<route>
  <from uri="direct:start"/>
  <setHeader name="myParam"><constant>42</constant></setHeader>
  <to uri="xslt:MyTransform.xsl"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - setHeader:
            name: myParam
            constant: "42"
        - to:
            uri: xslt:MyTransform.xsl
  • Variable

  • Java

  • XML

  • YAML

from("direct:start")
    .setVariable("myParam", constant("42"))
    .to("xslt:MyTransform.xsl");
<route>
  <from uri="direct:start"/>
  <setVariable name="myParam"><constant>42</constant></setVariable>
  <to uri="xslt:MyTransform.xsl"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - setVariable:
            name: myParam
            constant: "42"
        - to:
            uri: xslt: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 automatic binding adds every message header as a stylesheet parameter, including headers that arrived from outside the route (for example HTTP query parameters, or headers set by an upstream sender). A stylesheet that passes a parameter into the XPath document() function therefore lets an external sender influence which resource the transform reads.

When the xslt endpoint is reachable from an untrusted source and the stylesheet is not meant to take parameters from the wire, strip the incoming headers before the xslt step, keeping only the parameters the stylesheet expects:

from("jetty:http://0.0.0.0:8080/transform")
    // keep only the parameters the stylesheet declares; drop everything that arrived on the wire
    .removeHeaders("*", "myParam")
    .to("xslt:MyTransform.xsl");

Separately, Camel’s default XSLT transformer factory already denies external resource access — it sets ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET to the empty (deny-all) value. Since Camel 4.23 the always-installed resolver honours that setting, so when document() resolves an external http:, https:, ftp: or file: URI at transform time the reference is refused by default: the transform fails with a document-retrieval error (and the reason is logged as a warning) instead of reading the resource. This includes a relative document() when the stylesheet itself was loaded from file: (it resolves to a file: URI beside the stylesheet); stylesheets loaded from classpath: are unaffected, since a relative document() there resolves to a classpath: URI. To permit specific external protocols, supply your own TransformerFactory (through the transformerFactory option) whose ACCESS_EXTERNAL_STYLESHEET allows them — set the attribute to a comma-separated protocol list (such as file or http,https) or to all. Camel’s internal classpath:, ref: and bean: schemes are resource lookups outside the JAXP external-access model and remain available. A stylesheet’s xsl:include / xsl:import references are resolved when the stylesheet is compiled (they are part of the route definition) and are not affected by this runtime check.

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: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:org/apache/camel/spring/processor/example.xsl"/>
    <to uri="activemq:Another.Queue"/>
  </route>
</camelContext>
- route:
    from:
      uri: activemq:My.Queue
      steps:
        - to:
            uri: xslt: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.

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:template.xsl?allowTemplateFromHeader=true");
<route>
  <from uri="direct:transform"/>
  <setHeader name="CamelXsltResourceUri">
    <simple>file:styles/${header.region}.xsl</simple>
  </setHeader>
  <to uri="xslt:template.xsl?allowTemplateFromHeader=true"/>
</route>
- route:
    from:
      uri: direct:transform
      steps:
        - setHeader:
            name: CamelXsltResourceUri
            simple: "file:styles/${header.region}.xsl"
        - to:
            uri: xslt: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: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.

Live reload in dev mode

When routes-reload is enabled (camel.main.routesReloadEnabled=true, automatically set by camel run --dev), Camel disables contentCache on the XSLT component so that edits to the stylesheet file are picked up on the next message without having to restart the route. User properties (e.g. camel.component.xslt.contentCache=true) and explicit endpoint/URI settings are always respected: set contentCache=true to keep caching even in dev mode.

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 terminate if 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.