이 콘텐츠는 선택한 언어로 제공되지 않습니다.

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

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"/>
Copy to Clipboard Toggle word wrap

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>
    Copy to Clipboard Toggle word wrap
  • Modify the expression so that it returns a text() node, which automatically converts to string:
    <xpath>/cus:getCustomerStatus/customerId/text()</xpath>
    Copy to Clipboard Toggle word wrap

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.");
    }
}
Copy to Clipboard Toggle word wrap
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>
Copy to Clipboard Toggle word wrap
맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat