Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: CAMEL-6971
Wiki Markup
h2. CXFRS Component

{note}
When using CXF as a consumer, the [CAMEL:CXF Bean Component] allows you to factor out how message payloads are received from their processing as a RESTful or SOAP web service. This has the potential of using a multitude of transports to consume web services. The bean component's configuration is also simpler and provides the fastest method to implement web services using Camel and CXF.
{note}

The *cxfrs:* component provides integration with [Apache CXF|http://incubator.apache.org/cxf/] for connecting to JAX-RS services hosted in CXF.

Maven users will need to add the following dependency to their pom.xml for this component:
{code:xml}
<dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-cxf</artifactId>
   <version>x.x.x</version>  <!-- use the same version as your Camel core version -->
</dependency>
{code}

h3. URI format

{code}
cxfrs://address?options
{code}
Where *address* represents the CXF endpoint's address
{code}
cxfrs:bean:rsEndpoint
{code}
Where *rsEndpoint* represents the spring bean's name which presents the CXFRS client or server

For either style above, you can append options to the URI as follows:
{code}
cxfrs:bean:cxfEndpoint?resourceClasses=org.apache.camel.rs.Example
{code}

h3. Options
{div:class=confluenceTableSmall}
|| Name || Description || Example || Required? || default value ||
| {{resourceClasses}} | The resource classes which you want to export as REST service. Multiple classes can be separated by comma. | {{resourceClasses=org.apache.camel.rs.Example1,}}
{{org.apache.camel.rs.Exchange2}} | No | _None_ |
| {{resourceClass}} | *Deprecated*: Use {{resourceClasses}} The resource class which you want to export as REST service. | {{resourceClass =org.apache.camel.rs.Example1}} | No | _None_ |
| {{httpClientAPI}} | *new to Camel 2.1* If it is true, the CxfRsProducer will use the HttpClientAPI to invoke the service \\
If it is false, the CxfRsProducer will use the ProxyClientAPI to invoke the service | httpClientAPI=true | No | _true_ |
| synchronous | New in 2.5, this option will let CxfRsConsumer decide to use sync or async API to do the underlying work. The default value is false which means it will try to use async API by default. | synchronous=true | No | false |
| throwExceptionOnFailure | New in 2.6, this option tells the CxfRsProducer to inspect return codes and will generate an Exception if the return code is larger than 207. | throwExceptionOnFailure=true | No | true |
| {{maxClientCacheSize}} | New in 2.6, you can set a IN message header CamelDestinationOverrideUrl to dynamically override the target destination Web Service or REST Service defined in your routes.&nbsp; The implementation caches CXF clients or ClientFactoryBean in CxfProvider and CxfRsProvider.&nbsp; This option allows you to configure the maximum size of the cache. \\ | maxClientCacheSize=5 | No \\ | 10 |
| {{setDefaultBus}} | New in 2.9.0. Will set the default bus when CXF endpoint create a bus by itself | {{setDefaultBus=true}} | No | {{false}} |
| {{bus}} | New in 2.9.0. A default bus created by CXF Bus Factory. Use {{\#}} notation to reference a bus object from the registry. The referenced object must be an instance of {{org.apache.cxf.Bus}}. | {{bus=#busName}} | No | _None_ |
| {{bindingStyle}} | *As of 2.11*. Sets how requests and responses will be mapped to/from Camel. Two values are possible: 
- {{SimpleConsumer}} => see the [Consuming a REST Request with the Simple Binding Style|#Consuming a REST Request - Simple Binding Style] below.
- {{Default}} => the default style. For consumers this passes on a {{MessageContentsList}} to the route, requiring low-level processing in the route. | {{bindingStyle=SimpleConsumer}} | No | _Default_ |
| {{providers}}| *Since Camel 2.12.2* Add custom JAX-RS providers to the list of providers. | No | _None_ |
| {{schemaLocations}} | *Since Camel 2.12.2* Sets the locations of the schemas which can be used to validate the incoming XML or JAXB-driven JSON. | NO | _None_ |
{div}

You can also configure the CXF REST endpoint through the spring configuration. Since there are lots of difference between the CXF REST client and CXF REST Server, we provide different configuration for them.
Please check out the [schema file|http://svn.apache.org/repos/asf/camel/trunk/components/camel-cxf/src/main/resources/schema/cxfEndpoint.xsd] and [CXF REST user guide|http://cwiki.apache.org/CXF20DOC/jax-rs.html] for more information.

h3. How to configure the REST endpoint in Camel

In [camel-cxf schema file|http://svn.apache.org/repos/asf/camel/trunk/components/camel-cxf/src/main/resources/schema/cxfEndpoint.xsd], there are two elements for the REST endpoint definition. *cxf:rsServer* for REST consumer, *cxf:rsClient* for REST producer.
You can find a Camel REST service route configuration example here.

{snippet:id=cxfRsExample|lang=xml|url=camel/trunk/components/camel-cxf/src/test/resources/org/apache/camel/component/cxf/jaxrs/CxfRsSpringRouter.xml}

h3. Consuming a REST Request - Simple Binding Style

*Available as of Camel 2.11*

The {{Default}} binding style is rather low-level, requiring the user to manually process the {{MessageContentsList}} object coming into the route. Thus, it tightly couples the route logic with the method signature and parameter indices of the JAX-RS operation. Somewhat inelegant, difficult and error-prone.

In contrast, the {{SimpleConsumer}} binding style performs the following mappings, in order to *make the request data more accessible* to you within the Camel Message:

* JAX-RS Parameters (@HeaderParam, @QueryParam, etc.) are injected as IN message headers. The header name matches the value of the annotation.
* The request entity (POJO or other type) becomes the IN message body. If a single entity cannot be identified in the JAX-RS method signature, it falls back to the original {{MessageContentsList}}.
* Binary {{@Multipart}} body parts become IN message attachments, supporting {{DataHandler}}, {{InputStream}}, {{DataSource}} and CXF's {{Attachment}} class.
* Non-binary {{@Multipart}} body parts are mapped as IN message headers. The header name matches the Body Part name.

Additionally, the following rules apply to the *Response mapping*:

* If the message body type is different to {{javax.ws.rs.core.Response}} (user-built response), a new {{Response}} is created and the message body is set as the entity (so long it's not null). The response status code is taken from the {{Exchange.HTTP_RESPONSE_CODE}} header, or defaults to 200 OK if not present.
* If the message body type is equal to {{javax.ws.rs.core.Response}}, it means that the user has built a custom response, and therefore it is respected and it becomes the final response.
* In all cases, Camel headers permitted by custom or default {{HeaderFilterStrategy}} are added to the HTTP response.

h4. Enabling the Simple Binding Style

This binding style can be activated by setting the {{bindingStyle}} parameter in the consumer endpoint to value {{SimpleConsumer}}:

{code}
  from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
    .to("log:TEST?showAll=true");
{code}

h4. Examples of request binding with different method signatures

Below is a list of method signatures along with the expected result from the Simple binding.

*{{public Response doAction(BusinessObject request);}}*
Request payload is placed in IN message body, replacing the original MessageContentsList.

*{{public Response doAction(BusinessObject request, @HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);}}*
Request payload placed in IN message body, replacing the original MessageContentsList. Both request params mapped as IN message headers with names abcd and defg.

*{{public Response doAction(@HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);}}*
Both request params mapped as IN message headers with names abcd and defg. The original MessageContentsList is preserved, even though it only contains the 2 parameters.

*{{public Response doAction(@Multipart(value="body1") BusinessObject request, @Multipart(value="body2") BusinessObject request2);}}*
The first parameter is transferred as a header with name body1, and the second one is mapped as header body2. The original MessageContentsList is preserved as the IN message body.

*{{public Response doAction(InputStream abcd);}}*
The InputStream is unwrapped from the MessageContentsList and preserved as the IN message body. 

*{{public Response doAction(DataHandler abcd);}}*
The DataHandler is unwrapped from the MessageContentsList and preserved as the IN message body. 

h4. More examples of the Simple Binding Style

Given a JAX-RS resource class with this method:

{code}
    @POST @Path("/customers/{type}")
    public Response newCustomer(Customer customer, @PathParam("type") String type, @QueryParam("active") @DefaultValue("true") boolean active) {
        return null;
    }
{code}

Serviced by the following route:

{code}
    from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
        .recipientList(simple("direct:${header.operationName}"));

    from("direct:newCustomer")
        .log("Request: type=${header.type}, active=${header.active}, customerData=${body}");
{code}

The following HTTP request with XML payload (given that the Customer DTO is JAXB-annotated):

{code}
POST /customers/gold?active=true

Payload:
<Customer>
  <fullName>Raul Kripalani</fullName>
  <country>Spain</country>
  <project>Apache Camel</project>
</Customer>
{code}

Will print the message:

{code}
Request: type=gold, active=true, customerData=<Customer.toString() representation>
{code}

For more examples on how to process requests and write responses can be found [here|https://svn.apache.org/repos/asf/camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/simplebinding/].

h3. Consuming a REST Request - Default Binding Style

[CXF JAXRS front end|http://cwiki.apache.org/CXF20DOC/jax-rs.html] implements the [JAXRS(JSR311) API|https://jsr311.dev.java.net/], so we can export the resources classes as a REST service. And we leverage the [CXF Invoker API|http://cwiki.apache.org/confluence/display/CXF20DOC/Invokers] to turn a REST request into a normal Java object method invocation.
Unlike the {{camel-restlet}}, you don't need to specify the URI template within your restlet endpoint, CXF take care of the REST request URI to resource class method mapping according to the JSR311 specification. All you need to do in Camel is delegate this method request to a right processor or endpoint.

Here is an example of a CXFRS route...

{snippet:id=example|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsConsumerTest.java}

And the corresponding resource class used to configure the endpoint...

{info:title=note about the resource class}
This class is used to configure the JAXRS properties ONLY.  The methods will NOT be executed during the routing of messages to the endpoint, the route itself is responsible for ALL processing instead.
{info}

{snippet:id=example|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/testbean/CustomerServiceResource.java}

h3. How to invoke the REST service through camel-cxfrs producer

[CXF JAXRS front end|http://cwiki.apache.org/CXF20DOC/jax-rs.html] implements [a proxy based client API|http://cwiki.apache.org/CXF20DOC/jax-rs.html#JAX-RS-ProxybasedAPI], with this API you can invoke the remote REST service through a proxy.
{{camel-cxfrs}} producer is based on this [proxy API|http://cwiki.apache.org/CXF20DOC/jax-rs.html#JAX-RS-ProxybasedAPI].
So, you just need to specify the operation name in the message header and prepare the parameter in the message body, camel-cxfrs producer will generate right REST request for you.

Here is an example
{snippet:id=ProxyExample|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java}
[CXF JAXRS front end|http://cwiki.apache.org/CXF20DOC/jax-rs.html] also provides [a http centric client API|http://cxf.apache.org/docs/jax-rs.html#JAX-RS-HTTPcentricclients], You can also invoke this API from {{camel-cxfrs}} producer. You need to specify the HTTP_PATH and Http method and let the the producer know to use the http centric client by using the URI option *httpClientAPI* or set the message header with CxfConstants.CAMEL_CXF_RS_USING_HTTP_API. You can turn the response object to the type class that you specify with CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS.

{snippet:id=HttpExample|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java}
From Camel 2.1, we also support to specify the query parameters from cxfrs URI for the CXFRS http centric client.
{snippet:id=QueryExample|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java}To support the Dynamical routing, you can override the URI's query parameters by using the CxfConstants.CAMEL_CXF_RS_QUERY_MAP header to set the parameter map for it.
{snippet:id=QueryMapExample|lang=java|url=camel/trunk/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java}