XJ
Since Camel 3.0
Only producer is supported
The XJ component allows you to convert XML and JSON documents directly forth and back without the need of intermediate java objects. You can even specify an XSLT stylesheet to convert directly to the target JSON / XML (domain) model.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-xj</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
xj:templateName?transformDirection=XML2JSON|JSON2XML[&options]
| More documentation The XJ component extends the XSLT component, and therefore it supports all options provided by the XSLT component as well. At least look at the XSLT component documentation how to configure the xsl template. |
The transformDirection option is mandatory and must be either XML2JSON or JSON2XML.
The templateName parameter allows using identify transforma by specifying the name identity.
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 XJ 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 XJ endpoint is configured using URI syntax:
xj: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 | ||
Required The direction of the transformation. JSON2XML parses the JSON body into XML elements named object, with the JSON key in the xj:name attribute and the JSON type in the xj:type attribute, and returns the XML that the stylesheet writes. XML2JSON reads an XML body and writes the output of the stylesheet as JSON, using the xj:name and xj:type attributes as hints; output=DOM is not supported in this direction. Enum values:
| TransformDirection | ||
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 XJ component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The path of the file that the producer writes the result to when output=file. It is required with output=file, and the message body becomes this java.io.File. The deleteOutputFile option reads it too, to delete the file when the exchange is done. | String | |
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 |
Message Body
The message body at each side of the XJ 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 for XML2JSON as text, bytes, a stream, a file, a DOM or another javax.xml.transform.Source; the JSON for JSON2XML as text, bytes, a stream or a file. A Map, a List or no body fails, unless failOnNullBody=false for no body.
Not known when |
Producer output |
| The result of the transformation: JSON text with XML2JSON, XML text with JSON2XML. output=DOM works with JSON2XML only.
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
Converting JSON to XML
The following route does an "identity" transform of the message because no xslt stylesheet is given. In the context of XML to XML transformations, "Identity" transform means that the output document is just a copy of the input document. In the case of XJ, it means it transforms the JSON document to an equivalent XML representation.
-
Java
-
XML
-
YAML
from("direct:start")
.to("xj:identity?transformDirection=JSON2XML"); <route>
<from uri="direct:start"/>
<to uri="xj:identity?transformDirection=JSON2XML"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: xj:identity
parameters:
transformDirection: JSON2XML Sample:
The input:
{
"firstname": "camel",
"lastname": "apache",
"personalnumber": 42,
"active": true,
"ranking": 3.1415926,
"roles": [
"a",
{
"x": null
}
],
"state": {
"needsWater": true
}
} Will output:
<?xml version="1.0" encoding="UTF-8"?>
<object xmlns:xj="http://camel.apache.org/component/xj" xj:type="object">
<object xj:name="firstname" xj:type="string">camel</object>
<object xj:name="lastname" xj:type="string">apache</object>
<object xj:name="personalnumber" xj:type="int">42</object>
<object xj:name="active" xj:type="boolean">true</object>
<object xj:name="ranking" xj:type="float">3.1415926</object>
<object xj:name="roles" xj:type="array">
<object xj:type="string">a</object>
<object xj:type="object">
<object xj:name="x" xj:type="null">null</object>
</object>
</object>
<object xj:name="state" xj:type="object">
<object xj:name="needsWater" xj:type="boolean">true</object>
</object>
</object> As can be seen in the output above, XJ writes some metadata in the resulting xml that can be used in further processing:
-
XJ metadata nodes are always in the
http://camel.apache.org/component/xjnamespace. -
JSON key names are placed in the xj:name attribute.
-
The parsed JSON type can be found in the xj:type attribute. The above example already contains all possible types.
-
Generated XML elements are always named "object".
Now we can apply a stylesheet, e.g.:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xj="http://camel.apache.org/component/xj"
exclude-result-prefixes="xj">
<xsl:output omit-xml-declaration="no" encoding="UTF-8" method="xml" indent="yes"/>
<xsl:template match="/">
<person>
<xsl:apply-templates select="//object"/>
</person>
</xsl:template>
<xsl:template match="object[@xj:type != 'object' and @xj:type != 'array' and string-length(@xj:name) > 0]">
<xsl:variable name="name" select="@xj:name"/>
<xsl:element name="{$name}">
<xsl:value-of select="text()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*|node()"/>
</xsl:stylesheet> To the above sample by specifying the template on the endpoint:
-
Java
-
XML
-
YAML
from("direct:start")
.to("xj:com/example/json2xml.xsl?transformDirection=JSON2XML"); <route>
<from uri="direct:start"/>
<to uri="xj:com/example/json2xml.xsl?transformDirection=JSON2XML"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: xj:com/example/json2xml.xsl
parameters:
transformDirection: JSON2XML And get the following output:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<firstname>camel</firstname>
<lastname>apache</lastname>
<personalnumber>42</personalnumber>
<active>true</active>
<ranking>3.1415926</ranking>
<x>null</x>
<needsWater>true</needsWater>
</person> Converting XML to JSON
Based on the explanations above, an identity transform will be performed when no stylesheet is given:
-
Java
-
XML
-
YAML
from("direct:start")
.to("xj:identity?transformDirection=XML2JSON"); <route>
<from uri="direct:start"/>
<to uri="xj:identity?transformDirection=XML2JSON"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: xj:identity
parameters:
transformDirection: XML2JSON Given the sample input
<?xml version="1.0" encoding="UTF-8"?>
<person>
<firstname>camel</firstname>
<lastname>apache</lastname>
<personalnumber>42</personalnumber>
<active>true</active>
<ranking>3.1415926</ranking>
<roles>
<entry>a</entry>
<entry>
<x>null</x>
</entry>
</roles>
<state>
<needsWater>true</needsWater>
</state>
</person> will result in
{
"firstname": "camel",
"lastname": "apache",
"personalnumber": "42",
"active": "true",
"ranking": "3.1415926",
"roles": [
"a",
{
"x": "null"
}
],
"state": {
"needsWater": "true"
}
} You may have noted that the input XML and output JSON are very similar to the examples above when converting from json to xml, although nothing special is done here. We only transformed an arbitrary XML document to JSON. XJ uses the following rules by default:
-
The XML root element can be named somehow, it will always end in a JSON root object declaration
{} -
The JSON key name is the name of the XML element
-
If there is a name clash as in
<roles>above where two<entry>elements exist a json array will be generated. -
XML elements with text-only-child-nodes will result in the usual key/string-value pair. Mixed content elements result in a key/child-object pair as seen in
<state>above.
Now we can apply again a stylesheet, e.g.:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xj="http://camel.apache.org/component/xj"
exclude-result-prefixes="xj">
<xsl:output omit-xml-declaration="no" encoding="UTF-8" method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="personalnumber">
<xsl:element name="{local-name()}">
<xsl:attribute name="xj:type">
<xsl:value-of select="'int'"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="active|needsWater">
<xsl:element name="{local-name()}">
<xsl:attribute name="xj:type">
<xsl:value-of select="'boolean'"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="ranking">
<xsl:element name="{local-name()}">
<xsl:attribute name="xj:type">
<xsl:value-of select="'float'"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="roles">
<xsl:element name="{local-name()}">
<xsl:attribute name="xj:type">
<xsl:value-of select="'array'"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="*[normalize-space(text()) = 'null']">
<xsl:element name="{local-name()}">
<xsl:attribute name="xj:type">
<xsl:value-of select="'null'"/>
</xsl:attribute>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet> to the sample above by specifying the template on the endpoint:
-
Java
-
XML
-
YAML
from("direct:start")
.to("xj:com/example/xml2json.xsl?transformDirection=XML2JSON"); <route>
<from uri="direct:start"/>
<to uri="xj:com/example/xml2json.xsl?transformDirection=XML2JSON"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: xj:com/example/xml2json.xsl
parameters:
transformDirection: XML2JSON and get the following output:
{
"firstname": "camel",
"lastname": "apache",
"personalnumber": 42,
"active": true,
"ranking": 3.1415926,
"roles": [
"a",
{
"x": null
}
],
"state": {
"needsWater": true
}
} Note, this transformation resulted in exactly the same JSON document as we used as input to the json2xml conversion. What did the stylesheet do? We just gave some hints to XJ on how to write the JSON document. The following XML document is that what is passed to XJ after XSL transformation:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<firstname>camel</firstname>
<lastname>apache</lastname>
<personalnumber xmlns:xj="http://camel.apache.org/component/xj" xj:type="int">42</personalnumber>
<active xmlns:xj="http://camel.apache.org/component/xj" xj:type="boolean">true</active>
<ranking xmlns:xj="http://camel.apache.org/component/xj" xj:type="float">3.1415926</ranking>
<roles xmlns:xj="http://camel.apache.org/component/xj" xj:type="array">
<entry>a</entry>
<entry>
<x xj:type="null">null</x>
</entry>
</roles>
<state>
<needsWater xmlns:xj="http://camel.apache.org/component/xj" xj:type="boolean">true</needsWater>
</state>
</person> In the stylesheet we just provided the minimal required type hints to get the same result. The supported type hints are exactly the same as XJ writes to an XML document when converting from json to xml.
In the end, that means that we can feed back in the result document from the JSON to XML transformation sample above:
<?xml version="1.0" encoding="UTF-8"?>
<object xmlns:xj="http://camel.apache.org/component/xj" xj:type="object">
<object xj:name="firstname" xj:type="string">camel</object>
<object xj:name="lastname" xj:type="string">apache</object>
<object xj:name="personalnumber" xj:type="int">42</object>
<object xj:name="active" xj:type="boolean">true</object>
<object xj:name="ranking" xj:type="float">3.1415926</object>
<object xj:name="roles" xj:type="array">
<object xj:type="string">a</object>
<object xj:type="object">
<object xj:name="x" xj:type="null">null</object>
</object>
</object>
<object xj:name="state" xj:type="object">
<object xj:name="needsWater" xj:type="boolean">true</object>
</object>
</object> and get the same output again:
{
"firstname": "camel",
"lastname": "apache",
"personalnumber": 42,
"active": true,
"ranking": 3.1415926,
"roles": [
"a",
{
"x": null
}
],
"state": {
"needsWater": true
}
} As seen in the example above:
-
xj:type lets you specify exactly the desired output type
-
xj:name lets you overrule the JSON key name.
This is required when you want to generate key names that contain chars that aren’t allowed in XML element names.
Available type hints
| @xj:type= | Description |
|---|---|
| Generate a JSON object |
| Generate a JSON array |
| Generate a JSON string |
| Generate a JSON number without fractional part |
| Generate a JSON number with fractional part |
| Generate a JSON boolean |
| Generate an empty value using the word null |