Velocity
Since Camel 1.2
Only producer is supported
The Velocity component allows you to process a message using an Apache Velocity template. This can be ideal when using Templating to generate responses for requests.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-velocity</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
velocity:templateName[?options]
Where templateName is the classpath-local URI of the template to invoke; or the complete URL of the remote template (e.g.: file://folder/myfile.vm).
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 Velocity component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Sets whether the context map should allow access to all details. By default only the message body and headers can be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose a potential security risk as this opens access to the full power of CamelContext API. | false | boolean | |
Whether the producer reads the CamelVelocityResourceUri, CamelVelocityTemplate, CamelVelocityContext and CamelVelocitySupplementalContext headers. If false, the producer ignores all four headers. Enable it only when the route sets these headers, not a message sender. | false | boolean | |
Sets whether to use resource content cache or not. | 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 | |
Autowired To use a custom org.apache.velocity.app.VelocityEngine for all endpoints of the component. If not set, each endpoint creates its own engine, which loads the templates that a template includes with #parse or #include from the file system and the classpath, and applies the loaderCache and propertiesFile options. | VelocityEngine |
Endpoint Options
The Velocity endpoint is configured using URI syntax:
velocity:resourceUri
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required Path to the resource. You can prefix with: classpath, file, http, ref, or bean. classpath, file and http loads the resource using these protocols (classpath is default). ref will lookup the resource in the registry. bean will call a method on a bean to be used as the resource. For bean you can specify the method name after dot, eg bean:myBean.myMethod. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Sets whether the context map should allow access to all details. By default only the message body and headers can be accessed. This option can be enabled for full access to the current Exchange and CamelContext. Doing so impose a potential security risk as this opens access to the full power of CamelContext API. | false | boolean | |
Whether the producer reads the CamelVelocityResourceUri, CamelVelocityTemplate, CamelVelocityContext and CamelVelocitySupplementalContext headers. If false, the producer ignores all four headers. Enable it only when the route sets these headers, not a message sender. | false | boolean | |
Sets whether to use resource content cache or not. | true | boolean | |
The name of the character encoding (charset) that the producer uses to read the template of resourceUri, for example UTF-8. If not set, the default charset of the JVM is used. Not used for the template of the CamelVelocityTemplate header, which is already text, nor for the templates that #parse or #include loads. | String | ||
Whether the file resource loader of the VelocityEngine caches the templates that a template includes with #parse or #include. It does not apply to the template of resourceUri, which the producer reads itself and contentCache caches. Not used when the velocityEngine option of the component is set, and the propertiesFile can override it. | true | boolean | |
The URI of a Java properties file with the configuration of the VelocityEngine that the endpoint creates, for example file:velocity.properties, or a path on the classpath when the URI has no scheme. Its properties replace the defaults that Camel sets, such as the resource loaders and loaderCache. Not used when the velocityEngine option of the component is set. | String | ||
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 |
Message Headers
The Velocity component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelVelocityResourceUri (producer) Constant: | The URI of a template that the producer renders in place of the template of resourceUri, in the same form as resourceUri. Only used when allowTemplateFromHeader is true. The producer removes the header and hands the exchange to the velocity endpoint of that URI, with the same options as this endpoint, which renders the text of a CamelVelocityTemplate header instead if one is set. | String | |
CamelVelocityTemplate (producer) Constant: | The text of a template that the producer renders in place of the template of resourceUri. Only used when allowTemplateFromHeader is true. The producer removes the header after reading it. | String | |
CamelVelocityContext (producer) Constant: | The org.apache.velocity.context.Context that the template reads its data from, in place of the context that the producer builds from the exchange with the body, the headers and the other entries. Only used when allowTemplateFromHeader is true. The CamelVelocitySupplementalContext header is then ignored. | Context | |
CamelVelocitySupplementalContext (producer) Constant: | A Map of entries that the producer adds to the context that it builds from the exchange, where an entry replaces the one with the same key, such as body or headers. Only used when allowTemplateFromHeader is true, and not when the CamelVelocityContext header is set. | Map |
Message Body
The message body at each side of the Velocity 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 template gets the body as body, as it is: text, or a Map, a List or a POJO to read from; convert bytes or a stream to a String first. The template is the resource, or the CamelVelocityTemplate or CamelVelocityResourceUri header with allowTemplateFromHeader=true, and never the body. |
Producer output |
| The text the template writes, also when it is JSON or XML: unmarshal it to read its fields. The headers are kept. |
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.
Headers set during the Velocity evaluation are kept on the message, so a template can return values to the route as headers.
For example, to set the header fruit in the Velocity template:
$headers.put("fruit", "Apple") The fruit header is now set on the message after the velocity endpoint. With allowContextMapAll=true, the template can also use $in.setHeader("fruit", "Apple"), as the in entry is only in the Velocity context with that option.
Usage
Velocity Context
Camel will provide exchange information in the Velocity context (just a Map). The Exchange is transferred as: The body, header, headers, variable, variables and exception entries are always there; the others only when the endpoint has allowContextMapAll=true.
| key | value |
|---|---|
| The |
| The |
| The variables |
| The headers of the In message. |
| The Camel Context instance. |
| The In message. |
| The In message. |
| The In message body. |
| The Out message (only for InOut message exchange pattern). |
| The Out message (only for InOut message exchange pattern). |
You can set up a custom Velocity Context yourself by setting property allowTemplateFromHeader=true and setting the message header CamelVelocityContext just like this
VelocityContext velocityContext = new VelocityContext(variableMap);
exchange.getIn().setHeader("CamelVelocityContext", velocityContext); Using Velocity Tools such as EscapeTool
Anything you store in an exchange variable is available to the template via $variables. This makes it easy to hand Velocity Tools such as EscapeTool to the template, so special characters can be escaped for HTML, XML, JSON, SQL, or URLs directly in the template, instead of pre-processing the message before calling the template.
First, add the Velocity Tools dependency to your project (Camel does not ship it):
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>x.x.x</version>
</dependency> Then register an EscapeTool as a bean, pass it to the template in an exchange variable, and call it from the template:
-
Java
-
XML
-
YAML
from("direct:order")
.setVariable("esc", constant(new EscapeTool()))
.to("velocity:com/acme/order.vm"); <bean id="esc" class="org.apache.velocity.tools.generic.EscapeTool"/>
<route>
<from uri="direct:order"/>
<setVariable name="esc">
<simple>${ref:esc}</simple>
</setVariable>
<to uri="velocity:com/acme/order.vm"/>
</route> - beans:
- name: esc
type: org.apache.velocity.tools.generic.EscapeTool
- route:
from:
uri: direct:order
steps:
- setVariable:
name: esc
expression:
simple:
expression: ${ref:esc}
- to:
uri: velocity:com/acme/order.vm Dear ${headers.name}. You ordered item $variables.esc.xml(${headers.item}) on $variables.esc.xml(${body}). With a body of Monday & Tuesday the template renders Monday & Tuesday. The same works with $variables.esc.html(…), $variables.esc.json(…), $variables.esc.sql(…), and $variables.esc.url(…).
A message header works the same way (setHeader("esc", constant(new EscapeTool())) and $headers.esc in the template), but a variable keeps the tool out of the message, so it is not sent along to the next endpoint. |
Hot reloading
By default, contentCache is true: Camel loads the Velocity template resource only once, and changes to the resource are not picked up. This suits production, where the resource never changes.
To hot reload the template, set contentCache=false. Camel then loads the resource again for each message, for both file and classpath resources (expanded jar).
Dynamic templates
Camel provides two headers by which you can define a different resource location for a template or the template content itself. If any of these headers is set, and the endpoint has allowTemplateFromHeader=true, then Camel uses this over the endpoint configured resource. This allows you to provide a dynamic template at runtime.
| Header | Type | Description |
|---|---|---|
| String | A URI for the template resource to use instead of the endpoint configured. |
| String | The template to use instead of the endpoint configured. |
Examples
For example, you could use something like
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("velocity:com/acme/MyResponse.vm"); <route>
<from uri="activemq:My.Queue"/>
<to uri="velocity:com/acme/MyResponse.vm"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: velocity:com/acme/MyResponse.vm To use a Velocity template to formulate a response to a message for InOut message exchanges (where there is a JMSReplyTo header).
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("velocity:com/acme/MyResponse.vm")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="velocity:com/acme/MyResponse.vm"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: velocity:com/acme/MyResponse.vm
- to:
uri: activemq:Another.Queue And to use the content cache, e.g., for use in production, where the .vm template never changes:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("velocity:com/acme/MyResponse.vm?contentCache=true")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="velocity:com/acme/MyResponse.vm?contentCache=true"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: velocity:com/acme/MyResponse.vm
parameters:
contentCache: true
- to:
uri: activemq:Another.Queue And a file-based resource:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("velocity:file://myfolder/MyResponse.vm?contentCache=true")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="velocity:file://myfolder/MyResponse.vm?contentCache=true"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: velocity:file://myfolder/MyResponse.vm
parameters:
contentCache: true
- to:
uri: activemq:Another.Queue It’s possible to specify what template the component should use dynamically via a header, so for example:
-
Java
-
XML
-
YAML
from("direct:in")
.setHeader("CamelVelocityResourceUri").constant("path/to/my/template.vm")
.to("velocity:dummy?allowTemplateFromHeader=true"); <route>
<from uri="direct:in"/>
<setHeader name="CamelVelocityResourceUri">
<constant>path/to/my/template.vm</constant>
</setHeader>
<to uri="velocity:dummy?allowTemplateFromHeader=true"/>
</route> - route:
from:
uri: direct:in
steps:
- setHeader:
name: CamelVelocityResourceUri
expression:
constant:
expression: path/to/my/template.vm
- to:
uri: velocity:dummy
parameters:
allowTemplateFromHeader: true It’s possible to specify a template directly as a header. The component should use it dynamically via a header, so for example:
-
Java
-
XML
-
YAML
from("direct:in")
.setHeader("CamelVelocityTemplate").constant("Hi this is a velocity template that can do templating ${body}")
.to("velocity:dummy?allowTemplateFromHeader=true"); <route>
<from uri="direct:in"/>
<setHeader name="CamelVelocityTemplate">
<constant>Hi this is a velocity template that can do templating ${body}</constant>
</setHeader>
<to uri="velocity:dummy?allowTemplateFromHeader=true"/>
</route> - route:
from:
uri: direct:in
steps:
- setHeader:
name: CamelVelocityTemplate
expression:
constant:
expression: "Hi this is a velocity template that can do templating ${body}"
- to:
uri: velocity:dummy
parameters:
allowTemplateFromHeader: true The Email Example
In this sample, we want to use Velocity templating for an order confirmation email. The email template is laid out in Velocity as:
Dear ${headers.lastName}, ${headers.firstName}
Thanks for the order of ${headers.item}.
Regards Camel Riders Bookstore
${body} And the java code (from an unit test):
private Exchange createLetter() {
Exchange exchange = context.getEndpoint("direct:a").createExchange();
Message msg = exchange.getIn();
msg.setHeader("firstName", "Claus");
msg.setHeader("lastName", "Ibsen");
msg.setHeader("item", "Camel in Action");
msg.setBody("PS: Next beer is on me, James");
return exchange;
}
@Test
public void testVelocityLetter() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body(String.class).contains("Thanks for the order of Camel in Action");
template.send("direct:a", createLetter());
mock.assertIsSatisfied();
}
from("direct:a")
.to("velocity:org/apache/camel/component/velocity/letter.vm")
.to("mock:result");