Freemarker
Since Camel 2.10
Only producer is supported
The freemarker: component allows for processing a message using a FreeMarker 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-freemarker</artifactId>
<version>x.x.x</version> <!-- use the same version as your Camel core version -->
</dependency> URI format
freemarker: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.ftl).
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 Freemarker component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether the data model that the producer builds from the exchange also has the exchange, in, request, out, response, exchangeProperty, exchangeProperties and camelContext entries. If false, it has only the body, header, headers, variable, variables and exception entries. Enabling it gives the template the whole Exchange and CamelContext API. The default for the endpoints of the component. | false | boolean | |
Whether the producer reads the CamelFreemarkerResourceUri, CamelFreemarkerTemplate and CamelFreemarkerDataModel headers. If false, the producer ignores all three headers. A template from a header can do all that FreeMarker allows, such as calling the methods of the objects in the data model and, with the default settings of FreeMarker, running commands with the ?new built-in, and the CamelFreemarkerResourceUri header can name any resource, such as a file or an http URL. Enable it only when the route sets these headers, not a message sender. | false | boolean | |
Whether the endpoints of the component cache their template, unless the contentCache option of the endpoint says otherwise. The producer reads a resourceUri with a scheme, such as classpath: or file:, once and keeps its content. A resourceUri without a scheme is loaded by FreeMarker, whose template cache checks whether the template changed once templateUpdateDelay has passed. If false, FreeMarker caches no templates and the producer reads the template on each exchange. | 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 FreeMarker looks for a localized variant of a template first: for foo.ftl and the locale en_US, the default locale of the JVM, it tries foo_en_US.ftl, foo_en.ftl and then foo.ftl. Only for the templates that FreeMarker loads, which are a resourceUri without a scheme and the templates of #include and #import. Not used when the configuration option is set. | 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 | |
The freemarker.template.Configuration for the endpoints of the component, each of which uses a copy (clone) of it. If not set, the component creates one with incompatible improvements 2.3.34 and a template loader that loads the templates through Camel, from the classpath unless the name has a scheme such as file:, and applies localizedLookup. | Configuration |
Endpoint Options
The Freemarker endpoint is configured using URI syntax:
freemarker: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 CamelFreemarkerResourceUri, CamelFreemarkerTemplate and CamelFreemarkerDataModel headers. If false, the producer ignores all three headers. A template from a header can do all that FreeMarker allows, such as calling the methods of the objects in the data model and, with the default settings of FreeMarker, running commands with the ?new built-in, and the CamelFreemarkerResourceUri header can name any resource, such as a file or an http URL. Enable it only when the route sets these headers, not a message sender. | false | boolean | |
The freemarker.template.Configuration that the endpoint uses, in place of the copy of the Configuration of the component. FreeMarker uses it as it is: the templateUpdateDelay and localizedLookup options, and the template cache that contentCache=false turns off, are not applied to it. | Configuration | ||
Sets whether to use resource content cache or not. | true | boolean | |
The name of the character encoding (charset) that FreeMarker uses to read the template of resourceUri, for example UTF-8. If not set, FreeMarker uses the default encoding of the Configuration, which is the default charset of the JVM unless set otherwise. Only used for a resourceUri without a scheme: the producer reads a resourceUri with a scheme, such as classpath: or file:, with the default charset of the JVM. Not used for the CamelFreemarkerTemplate header, which is already text. | String | ||
The number of seconds after which FreeMarker checks again whether a cached template changed, and reloads it if so (the template update delay of the Configuration). 0 or less keeps the delay of the Configuration, which is 5 seconds unless set otherwise. Only used when contentCache is true, and only for a resourceUri without a scheme: the producer reads a resourceUri with a scheme, such as classpath: or file:, once and does not check it for changes. Not applied to a Configuration that the configuration option of the endpoint sets. | int | ||
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 Freemarker component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelFreemarkerResourceUri (producer) Constant: | The URI of a template that the producer renders in place of the template of resourceUri, in the same form as resourceUri (a path on the classpath, or a URI with a scheme such as file: or http:). Only used when allowTemplateFromHeader is true. The producer removes the header and hands the exchange to the freemarker endpoint of that URI, with the same options as this endpoint, which renders the text of a CamelFreemarkerTemplate header instead if one is set. | String | |
CamelFreemarkerTemplate (producer) Constant: | The text of a FreeMarker template that the producer renders in place of the template of resourceUri. Only used when allowTemplateFromHeader is true. The producer parses it on each exchange, without caching, and removes the header after reading it. | String | |
CamelFreemarkerDataModel (producer) Constant: | The data model that the template reads, in place of the Map that the producer builds from the exchange with the body, the headers and the other entries: a java.util.Map with String keys or a JavaBean, whose entries or properties are the top-level variables of the template. Only used when allowTemplateFromHeader is true. The producer does not remove the header. | Object |
Message Body
The message body at each side of the Freemarker 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, and no body fails ${body} unless it is written ${body!}. The template is the resource, or the CamelFreemarkerTemplate or CamelFreemarkerResourceUri 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
Headers set during the FreeMarker evaluation are returned to the message and added as headers. This provides a mechanism for the FreeMarker component to return values to the Message.
For example, set the header value of fruit in the FreeMarker template (request is only available when the endpoint has allowContextMapAll=true):
${request.setHeader('fruit', 'Apple')} The header, fruit, is now accessible from the message.out.headers.
Usage
FreeMarker Context
Camel will provide exchange information in the FreeMarker 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 In message body. |
| The headers of the In message. |
| The variables. |
| The exception of the |
| The In message (only with |
| The Out message (only with |
| The |
| The |
| The Camel Context (only with |
You can set up your custom FreeMarker context in the message header with the key "CamelFreemarkerDataModel" just like this
Map<String, Object> variableMap = new HashMap<String, Object>();
variableMap.put("headers", headersMap);
variableMap.put("body", "Monday");
variableMap.put("exchange", exchange);
exchange.getIn().setHeader("CamelFreemarkerDataModel", variableMap); Hot reloading
A resourceUri with a scheme, such as file: or classpath:, is by default not hot reloadable: Camel caches the content. If you set contentCache=false, then Camel does not cache the resource and hot reloading is thus enabled. This scenario can be used in development.
A resourceUri without a scheme is loaded by FreeMarker itself, which checks whether the template has changed at most every templateUpdateDelay seconds (5 by default), also with contentCache=true.
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.
Examples
For example, you could use something like:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("freemarker:com/acme/MyResponse.ftl"); <route>
<from uri="activemq:My.Queue"/>
<to uri="freemarker:com/acme/MyResponse.ftl"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: freemarker:com/acme/MyResponse.ftl To use a FreeMarker template to formulate a response for 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:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("freemarker:com/acme/MyResponse.ftl")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="freemarker:com/acme/MyResponse.ftl"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: freemarker:com/acme/MyResponse.ftl
- to:
uri: activemq:Another.Queue And to disable the content cache, e.g., for development usage where the .ftl template should be hot reloaded:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("freemarker:com/acme/MyResponse.ftl?contentCache=false")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="freemarker:com/acme/MyResponse.ftl?contentCache=false"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: freemarker:com/acme/MyResponse.ftl
parameters:
contentCache: false
- to:
uri: activemq:Another.Queue And a file-based resource:
-
Java
-
XML
-
YAML
from("activemq:My.Queue")
.to("freemarker:file://myfolder/MyResponse.ftl?contentCache=false")
.to("activemq:Another.Queue"); <route>
<from uri="activemq:My.Queue"/>
<to uri="freemarker:file://myfolder/MyResponse.ftl?contentCache=false"/>
<to uri="activemq:Another.Queue"/>
</route> - route:
from:
uri: activemq:My.Queue
steps:
- to:
uri: freemarker:file://myfolder/MyResponse.ftl
parameters:
contentCache: false
- 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("CamelFreemarkerResourceUri").constant("path/to/my/template.ftl")
.to("freemarker:dummy?allowTemplateFromHeader=true"); <route>
<from uri="direct:in"/>
<setHeader name="CamelFreemarkerResourceUri">
<constant>path/to/my/template.ftl</constant>
</setHeader>
<to uri="freemarker:dummy?allowTemplateFromHeader=true"/>
</route> - route:
from:
uri: direct:in
steps:
- setHeader:
name: CamelFreemarkerResourceUri
expression:
constant:
expression: path/to/my/template.ftl
- to:
uri: freemarker:dummy
parameters:
allowTemplateFromHeader: true