此内容没有您所选择的语言版本。

39.6. Generating Responses Using Templates


Overview

One of the simplest and quickest approaches to generating a response message is to use a velocity template. Figure 39.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 PAYLOAD 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 39.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>
          <convertBodyTo type="org.w3c.dom.Node"/>
          <setHeader headerName="customerId">
            <xpath>/cus:getCustomerStatus/customerId/text()</xpath>
          </setHeader>
          <to uri="getCustomerStatus"/>
          <to uri="velocity:getCustomerStatusResponse.vm"/>
        </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. To facilitate processing the payload body, the first step uses convertBodyTo to convert the body type from org.apache.camel.component.cxf.CxfPayload (the default payload type) to org.w3c.dom.Node.
  2. The route then applies an XPath expression to the message in order to extract the customer ID value and then stashes it in the customerId header.
  3. 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.
  4. Finally, a response is generated using a velocity template.
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).

Converting XPath result to a string

Because the default return type of XPath is a node list, you must explicitly convert the result to a string, if you want to obtain the string contents of an element. There are two alternative ways of obtaining the string value of an element:
  • Specify the result type explicitly using the resultType attribute, as follows:
    <xpath resultType="java.lang.String">/cus:getCustomerStatus/customerId</xpath>
  • Modify the expression so that it returns a text() node, which automatically converts to string:
    <xpath>/cus:getCustomerStatus/customerId/text()</xpath>

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.
In the preceding code, we make the modifications directly to the In message. When the exchange's Out message is null, the next processor in the route gets a copy of the current In message instead
Note
An exceptional case occurs when the message exchange pattern is inOnly, in which case the Out message value is always copied into the In message, even if it is null.

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 reponse is located in the customer-ws-camel-cxf-payload/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

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.