40.6. Generating Responses Using Templates


Overview

One of the simples and quickest approaches to generating a response message is to use a velocity template. Figure 40.3, “Response Generated by Velocity” shows the outline of a general template-based route. At the start of the route is a Camel CXF endpoint in provider mode, which is the appropriate mode to use for processing the message as an XML document. After doing the work required to process the message and stashing some intermediate results in message headers, the route generates the response message using a Velocity template.

Figure 40.3. Response Generated by Velocity

Response Generated by Velocity

Sample template-based route

For example, you could define a template-based route specifically for the getCustoemrStatus operation, as follows:
        ...
        <when>
          <simple>${in.header.operationName} == 'getCustomerStatus'</simple>
          <setHeader headerName="customerId">
            <xpath resultType="java.lang.String">/cus:getCustomerStatus/customerId</xpath>
          </setHeader>
          <to uri="getCustomerStatus"/>
          <to uri="velocity:getCustomerStatusResponse.vm"/>
          <convertBodyTo type="javax.xml.transform.sax.SAXSource"/>
        </when>
      </choice>
    </route>
  </camelContext
  ...
  <bean id="getCustomerStatus"
    class="com.fusesource.customerwscamelcxfpayload.GetCustomerStatus"/>

Route processing steps

Given the preceding route definition, any message whose operation name matches getCustomerStatus would be processed as follows:
  1. The route applies an XPath expression to the message in order to extract the customer ID value and then stashes it in the customerId header.
  2. The next step sends the message to the getCustomerStatus bean, which does whatever processing is required to get the customer status for the specified customer ID. The results from this step are stashed in message headers.
  3. A response is generated using a Velocity template.
  4. Finally, the XML string generated by the Velocity template must be explicitly converted to the javax.xml.transform.sax.SAXSource type using convertBodyTo (which implicitly relies on a type converter).
Note
A common pattern when implementing Apache Camel routes is to use message headers as a temporary stash to hold intermediate results (you could also use exchange properties in the same way).

XPath expressions and SAXSource

XPath expressions can be applied directly to SAXSource objects. The XPath implementation has a pluggable architecture that supports a variety of XML parsers and when XPath encounters a SAXSource object, it automatically loads the plug-in required to support SAXSource parsing.

getCustomerStatus processor bean

The getCustomerStatus processor bean is an instance of the GetCustomerStatus processor class, which is defined as follows:
// Java
package com.fusesource.customerwscamelcxfpayload;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class GetCustomerStatus implements Processor
{
    public void process(Exchange exchng) throws Exception {
        String id = exchng.getIn().getHeader("customerId", String.class);

        // Maybe do some kind of lookup here!
        //

        exchng.getIn().setHeader("status", "Away");
        exchng.getIn().setHeader("statusMessage", "Going to sleep.");
    }
}
The implementation shown here is just a placeholder. In a realistic application you would perform some sort of checks or database lookup to obtain the customer status. In the demonstration code, however, the status and statusMessage are simply set to constant values and stashed in message headers.

getCustomerStatusResponse.vm Velocity template

You can generate a response message very simply using a Velocity template. The Velocity template consists of a message in plain text, where specific pieces of data can be inserted using expressions—for example, the expression ${header.HeaderName} substitutes the value of a named header.
The Velocity template for generating the getCustomerStatus response is located in the customer-ws-camel-cxf-provider/src/main/resources directory and it contains the following template script:
<ns2:getCustomerStatusResponse xmlns:ns2="http://demo.fusesource.com/wsdl/CustomerService/">
   <status>${headers.status}</status>
   <statusMessage>${headers.statusMessage}</statusMessage>
</ns2:getCustomerStatusResponse>
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.