Camel Component: CXF - 6.3

Talend ESB Mediation Developer Guide

EnrichVersion
6.3
EnrichProdName
Talend Data Fabric
Talend Data Services Platform
Talend ESB
Talend MDM Platform
Talend Open Studio for ESB
Talend Real-Time Big Data Platform
task
Design and Development
EnrichPlatform
Talend ESB

Note

When using CXF as a consumer, the Camel Component: CXF Bean 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.

When using CXF in streaming modes (see DataFormat option), then also read about Stream caching.

The cxf: component provides integration with Apache CXF for connecting to JAX-WS services hosted in CXF.

Maven users will need to add the following dependency to their pom.xml for this component:

<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>

Note

To learn about CXF dependencies the WHICH-JARS text file can be viewed.

URI format

There are two scenarios:

cxf:bean:cxfEndpoint[?options]

where cxfEndpoint represents a bean ID that references a bean in the Spring bean registry. With this URI format, most of the endpoint details are specified in the bean definition.

cxf://someAddress[?options]

where someAddress specifies the CXF endpoint's address. With this URI format, most of the endpoint details are specified using options.

For either style above, you can append options to the URI as follows:

cxf:bean:cxfEndpoint?wsdlURL=wsdl/hello_world.wsdl&dataFormat=PAYLOAD

Options

Name

Required

Description

wsdlURL

No

The location of the WSDL. It is obtained from endpoint address by default.

Example: file://local/wsdl/hello.wsdl or wsdl/hello.wsdl

serviceClass

Yes

The name of the SEI (Service Endpoint Interface) class. This class can have, but does not require, JSR181 annotations.

This option is only required by POJO mode. If the wsdlURL option is provided, serviceClass is not required for PAYLOAD and MESSAGE mode. When wsdlURL option is used without serviceClass, the serviceName and portName (endpointName for Spring configuration) options MUST be provided. It is possible to use # notation to reference a serviceClass object instance from the registry. For example, serviceClass=#beanName. The serviceClass for a CXF producer (that is, the to endpoint) should be a Java interface.

It is possible to omit both wsdlURL and serviceClass options for PAYLOAD and MESSAGE mode. When they are omitted, arbitrary XML elements can be put in CxfPayload's body in PAYLOAD mode to facilitate CXF Dispatch Mode.

Please be advised that the referenced object cannot be a Proxy (Spring AOP Proxy is OK) as it relies on Object.getClass().getName() method for non Spring AOP Proxy.

Example: org.apache.camel.Hello

serviceClassInstance

Yes

Use either serviceClass or serviceClassInstance.

Deprecated in 2.x. In 1.6.x serviceClassInstance works like serviceClass=#beanName, which looks up a serviceObject instance from the registry.

Example: serviceClassInstance= beanName

serviceName

No

The service name this service is implementing, it maps to the wsdl:service@name

*Required for camel-cxf consumer since camel-2.2.0 or if more than one serviceName is present in WSDL.

Example: {http:­//org.apache.camel}ServiceName

endpointName

No

The port name this service is implementing, it maps to the wsdl:port@name

*Required for camel-cxf consumer since camel-2.2.0 or if more than one portName is present under serviceName. Example: {http:­//org.apache.camel}PortName

dataFormat

No

The data type messages supported by the CXF endpoint.

Default: POJO

Example: POJO,PAYLOAD,MESSAGE

relayHeaders

No

Please see the Description of relayHeaders option section for this option in 2.0. Should a CXF endpoint relay headers along the route. Currently only available when dataFormat=POJO

Default: true

Example:true,false

wrapped

No

Which kind of operation that CXF endpoint producer will invoke.

Default:false

Example:true,false

wrappedStyle

No

New in 2.5.0 The WSDL style that describes how parameters are represented in the SOAP body. If the value is false, CXF will chose the document-literal unwrapped style. If the value is true, CXF will chose the document-literal wrapped style.

Default: Null

Example:true,false

setDefaultBus

No

This will set the default bus when CXF endpoint create a bus by itself.

Default: false

Example:true,false

bus

No

New in 2.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 .

Example: bus=#busName

cxfBinding

No

New in 2.0, use # notation to reference a CXF binding object from the registry. The referenced object must be an instance of org.apache.camel.component.cxf.CxfBinding (use an instance of org.apache.camel.component.cxf. DefaultCxfBinding).

Example: cxfBinding=#bindingName

headerFilterStrategy

No

Use # notation to reference a header filter strategy object from the registry. The referenced object must be an instance of org.apache.camel.spi.HeaderFilterStrategy (use an instance of org.apache.camel.component.cxf. CxfHeaderFilter-Strategy). .

Example: headerFilterStrategy=#strategyName

loggingFeatureEnabled

No

New in 2.3, this option enables CXF Logging Feature which writes inbound and outbound SOAP messages to log.

Default:false

Example:loggingFeatureEnabled=true

defaultOperationName

No

New in 2.4, this option will set the default operationName that will be used by the CxfProducer which invokes the remote service.

Default: null

Example:defaultOperationName=greetMe

defaultOperationName-space

No

New in 2.4, this option will set the default operationNamespace that will be used by the CxfProducer which invokes the remote service.

Default: null

Example:defaultOperationNamespace= http://apache.org/hello_world_soap_http

synchronous

No

New in 2.5, this option will let cxf endpoint decide to use sync or async API to do the underlying work. The default value is false which means camel-cxf endpoint will try to use async API by default. Default: false

Example: synchronous=true

publishedEndpointUrl

No

New in 2.5, this option can override the endpointUrl that published from the WSDL which can be accessed with service address url plus ?wsdl.

Default: null

Example:publshedEndpointUrl=http://example.com/service

properties.XXX

No

Allows for setting custom properties to CXF in the endpoint URI. For example setting properties.mtom-enabled = true to enable MTOM.

allowStreaming

No

This option controls whether the CXF component, when running in PAYLOAD mode, will parse the incoming messages into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases.

skipFaultLogging

No

Starting in 2.11, this option controls whether the PhaseInterceptorChain skips logging Faults that it catches.

username

No

New in Camel 2.12.3 This option is used to set the basic authentication information of username for the CXF client.

password

No

New in Camel 2.12.3 This option is used to set the basic authentication information of password for the CXF client.

continuationTimeout

No

New in Camel 2.14.0 This option is used to set the CXF continuation timeout which could be used in CxfConsumer by default when the CXF server is using Jetty or Servlet transport. (Before Camel 2.14.0, CxfConsumer just set the continuation timeout to be 0, which means the continuation suspend operation never timeout.)

Default: 30000 

Example: continuation=80000

The serviceName and portName are QNames, so if you provide them, be sure to prefix them with their {namespace} as shown in the examples above.

The descriptions of the dataformats

DataFormat

Description

POJO

POJOs (Plain old Java objects) are the Java parameters to the method being invoked on the target server. Both Protocol and Logical JAX-WS handlers are supported.

PAYLOAD

PAYLOAD is the message payload (the contents of the soap:body ) after message configuration in the CXF endpoint is applied. Only Protocol JAX-WS handlers are supported. Logical JAX-WS handlers are not.

MESSAGE

MESSAGE is the raw message that is received from the transport layer. It is not suppose to touch or change Stream, some of the CXF interceptors will be removed if you are using this kind of DataFormat so you can't see any soap headers after the camel-cxf consumer and JAX-WS handler is not supported.

CXF_MESSAGE

Starting with Camel 2.8.2, CXF_MESSAGE allows for invoking the full capabilities of CXF interceptors by converting the message from the transport layer into a raw SOAP message.

You can determine the data format mode of an exchange by retrieving the exchange property, CamelCXFDataFormat. The exchange key constant is defined in org.apache.camel.component.cxf.CxfConstants.DATA_FORMAT_PROPERTY .

Logging Messages

CXF's default logger is java.util.logging . If you want to change it to log4j, proceed as follows. Create a file, in the classpath, named META-INF/cxf/org.apache.cxf.logger . This file should contain the fully-qualified name of the class, org.apache.cxf.common.logging.Log4jLogger, with no comments, on a single line.

Note CXF's LoggingOutInterceptor outputs outbound messages that are sent on the wire to the logging system (Java Util Logging). Since the LoggingOutInterceptor is in PRE_STREAM phase (but PRE_STREAM phase is removed in MESSAGE mode), you have to configure LoggingOutInterceptor to be run during the WRITE phase. The following is an example:

<bean id="loggingOutInterceptor" 
   class="org.apache.cxf.interceptor.LoggingOutInterceptor">
   <!-- it really should have been user-prestream, -->
   <!-- but CXF does have such phase! -->
   <constructor-arg value="write"/> 
</bean>
   		
<cxf:cxfEndpoint id="serviceEndpoint" 
   address="http://localhost:9002/helloworld"  
   serviceClass="org.apache.camel.component.cxf.HelloService">
   <cxf:outInterceptors>
      <ref bean="loggingOutInterceptor"/>
   </cxf:outInterceptors>
   <cxf:properties>
      <entry key="dataFormat" value="MESSAGE"/>
   </cxf:properties>
</cxf:cxfEndpoint>

Description of relayHeaders option

There are in-band and out-of-band on-the-wire headers from the perspective of a JAXWS WSDL-first developer.

The in-band headers are headers that are explicitly defined as part of the WSDL binding contract for an endpoint such as SOAP headers.

The out-of-band headers are headers that are serialized over the wire, but are not explicitly part of the WSDL binding contract.

Headers relaying/filtering is bi-directional.

When a route has a CXF endpoint and the developer needs to have on-the-wire headers, such as SOAP headers, be relayed along the route to be consumed say by another JAXWS endpoint, then relayHeaders should be set to true, which is the default value.

The relayHeaders=true express an intent to relay the headers. The decision on whether a given header is relayed is delegated to a pluggable instance that implements the MessageHeadersRelay interface. A concrete implementation of MessageHeadersRelay will be consulted to decide if a header needs to be relayed or not. There is already an implementation of SoapMessageHeadersRelay which binds itself to well-known SOAP name spaces. Currently only out-of-band headers are filtered, and in-band headers will always be relayed when relayHeaders=true . If there is a header on the wire, whose name space is unknown to the runtime, then a fall back DefaultMessageHeadersRelay will be used, which simply allows all headers to be relayed.

The relayHeaders=false setting asserts that all headers in-band and out-of-band will be dropped.

  • POJO and PAYLOAD modes are supported. In POJO mode, only out-of-band message headers are available for filtering as the in-band headers have been processed and removed from header list by CXF. The in-band headers are incorporated into the MessageContentList in POJO mode. If filtering of in-band headers is required, please use PAYLOAD mode or plug in a (pretty straightforward) CXF interceptor/JAXWS Handler to the CXF endpoint.

  • The Message Header Relay mechanism has been merged into CxfHeaderFilterStrategy . The relayHeaders option, its semantics, and default value remain the same, but it is a property of CxfHeaderFilterStrategy . Here is an example of configuring it:

    <bean id="dropAllMessageHeadersStrategy" 
       class="org.apache.camel.component.cxf.CxfHeaderFilterStrategy">
       <!--  Set relayHeaders to false to drop all SOAP headers -->
       <property name="relayHeaders" value="false"/> 
    </bean>

    Then, your endpoint can reference the CxfHeaderFilterStrategy .

    <route>
       <from uri="cxf:bean:routerNoRelayEndpoint?headerFilterStrategy   //
          #dropAllMessageHeadersStrategy"/>          
       <to uri="cxf:bean:serviceNoRelayEndpoint?headerFilterStrategy   //
          #dropAllMessageHeadersStrategy"/>
    </route>
    
  • The MessageHeadersRelay interface has changed slightly and has been renamed to MessageHeaderFilter . It is a property of CxfHeaderFilterStrategy . Here is an example of configuring user defined Message Header Filters:

    <bean id="customMessageFilterStrategy" 
    			class="org.apache.camel.component.cxf.CxfHeaderFilterStrategy">
       <property name="messageHeaderFilters">
          <list>
             <!-- SoapMessageHeaderFilter is the built in filter.  -->
             <!-- It can be removed by omitting it. -->
             <bean class=
                "org.apache.camel.component.cxf.SoapMessageHeaderFilter"/>
                
             <!--  Add custom filter here -->    
             <bean class=
                "org.apache.camel.component.cxf.soap.CustomHeaderFilter"/>
          </list>
       </property>
    </bean>

  • Other than relayHeaders, there are new properties that can be configured in CxfHeaderFilterStrategy.

    Name

    Description

    type

    Required?

    Default value

    relayHeaders

    All message headers will be processed by Message Header Filters

    boolean

    No

    true

    relayAll-MessageHeaders

    All message headers will be propagated (without processing by Message Header Filters)

    boolean

    No

    false

    allowFilter-NamespaceClash

    If two filters overlap in activation namespace, the property control how it should be handled. If the value is true, last one wins. If the value is false, it will throw an exception

    boolean

    No

    false

Configure the CXF endpoints with Spring

You can configure the CXF endpoint with the Spring configuration file shown below, and you can also embed the endpoint into the camelContext tags. When you are invoking the service endpoint, you can set the operationName and operationNamespace headers to explicitly state which operation you are calling.

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:cxf="http://camel.apache.org/schema/cxf"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
      http://camel.apache.org/schema/cxf 
         http://camel.apache.org/schema/cxf/camel-cxf.xsd
      http://camel.apache.org/schema/spring 
         http://camel.apache.org/schema/spring/camel-spring.xsd">

   <cxf:cxfEndpoint id="routerEndpoint" 
      address="http://localhost:9003/CamelContext/RouterPort"
      serviceClass="org.apache.hello_world_soap_http.GreeterImpl"/>
            
   <cxf:cxfEndpoint id="serviceEndpoint" 
      address="http://localhost:9000/SoapContext/SoapPort"
      wsdlURL="testutils/hello_world.wsdl"
      serviceClass="org.apache.hello_world_soap_http.Greeter"
      endpointName="s:SoapPort"
      serviceName="s:SOAPService"
      xmlns:s="http://apache.org/hello_world_soap_http" />
                  
   <camelContext id="camel" 
      xmlns="http://activemq.apache.org/camel/schema/spring">
      <route>
         <from uri="cxf:bean:routerEndpoint" />
         <to uri="cxf:bean:serviceEndpoint" />
      </route>
   </camelContext>
</beans>

Be sure to include the JAX-WS schemaLocation attribute specified on the root beans element. This allows CXF to validate the file and is required. Also note the namespace declarations at the end of the <cxf:cxfEndpoint/> tag--these are required because the combined { namespace}localName syntax is presently not supported for this tag's attribute values.

The cxf:cxfEndpoint element supports many additional attributes:

Name

Value

PortName

The endpoint name this service is implementing, it maps to the wsdl:port@name . In the format of ns:PORT_NAME where ns is a namespace prefix valid at this scope.

serviceName

The service name this service is implementing, it maps to the wsdl:service@name . In the format of ns:SERVICE_NAME where ns is a namespace prefix valid at this scope.

wsdlURL

The location of the WSDL. Can be on the classpath, file system, or be hosted remotely.

bindingId

The bindingId for the service model to use.

address

The service publish address.

bus

The bus name that will be used in the JAX-WS endpoint.

serviceClass

The class name of the SEI (Service Endpoint Interface) class which could have JSR181 annotation or not.

It also supports many child elements:

Name

Value

cxf:inInterceptors

The incoming interceptors for this endpoint. A list of <bean> or <ref>.

cxf:inFaultInterceptors

The incoming fault interceptors for this endpoint. A list of <bean> or <ref> .

cxf:outInterceptors

The outgoing interceptors for this endpoint. A list of <bean> or <ref> .

cxf:outFaultInterceptors

The outgoing fault interceptors for this endpoint. A list of <bean> or <ref> .

cxf:properties

A properties map which should be supplied to the JAX-WS endpoint. See below.

cxf:handlers

A JAX-WS handler list which should be supplied to the JAX-WS endpoint. See below.

cxf:dataBinding

You can specify the which DataBinding will be use in the endpoint. This can be supplied using the Spring <bean class="MyDataBinding"/> syntax.

cxf:binding

You can specify the BindingFactory for this endpoint to use. This can be supplied using the Spring <bean class="MyBindingFactory"/> syntax.

cxf:features

The features that hold the interceptors for this endpoint. A list of {{<bean>}}s or {{<ref>}}s

cxf:schemaLocations

The schema locations for endpoint to use. A list of {{<schemaLocation>}}s

cxf:serviceFactory

The service factory for this endpoint to use. This can be supplied using the Spring <bean class="MyServiceFactory"/> syntax

You can find more advanced examples that show how to provide interceptors, properties and handlers on the CXF JAX-WS Configuration page.

NOTE You can use cxf:properties to set the camel-cxf endpoint's dataFormat and setDefaultBus properties from Spring configuration file.

<cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/router"
   serviceClass="org.apache.camel.component.cxf.HelloService"
   endpointName="s:PortName"
   serviceName="s:ServiceName"
   xmlns:s="http://www.example.com/test">
   <cxf:properties>
      <entry key="dataFormat" value="MESSAGE"/>
      <entry key="setDefaultBus" value="true"/>
   </cxf:properties>
</cxf:cxfEndpoint>

How to consume a message from a camel-cxf endpoint in POJO data format

The camel-cxf endpoint consumer POJO data format is based on the cxf invoker, so the message header has a property with the name of CxfConstants.OPERATION_NAME and the message body is a list of the SEI method parameters.

public class PersonProcessor implements Processor {

   private static final transient Logger LOG = 
      LoggerFactory.getLogger(PersonProcessor.class);

   @SuppressWarnings("unchecked")
   public void process(Exchange exchange) throws Exception {
      LOG.info("processing exchange in camel");

      BindingOperationInfo boi = 
         (BindingOperationInfo)exchange.getProperty(
         BindingOperationInfo.class.toString());
      if (boi != null) {
         LOG.info("boi.isUnwrapped" + boi.isUnwrapped());
      }
      // Get the parameters list which element is the holder.
      MessageContentsList msgList = (
         MessageContentsList)exchange.getIn().getBody();
            
      Holder<String> personId = (Holder<String>)msgList.get(0);
      Holder<String> ssn = (Holder<String>)msgList.get(1);
      Holder<String> name = (Holder<String>)msgList.get(2);

      if (personId.value == null || personId.value.length() == 0) {
         LOG.info("person id 123, so throwing exception");
         // Try to throw out the soap fault message
         org.apache.camel.wsdl_first.types.UnknownPersonFault personFault =
            new org.apache.camel.wsdl_first.types.UnknownPersonFault();
         personFault.setPersonId("");
         org.apache.camel.wsdl_first.UnknownPersonFault fault =
            new org.apache.camel.wsdl_first.UnknownPersonFault(
            "Get the null value of person name", personFault);
         // Since Camel has its own exception handler framework, we can't 
         // throw the exception to trigger it. We set the fault message
         // in the exchange for camel-cxf component handling and return
         exchange.getOut().setFault(true);
         exchange.getOut().setBody(fault);
         return;
      }

      name.value = "Bonjour";
      ssn.value = "123";
      LOG.info("setting Bonjour as the response");
      // Set the response message, first element is the return value of 
      // the operation, the others are the holders of method parameters
      exchange.getOut().setBody(new Object[] {null, personId, ssn, name});
   }
}

How to prepare the message for the camel-cxf endpoint in POJO data format

The camel-cxf endpoint producer is based on the CXF client API. First you need to specify the operation name in the message header, then add the method parameters to a list, and initialize the message with this parameter list. The response message's body is a messageContentsList; you can get the result from that list.

Note: the message body is a MessageContentsList. If you want to get the object array from the message body, you can get the body using message.getbody(Object[].class), as follows:

Exchange senderExchange = new DefaultExchange(context, 
   ExchangePattern.InOut);
final List<String> params = new ArrayList<String>();

// Prepare the request message for the camel-cxf procedure
params.add(TEST_MESSAGE);
senderExchange.getIn().setBody(params);
senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, 
   ECHO_OPERATION);

Exchange exchange = template.send("direct:EndpointA", senderExchange);

org.apache.camel.Message out = exchange.getOut();

// The response message's body is a MessageContentsList whose first 
// element is the return value of the operation. If there are some holder
// parameters, the holder parameter will be filled in the rest of List.
// The result will be extracted from the MessageContentsList with the
// String class type
MessageContentsList result = (MessageContentsList)out.getBody();
LOG.info("Received output text: " + result.get(0));
Map<String, Object> responseContext = 
   CastUtils.cast((Map)out.getHeader(Client.RESPONSE_CONTEXT));
assertNotNull(responseContext);
assertEquals("We should get the response context here", "UTF-8", 
   responseContext.get(org.apache.cxf.message.Message.ENCODING));
assertEquals("Reply body on Camel is wrong", "echo " + 
   TEST_MESSAGE, result.get(0));

How to deal with the message for a camel-cxf endpoint in PAYLOAD data format

PAYLOAD means that you process the payload message from the SOAP envelope. You can use the Header.HEADER_LIST as the key to set or get the SOAP headers and use the List<Element> to set or get SOAP body elements.

We use the common Camel DefaultMessageImpl underlayer. Message.getBody() will return an org.apache.camel.component.cxf.CxfPayload object, which has getters for SOAP message headers and Body elements. This change enables decoupling the native CXF message from the Camel message.

protected RouteBuilder createRouteBuilder() {
   return new RouteBuilder() {
      public void configure() {
         from(SIMPLE_ENDPOINT_URI + "&dataFormat=PAYLOAD")
            .to("log:info").process(new Processor() {
            @SuppressWarnings("unchecked")
            public void process(final Exchange exchange) 
            throws Exception{
               CxfPayload<SoapHeader> requestPayload = 
                     exchange.getIn().getBody(CxfPayload.class);
               List<Element> inElements = requestPayload.getBody();
               List<Element> outElements = new ArrayList<Element>();
               // You can use a customer toStringConverter to turn a 
               // CxfPayLoad message into String as you want
               String request = exchange.getIn().getBody(String.class);
               XmlConverter converter = new XmlConverter();
               String docString = ECHO_RESPONSE;
               if (inElements.get(0).getLocalName().
                  equals("echoBoolean")) {
                  docString = ECHO_BOOLEAN_RESPONSE;
                  assertEquals("Get a wrong request", 
                        ECHO_BOOLEAN_REQUEST, request);
               } else {
                  assertEquals("Get a wrong request", ECHO_REQUEST, 
                     request);
               }
               Document outDocument = converter.toDOMDocument(docString);
               outElements.add(outDocument.getDocumentElement());
               // set the payload header with null
               CxfPayload<SoapHeader> responsePayload = 
                        new CxfPayload<SoapHeader>(null, outElements);
               exchange.getOut().setBody(responsePayload); 
            }
         });
      }
   };
}

How to get and set SOAP headers in POJO mode

POJO means that the data format is a "list of Java objects" when the Camel-cxf endpoint produces or consumes Camel exchanges. Even though Camel expose message body as POJOs in this mode, Camel-cxf still provides access to read and write SOAP headers. However, since CXF interceptors remove in-band SOAP headers from Header list after they have been processed, only out-of-band SOAP headers are available to Camel-cxf in POJO mode.

The following example illustrate how to get/set SOAP headers. Suppose we have a route that forwards from one Camel-cxf endpoint to another. That is, SOAP Client -> Camel -> CXF service. We can attach two processors to obtain/insert SOAP headers at (1) before request goes out to the CXF service and (2) before response comes back to the SOAP Client. Processor (1) and (2) in this example are InsertRequestOutHeaderProcessor and InsertResponseOutHeaderProcessor. Our route looks like this:

<route>
   <from uri="cxf:bean:routerRelayEndpointWithInsertion"/>
   <process ref="InsertRequestOutHeaderProcessor" />
   <to uri="cxf:bean:serviceRelayEndpointWithInsertion"/>
   <process ref="InsertResponseOutHeaderProcessor" />
</route>     

In 2.x SOAP headers are propagated to and from Camel Message headers. The Camel message header name is "org.apache.cxf.headers.Header.list" which is a constant defined in CXF (org.apache.cxf.headers.Header.HEADER_LIST). The header value is a List of CXF SoapHeader objects (org.apache.cxf.binding.soap.SoapHeader). The following snippet is the InsertResponseOutHeaderProcessor (that inserts a new SOAP header in the response message). The way to access SOAP headers in both InsertResponseOutHeaderProcessor and InsertRequestOutHeaderProcessor is the same. The only difference between the two processors is setting the direction of the inserted SOAP header.

public static class InsertResponseOutHeaderProcessor implements Processor {

   @SuppressWarnings("unchecked")
   public void process(Exchange exchange) throws Exception {
      List<SoapHeader> soapHeaders = 
               (List)exchange.getIn().getHeader(Header.HEADER_LIST);

      // Insert a new header
      String xml = 
         "<?xml version=\"1.0\" encoding=\"utf-8\"?><outofbandHeader "
         + "xmlns=\"http://cxf.apache.org/outofband/Header\" "
         + "hdrAttribute=\"testHdrAttribute\" "
         + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
         + "soap:mustUnderstand=\"1\"><name>"
         + "New_testOobHeader</name><value>New_testOobHeaderValue"
         + "</value></outofbandHeader>";
            
      SoapHeader newHeader = new SoapHeader(soapHeaders.get(0).
         getName(), DOMUtils.readXml(new StringReader(xml)).
         getDocumentElement());
                 
      // make sure direction is OUT since it is a response message.
      newHeader.setDirection(Direction.DIRECTION_OUT);
      //newHeader.setMustUnderstand(false);
      soapHeaders.add(newHeader);
    }  
}

In 1.x SOAP headers are not propagated to and from Camel Message headers. Users have to go deeper into CXF APIs to access SOAP headers. Also, accessing the SOAP headers in a request message is slight different than in a response message. The InsertRequestOutHeaderProcessor and InsertResponseOutHeaderProcessor are as follows:

public static class InsertRequestOutHeaderProcessor implements Processor {

   public void process(Exchange exchange) throws Exception {
      CxfMessage message = exchange.getIn().getBody(CxfMessage.class);
      Message cxf = message.getMessage();
      List<SoapHeader> soapHeaders = (List)cxf.get(Header.HEADER_LIST);

      // Insert a new header
      String xml = 
         "<?xml version=\"1.0\" encoding=\"utf-8\"?><outofbandHeader "
         + "xmlns=\"http://cxf.apache.org/outofband/Header\" "
         + "hdrAttribute=\"testHdrAttribute\" "
         + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\""
         + " soap:mustUnderstand=\"1\"><name>"
         + "New_testOobHeader</name><value>New_testOobHeaderValue"
         + "</value></outofbandHeader>";
        
      SoapHeader newHeader = new SoapHeader(soapHeaders.get(0).getName(),
         DOMUtils.readXml(new StringReader(xml)).getDocumentElement());

      // make sure direction is IN since it is a request message.
      newHeader.setDirection(Direction.DIRECTION_IN);
      //newHeader.setMustUnderstand(false);
      soapHeaders.add(newHeader);       
   }
}

public static class InsertResponseOutHeaderProcessor 
   implements Processor {

   public void process(Exchange exchange) throws Exception {
      CxfMessage message = exchange.getIn().getBody(CxfMessage.class);
      Map responseContext = 
         (Map)message.getMessage().get(Client.RESPONSE_CONTEXT);
      List<SoapHeader> soapHeaders = 
         (List)responseContext.get(Header.HEADER_LIST);
   
      // Insert a new header
      String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
         + "<outofbandHeader xmlns="
         + "\"http://cxf.apache.org/outofband/Header\" "
         + "hdrAttribute=\"testHdrAttribute\" "
         + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
         + "soap:mustUnderstand=\"1\">"
         + "<name>New_testOobHeader</name><value>"
         + "New_testOobHeaderValue</value></outofbandHeader>";
            
      SoapHeader newHeader = new SoapHeader(soapHeaders.get(0).
         getName(),
         DOMUtils.readXml(new StringReader(xml)).getDocumentElement()
      );
 
      // make sure direction is OUT since it is a response message.
      newHeader.setDirection(Direction.DIRECTION_OUT);
      //newHeader.setMustUnderstand(false);
      soapHeaders.add(newHeader);
   }
}

How to get and set SOAP headers in PAYLOAD mode

We've already shown how to access SOAP message (CxfPayload object) in PAYLOAD mode (See "How to deal with the message for a camel-cxf endpoint in PAYLOAD data format").

In 2.x Once you obtain a CxfPayload object, you can invoke the CxfPayload.getHeaders() method that returns a List of DOM Elements (SOAP headers).

from(getRouterEndpointURI()).process(new Processor() {
   @SuppressWarnings("unchecked")
   public void process(Exchange exchange) throws Exception {
      CxfPayload<SoapHeader> payload = 
         exchange.getIn().getBody(CxfPayload.class);
      List<Element> elements = payload.getBody();
      assertNotNull("We should get the elements here", elements);
      assertEquals("Get the wrong elements size", 1, elements.size());
      assertEquals("Get the wrong namespace URI", 
         "http://camel.apache.org/pizza/types", 
         elements.get(0).getNamespaceURI());
            
      List<SoapHeader> headers = payload.getHeaders();
      assertNotNull("We should get the headers here", headers);
      assertEquals("Get the wrong headers size", headers.size(), 1);
      assertEquals("Get the wrong namespace URI", 
         ((Element)(headers.get(0).getObject())).getNamespaceURI(), 
         "http://camel.apache.org/pizza/types");         
   }  
})
.to(getServiceEndpointURI());

SOAP headers are not available in MESSAGE mode

SOAP headers are not available in MESSAGE mode as SOAP processing is skipped.

How to throw a SOAP Fault from Camel

If you are using a camel-cxf endpoint to consume the SOAP request, you may need to throw the SOAP Fault from the Camel context. Basically, you can use the throwFault DSL to do that; it works for POJO, PAYLOAD and MESSAGE data format. You can define the soap fault like this

SOAP_FAULT = new SoapFault(EXCEPTION_MESSAGE, SoapFault.FAULT_CODE_CLIENT);
Element detail = SOAP_FAULT.getOrCreateDetail();
Document doc = detail.getOwnerDocument();
Text tn = doc.createTextNode(DETAIL_TEXT);
detail.appendChild(tn);

Then throw it as you like:

from(routerEndpointURI).setFaultBody(constant(SOAP_FAULT));

If your CXF endpoint is working in the MESSAGE data format, you could set the SOAP Fault message in the message body and set the response code in the message header.

from(routerEndpointURI).process(new Processor() {

   public void process(Exchange exchange) throws Exception {
      Message out = exchange.getOut();
      // Set the message body with the 
      out.setBody(this.getClass().
         getResourceAsStream("SoapFaultMessage.xml"));
      // Set the response code here
      out.setHeader(
         org.apache.cxf.message.Message.RESPONSE_CODE, 
         new Integer(500));
   }
});

Same for using POJO data format. You can set the SOAPFault on the out body and also indicate it is a fault by calling Message.setFault(true):

from("direct:start").onException(SoapFault.class)
   .maximumRedeliveries(0).handled(true)
   .process(new Processor() {
      public void process(Exchange exchange) throws Exception {
         SoapFault fault = exchange
            .getProperty(Exchange.EXCEPTION_CAUGHT, SoapFault.class);
         exchange.getOut().setFault(true);
         exchange.getOut().setBody(fault);
      }
   }
).end().to(SERVICE_URI);

How to propagate a camel-cxf endpoint's request and response context

CXF client API provides a way to invoke the operation with request and response context. If you are using a camel-cxf endpoint producer to invoke the outside web service, you can set the request context and get response context with the following code:

CxfExchange exchange = 
   (CxfExchange)template.send(getJaxwsEndpointUri(), new Processor() {
   public void process(final Exchange exchange) {
      final List<String> params = new ArrayList<String>();
      params.add(TEST_MESSAGE);
      // Set the request context to the inMessage
      Map<String, Object> requestContext = 
         new HashMap<String, Object>();
      requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, 
         JAXWS_SERVER_ADDRESS);
      exchange.getIn().setBody(params);
      exchange.getIn().setHeader(Client.REQUEST_CONTEXT , requestContext);
      exchange.getIn().setHeader(
         CxfConstants.OPERATION_NAME, GREET_ME_OPERATION);
   }
});

org.apache.camel.Message out = exchange.getOut();
// The output is an object array, 
// the first element of the array is the return value
Object\[\] output = out.getBody(Object\[\].class);
LOG.info("Received output text: " + output\[0\]);
// Get the response context form outMessage
Map<String, Object> responseContext = 
   CastUtils.cast((Map)out.getHeader(Client.RESPONSE_CONTEXT));
assertNotNull(responseContext);
assertEquals("Get the wrong wsdl opertion name", 
   "{http://apache.org/hello_world_soap_http}greetMe",
   responseContext.get("javax.xml.ws.wsdl.operation").toString());

Attachment Support

POJO Mode: Both SOAP with Attachment and MTOM are supported (see example in Payload Mode for enabling MTOM). However, SOAP with Attachment is not tested. Since attachments are marshalled and unmarshalled into POJOs, users typically do not need to deal with the attachment themselves. Attachments are propagated to Camel message's attachments since 2.12.3 . So, it is possible to retrieve attachments by Camel Message API

DataHandler Message.getAttachment(String id)

.

Payload Mode: MTOM is supported since 2.1. Attachments can be retrieved by Camel Message APIs mentioned above. SOAP with Attachment (SwA) is supported and attachments can be retrieved since 2.5. SwA is the default (same as setting the CXF endpoint property "mtom-enabled" to false).

To enable MTOM, set the CXF endpoint property "mtom-enabled" to true.

<cxf:cxfEndpoint id="routerEndpoint" 
   address="http://localhost:9091/jaxws-mtom/hello"
   wsdlURL="mtom.wsdl"
   serviceName="ns:HelloService"
   endpointName="ns:HelloPort"
   xmlns:ns="http://apache.org/camel/cxf/mtom_feature">

   <cxf:properties>
      <!--  enable mtom by setting this property to true -->
      <entry key="mtom-enabled" value="true"/>
         
      <!--  set the camel-cxf endpoint data fromat to PAYLOAD mode -->
      <entry key="dataFormat" value="PAYLOAD"/>
   </cxf:properties>

<cxf:cxfEndpoint>        

You can produce a Camel message with attachment to send to a CXF endpoint in Payload mode.

Exchange exchange = context.createProducerTemplate().send(
   "direct:testEndpoint", new Processor() {

   public void process(Exchange exchange) throws Exception {
      exchange.setPattern(ExchangePattern.InOut);
      List<Element> elements = new ArrayList<Element>();
      
      elements.add(DOMUtils.readXml(
         new StringReader(MtomTestHelper.REQ_MESSAGE)).
         getDocumentElement());
      CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(
         new ArrayList<SoapHeader>(),elements);
         
      exchange.getIn().setBody(body);
      exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, 
         new DataHandler(new ByteArrayDataSource(
            MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream")));

      exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, 
         new DataHandler(new ByteArrayDataSource(
            MtomTestHelper.requestJpeg, "image/jpeg")));
   }
});

// process response 

CxfPayload<SoapHeader> out = exchange.getOut().getBody(CxfPayload.class);
Assert.assertEquals(1, out.getBody().size());

Map<String, String> ns = new HashMap<String, String>();
ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS);
ns.put("xop", MtomTestHelper.XOP_NS);

XPathUtils xu = new XPathUtils(ns);
Element ele = (Element)xu.getValue(
   "//ns:DetailResponse/ns:photo/xop:Include", 
   out.getBody().get(0),XPathConstants.NODE);
            
String photoId = ele.getAttribute("href").substring(4); // skip "cid:"

ele = (Element)xu.getValue(
   "//ns:DetailResponse/ns:image/xop:Include", 
   out.getBody().get(0),XPathConstants.NODE);
            
String imageId = ele.getAttribute("href").substring(4); // skip "cid:"

DataHandler dr = exchange.getOut().getAttachment(photoId);
Assert.assertEquals("application/octet-stream", dr.getContentType());
MtomTestHelper.assertEquals(
   MtomTestHelper.RESP_PHOTO_DATA, 
   IOUtils.readBytesFromStream(dr.getInputStream()));
   
dr = exchange.getOut().getAttachment(imageId);
Assert.assertEquals("image/jpeg", dr.getContentType());

BufferedImage image = ImageIO.read(dr.getInputStream());
Assert.assertEquals(560, image.getWidth());
Assert.assertEquals(300, image.getHeight());

You can also consume a Camel message received from a CXF endpoint in Payload mode.

public static class MyProcessor implements Processor {

   @SuppressWarnings("unchecked")
   public void process(Exchange exchange) throws Exception {
      CxfPayload<SoapHeader> in = exchange.getIn().getBody(
         CxfPayload.class);
        
      // verify request
      Assert.assertEquals(1, in.getBody().size());
        
      Map<String, String> ns = new HashMap<String, String>();
      ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS);
      ns.put("xop", MtomTestHelper.XOP_NS);

      XPathUtils xu = new XPathUtils(ns);
      Element ele = (Element)
         xu.getValue("//ns:Detail/ns:photo/xop:Include", 
         in.getBody().get(0),XPathConstants.NODE);
                  
      // skip "cid:"
      String photoId = ele.getAttribute("href").substring(4); 
      Assert.assertEquals(MtomTestHelper.REQ_PHOTO_CID, photoId);

      ele = (Element)xu.getValue("//ns:Detail/ns:image/xop:Include", 
         in.getBody().get(0), XPathConstants.NODE);
                  
      // skip "cid:"
      String imageId = ele.getAttribute("href").substring(4); 
      Assert.assertEquals(MtomTestHelper.REQ_IMAGE_CID, imageId);

      DataHandler dr = exchange.getIn().getAttachment(photoId);
      Assert.assertEquals("application/octet-stream", dr.getContentType());
      MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, 
         IOUtils.readBytesFromStream(dr.getInputStream()));
   
      dr = exchange.getIn().getAttachment(imageId);
      Assert.assertEquals("image/jpeg", dr.getContentType());
      MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, 
         IOUtils.readBytesFromStream(dr.getInputStream()));

        // create response
      List<Element> elements = new ArrayList<Element>();
      elements.add(DOMUtils.readXml(new StringReader(
         MtomTestHelper.RESP_MESSAGE)).getDocumentElement());
      CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(
         new ArrayList<SoapHeader>(),elements);
      exchange.getOut().setBody(body);
      exchange.getOut().addAttachment(MtomTestHelper.RESP_PHOTO_CID, 
         new DataHandler(new ByteArrayDataSource(
         MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

      exchange.getOut().addAttachment(MtomTestHelper.RESP_IMAGE_CID, 
         new DataHandler(new ByteArrayDataSource(
         MtomTestHelper.responseJpeg, "image/jpeg")));
    }
}

Message Mode: Attachments are not supported as it does not process the message at all.