CXF

Since Camel 1.0

Both producer and consumer are supported

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

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

pom.xml:
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-cxf-soap</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

There are two URI formats for this endpoint: cxfEndpoint and someAddress.

cxfEndpoint

cxf:bean:cxfEndpoint[?options]

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

someAddress

cxf://someAddress[?options]

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

URI Options

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

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

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

The component level is the highest level which holds general and common configurations that are inherited by the endpoints. For example a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

Configuring components can be done with the Component DSL, in a configuration file (application.properties|yaml), or directly with Java code.

Configuring Endpoint Options

Where you find yourself configuring the most is on endpoints, as endpoints often have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL as a type safe way of configuring endpoints.

A good practice when configuring options is to use Property Placeholders, which allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse.

The following two sections lists all the options, firstly for the component followed by the endpoint.

Component Options

The CXF component supports 6 options, which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

allowStreaming (advanced)

This option controls whether the CXF component, when running in PAYLOAD mode, will DOM 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.

Boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

Endpoint Options

The CXF endpoint is configured using URI syntax:

cxf:beanId:address

with the following path and query parameters:

Path Parameters (2 parameters)

Name Description Default Type

beanId (common)

To lookup an existing configured CxfEndpoint. Must used bean: as prefix.

String

address (service)

The service publish address.

String

Query Parameters (36 parameters)

Name Description Default Type

dataFormat (common)

The data type messages supported by the CXF endpoint.

Enum values:

  • PAYLOAD

  • RAW

  • MESSAGE

  • CXF_MESSAGE

  • POJO

POJO

DataFormat

wrappedStyle (common)

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.

Boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

  • InOptionalOut

ExchangePattern

cookieHandler (producer)

Configure a cookie handler to maintain a HTTP session.

CookieHandler

defaultOperationName (producer)

This option will set the default operationName that will be used by the CxfProducer which invokes the remote service.

String

defaultOperationNamespace (producer)

This option will set the default operationNamespace that will be used by the CxfProducer which invokes the remote service.

String

hostnameVerifier (producer)

The hostname verifier to be used. Use the # notation to reference a HostnameVerifier from the registry.

HostnameVerifier

sslContextParameters (producer)

The Camel SSL setting reference. Use the # notation to reference the SSL Context.

SSLContextParameters

wrapped (producer)

Which kind of operation that CXF endpoint producer will invoke.

false

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

synchronous (producer (advanced))

Sets whether synchronous processing should be strictly used.

false

boolean

allowStreaming (advanced)

This option controls whether the CXF component, when running in PAYLOAD mode, will DOM 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.

Boolean

bus (advanced)

To use a custom configured CXF Bus.

Bus

continuationTimeout (advanced)

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.

30000

long

cxfBinding (advanced)

To use a custom CxfBinding to control the binding between Camel Message and CXF Message.

CxfBinding

cxfConfigurer (advanced)

This option could apply the implementation of org.apache.camel.component.cxf.CxfEndpointConfigurer which supports to configure the CXF endpoint in programmatic way. User can configure the CXF server and client by implementing configure{ServerClient} method of CxfEndpointConfigurer.

CxfConfigurer

defaultBus (advanced)

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

false

boolean

headerFilterStrategy (advanced)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

mergeProtocolHeaders (advanced)

Whether to merge protocol headers. If enabled then propagating headers between Camel and CXF becomes more consistent and similar. For more details see CAMEL-6393.

false

boolean

mtomEnabled (advanced)

To enable MTOM (attachments). This requires to use POJO or PAYLOAD data format mode.

false

boolean

properties (advanced)

To set additional CXF options using the key/value pairs from the Map. For example to turn on stacktraces in SOAP faults, properties.faultStackTraceEnabled=true.

Map

schemaValidationEnabled (advanced)

Enable schema validation for request and response. Disabled by default for performance reason.

false

Boolean

skipPayloadMessagePartCheck (advanced)

Sets whether SOAP message validation should be disabled.

false

boolean

loggingFeatureEnabled (logging)

This option enables CXF Logging Feature which writes inbound and outbound SOAP messages to log.

false

boolean

loggingSizeLimit (logging)

To limit the total size of number of bytes the logger will output when logging feature has been enabled and -1 for no limit.

49152

int

skipFaultLogging (logging)

This option controls whether the PhaseInterceptorChain skips logging the Fault that it catches.

false

boolean

password (security)

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

String

username (security)

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

String

bindingId (service)

The bindingId for the service model to use.

String

portName (service)

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

String

publishedEndpointUrl (service)

This option can override the endpointUrl that published from the WSDL which can be accessed with service address url plus wsd.

String

serviceClass (service)

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

Class

serviceName (service)

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

String

wsdlURL (service)

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

String

Message Headers

The CXF component supports 6 message header(s), which is/are listed below:

Name Description Default Type

operationName (common)

Constant: OPERATION_NAME

The name of the operation.

String

operationNamespace (common)

Constant: OPERATION_NAMESPACE

The operation namespace.

String

CamelDestinationOverrideUrl (common)

Constant: DESTINATION_OVERRIDE_URL

The destination override url.

String

ResponseContext (common)

Constant: RESPONSE_CONTEXT

The response context.

Map

CamelAuthentication (common)

Constant: AUTHENTICATION

The authentication.

Subject

RequestContext (common)

Constant: REQUEST_CONTEXT

The request context.

Object

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.

Descriptions of the dataformats

In Apache Camel, the Camel CXF component is the key to integrating routes with Web services. You can use the Camel CXF component to create a CXF endpoint, which can be used in either of the following ways:

  • Consumer — (at the start of a route) represents a Web service instance, which integrates with the route. The type of payload injected into the route depends on the value of the endpoint’s dataFormat option.

  • Producer — (at other points in the route) represents a WS client proxy, which converts the current exchange object into an operation invocation on a remote Web service. The format of the current exchange must match the endpoint’s dataFormat setting.

DataFormat Description Support

POJO

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

The message payload (the contents of the soap:body) after message configuration in the CXF endpoint is applied.

Only Protocol JAX-WS handler is supported. Logical JAX-WS handler is not supported.

RAW

Provides the raw message stream that is received from the transport layer. It is not possible to touch or change the stream, some of the CXF interceptors are removed if you are using this kind of DataFormat, so you can’t see any soap headers after the camel-cxf consumer.

JAX-WS handler is not supported. Note that RAW mode is equivalent to deprecated MESSAGE mode.

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.common.message.CxfConstants.DATA_FORMAT_PROPERTY.

Creating a simple CXF service with POJO data format

If you have a simple java web service interface and an implementation, you can create a simple CXF service.

Java web service interface:
package org.apache.camel.component.cxf.soap.server;

@WebService(targetNamespace = "http://server.soap.cxf.component.camel.apache.org/", name = "EchoService")
public interface EchoService {

    String echo(String text);
}
Implementation:
package org.apache.camel.component.cxf.soap.server;

@WebService(name = "EchoService", serviceName = "EchoService", targetNamespace = "http://server.soap.cxf.component.camel.apache.org/")
public class EchoServiceImpl implements EchoService {

    @Override
    public String echo(String text) {
        return text;
    }

}

POJO mode is the default, so you do not have to specify it.

Simple CXF service
    from("cxf:echoServiceResponseFromImpl?serviceClass=org.apache.camel.component.cxf.soap.server.EchoServiceImpl&address=/echo-impl")// no body set here; the response comes from EchoServiceImpl
                .log("${body}");

In a more complicated implementation of the service, you can set the body from the route instead:

CXF service with body set from route
    from("cxf:echoServiceResponseFromRoute?serviceClass=org.apache.camel.component.cxf.soap.server.EchoServiceImpl&address=/echo-route")
                .setBody(exchange -> exchange.getMessage().getBody(String.class) + " from Camel route");

Consuming 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 Logger LOG = LoggerFactory.getLogger(PersonProcessor.class);

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

        BindingOperationInfo boi = (BindingOperationInfo) exchange.getProperty(BindingOperationInfo.class.getName());
        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);
            exchange.getMessage().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.getMessage().setBody(new Object[] { null, personId, ssn, name });
    }

}

Preparing the message for the camel-cxf endpoint in POJO data format

The camel-cxf endpoint producer is based on the CXF client API.

To prepare the message:

  1. Specify the operation name in the message header.

  2. Add the method parameters to a list.

  3. Initialize the message with this parameter list.

The response message’s body is a messageContentsList, so you can get the result from that list.

  • If you do not specify the operation name in the message header, CxfProducer tries to use the defaultOperationName from CxfEndpoint.

  • If there is no defaultOperationName set on CxfEndpoint, it will pick up the first operationName from the Operation list.

  • If you want to get the object array from the message body, you can get the body using message.getBody(Object[].class), as shown here:

    Exchange senderExchange = new DefaultExchange(context, ExchangePattern.InOut);
    final List<String> params = new ArrayList<>();
    // 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.getMessage();
    // The response message's body is an MessageContentsList which first element is the return value of the operation,
    // If there are some holder parameters, the holder parameter is filled in the reset of List.
    // The result is 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("UTF-8", responseContext.get(org.apache.cxf.message.Message.ENCODING),
            "We should get the response context here");
    assertEquals("echo " + TEST_MESSAGE, result.get(0), "Reply body on Camel is wrong");

Consuming a message from a camel-cxf endpoint in PAYLOAD data format

PAYLOAD means that you process the payload from the SOAP envelope as a native CxfPayload. Message.getBody() will return a org.apache.camel.component.cxf.CxfPayload object, with getters for SOAP message headers and the SOAP body.

protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {
        public void configure() {
            from(simpleEndpointURI + "&dataFormat=PAYLOAD").to("log:info").process(new Processor() {
                public void process(final Exchange exchange) throws Exception {
                    CxfPayload<SoapHeader> requestPayload = exchange.getIn().getBody(CxfPayload.class);
                    List<Source> inElements = requestPayload.getBodySources();
                    List<Source> outElements = new ArrayList<>();
                    // 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 documentString = ECHO_RESPONSE;

                    Element in = new XmlConverter().toDOMElement(inElements.get(0));
                    // Just check the element namespace
                    if (!in.getNamespaceURI().equals(ELEMENT_NAMESPACE)) {
                        throw new IllegalArgumentException("Wrong element namespace");
                    }
                    if (in.getLocalName().equals("echoBoolean")) {
                        documentString = ECHO_BOOLEAN_RESPONSE;
                        checkRequest("ECHO_BOOLEAN_REQUEST", request);
                    } else {
                        documentString = ECHO_RESPONSE;
                        checkRequest("ECHO_REQUEST", request);
                    }
                    Document outDocument = converter.toDOMDocument(documentString, exchange);
                    outElements.add(new DOMSource(outDocument.getDocumentElement()));
                    // set the payload header with null
                    CxfPayload<SoapHeader> responsePayload = new CxfPayload<>(null, outElements, null);
                    exchange.getMessage().setBody(responsePayload);
                }
            });
        }
    };
}

Getting and setting 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 exposes the 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 the header list after they have been processed, only out-of-band SOAP headers are available to camel-cxf in POJO mode.

The following example illustrates how to get and set SOAP headers. If you have a route that forwards from one camel-cxf endpoint to another, such as SOAP Client → Camel → CXF service, you can attach two processors to obtain/insert SOAP headers:

  1. Before a request goes out to the CXF service.

  2. Before the response comes back to the SOAP Client.

Processor (1) and (2) in this example are InsertRequestOutHeaderProcessor and InsertResponseOutHeaderProcessor:

Route for SOAP headers
  • Java

  • XML

from("cxf:bean:routerRelayEndpointWithInsertion")
    .process(new InsertRequestOutHeaderProcessor())
    .to("cxf:bean:serviceRelayEndpointWithInsertion")
    .process(new InsertResponseOutHeaderProcessor());
<route>
    <from uri="cxf:bean:routerRelayEndpointWithInsertion"/> (1)
    <process ref="InsertRequestOutHeaderProcessor" />
    <to uri="cxf:bean:serviceRelayEndpointWithInsertion"/> (2)
    <process ref="InsertResponseOutHeaderProcessor" />
</route>

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

You can access SOAP headers in the same way in both InsertResponseOutHeaderProcessor and InsertRequestOutHeaderProcessor. The only difference between the two processors is the direction of the inserted SOAP header.

The following snippet is the InsertResponseOutHeaderProcessor (that inserts a new SOAP header in the response message) example:

public static class InsertResponseOutHeaderProcessor implements Processor {

    public void process(Exchange exchange) throws Exception {
        List<SoapHeader> soapHeaders = CastUtils.cast((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());
        // ensure the direction is OUT since it is a response message.
        newHeader.setDirection(Direction.DIRECTION_OUT);
        //newHeader.setMustUnderstand(false);
        soapHeaders.add(newHeader);

    }

}

Getting and setting SOAP headers in PAYLOAD mode

You can see how to access the SOAP message as a CxfPayload object in PAYLOAD mode in the section Consuming a message from a camel-cxf endpoint in PAYLOAD data format.

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() {
    public void process(Exchange exchange) throws Exception {
        CxfPayload<SoapHeader> payload = exchange.getIn().getBody(CxfPayload.class);
        List<Source> elements = payload.getBodySources();
        assertNotNull(elements, "We should get the elements here");
        assertEquals(1, elements.size(), "Get the wrong elements size");

        Element el = new XmlConverter().toDOMElement(elements.get(0));
        elements.set(0, new DOMSource(el));
        assertEquals("http://camel.apache.org/pizza/types",
                el.getNamespaceURI(), "Get the wrong namespace URI");

        List<SoapHeader> headers = payload.getHeaders();
        assertNotNull(headers, "We should get the headers here");
        assertEquals(1, headers.size(), "Get the wrong headers size");
        assertEquals("http://camel.apache.org/pizza/types",
                ((Element) (headers.get(0).getObject())).getNamespaceURI(), "Get the wrong namespace URI");
        // alternatively you can also get the SOAP header via the camel header:
        headers = exchange.getIn().getHeader(Header.HEADER_LIST, List.class);
        assertNotNull(headers, "We should get the headers here");
        assertEquals(1, headers.size(), "Get the wrong headers size");
        assertEquals("http://camel.apache.org/pizza/types",
                ((Element) (headers.get(0).getObject())).getNamespaceURI(), "Get the wrong namespace URI");

    }

})
.to(getServiceEndpointURI());

You can also use the method described in the section Getting and setting SOAP headers in PAYLOAD mode to set or get the SOAP headers.

You can use the header org.apache.cxf.headers.Header.list to get and set a list of SOAP headers. This does also mean that if you have a route that forwards from one camel-cxf endpoint to another (SOAP Client → Camel → CXF service), now also the SOAP headers sent by the SOAP client are forwarded to the CXF service.

If you do not want to forward the headers you have to remove them in the Camel header org.apache.cxf.headers.Header.list.

SOAP headers are not available in RAW mode

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

Throwing 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. You can use the throwFault DSL to do that; it works for POJO, PAYLOAD and RAW data format.

You can define the soap fault as shown here:

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

You can define the SOAP fault as shown here:

Throwing the SOAP fault:
from(routerEndpointURI).setFaultBody(constant(SOAP_FAULT));

If your CXF endpoint is working in the RAW data format, you can set the SOAP Fault message in the message body and set the response code in the message header as demonstrated here:

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

    public void process(Exchange exchange) throws Exception {
        Message out = exchange.getMessage();
        // 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));
    }

});

In the POJO data format you can set the SOAPFault on the out body.

Propagating a camel-cxf endpoint’s request and response context

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

Setting the request context and getting the response context:
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.getMessage();
// 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 operation name", "{http://apache.org/hello_world_soap_http}greetMe",
    responseContext.get("javax.xml.ws.wsdl.operation").toString());

Attachment Support

POJO Mode

In POJO Mode, Message Transmission Optimization Mechanism (MTOM) is supported if it is enabled. See Setting the CXF endpoint property: in Payload Mode.

DataHandler Exchange.getIn(AttachmentMessage.class).getAttachment(String id)

Payload Mode

In Payload Mode, Message Transmission Optimization Mechanism (MTOM) is supported. Attachments can be retrieved through the Camel Message API. SOAP with Attachment (SwA) is supported and attachments can be retrieved. SwA is the default, as the default setting for CXF endpoint property mtom-enabled is false.

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

Setting the CXF endpoint property:
  • Java (Quarkus)

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.cxf.common.DataFormat;
import org.apache.camel.component.cxf.jaxws.CxfEndpoint;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.SessionScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Named;

@ApplicationScoped
public class CxfSoapMtomRoutes extends RouteBuilder {

    @Override
    public void configure() {
        from("cxf:bean:mtomPayloadModeEndpoint")
                .process( exchange -> { ... });
    }

    @Produces
    @SessionScoped
    @Named
    CxfEndpoint mtomPayloadModeEndpoint() {
        final CxfEndpoint result = new CxfEndpoint();
        result.setServiceClass(MyMtomService.class);
        result.setDataFormat(DataFormat.PAYLOAD);
        result.setMtomEnabled(true);
        result.setAddress("/mtom/hello");
        return result;
    }
}
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<Source> elements = new ArrayList<Source>();
        elements.add(new DOMSource(DOMUtils.readXml(new StringReader(MtomTestHelper.REQ_MESSAGE)).getDocumentElement()));
        CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(),
            elements, null);
        exchange.getIn().setBody(body);
        exchange.getIn(AttachmentMessage.class).addAttachment(MtomTestHelper.REQ_PHOTO_CID,
            new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream")));

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

    }

});

// process response

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

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

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

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

DataHandler dr = exchange.getMessage(AttachmentMessage.class).getAttachment(decodingReference(photoId));
assertEquals("application/octet-stream", dr.getContentType());
assertArrayEquals(MtomTestHelper.RESP_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));

dr = exchange.getMessage(AttachmentMessage.class).getAttachment(decodingReference(imageId));
assertEquals("image/jpeg", dr.getContentType());

BufferedImage image = ImageIO.read(dr.getInputStream());
assertEquals(560, image.getWidth());
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 {

    @Override
    public void process(Exchange exchange) throws Exception {
        CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class);

        // verify request
        assertEquals(1, in.getBody().size());

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

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

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

        DataHandler dr = exchange.getIn(AttachmentMessage.class).getAttachment(photoId);
        assertEquals("application/octet-stream", dr.getContentType());
        assertArrayEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));

        dr = exchange.getIn(AttachmentMessage.class).getAttachment(imageId);
        assertEquals("image/jpeg", dr.getContentType());
        assertArrayEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream()));

        // create response
        List<Source> elements = new ArrayList<>();
        elements.add(new DOMSource(StaxUtils.read(new StringReader(MtomTestHelper.RESP_MESSAGE)).getDocumentElement()));
        CxfPayload<SoapHeader> sbody = new CxfPayload<>(
                new ArrayList<SoapHeader>(),
                elements, null);
        exchange.getMessage().setBody(sbody);
        exchange.getMessage(AttachmentMessage.class).addAttachment(MtomTestHelper.RESP_PHOTO_CID,
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

        exchange.getMessage(AttachmentMessage.class).addAttachment(MtomTestHelper.RESP_IMAGE_CID,
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg")));

    }
}

RAW Mode

In RAW Mode, attachments are not supported as it does not process the message at all.

CXF_MESSAGE Mode

In CXF_MESSAGE Mode, MTOM is supported, and Attachments can be retrieved by Camel Message APIs (see [retrieve-attachments-camel-message-api]). Note that when receiving a multipart that is, a MTOM message, the default SOAPMessage to String converter will provide the complete multipart payload in the body. If you require just the SOAP XML as a String, you can set the message body with message.getSOAPPart(), and Camel convert can do the rest of work for you.

Streaming Support in PAYLOAD mode

The camel-cxf component supports streaming of incoming messages when using PAYLOAD mode.

The incoming messages can remain as a javax.xml.transform.Source while being routed and, if nothing modifies the payload, can then be directly streamed out to the target destination.

For a simple proxy (such as from("cxf:…​").to("cxf:…​")), this provides significant improvements in performance and memory requirements.

However, there are cases where streaming may not be appropriate or desired. Due to the streaming nature, invalid incoming XML may not be caught until later in the processing chain. Also, certain actions may require the message to be DOM parsed anyway (for example WS-Security or message tracing) in which case the advantages of the streaming is limited.

Controlling streaming in PAYLOAD mode

You can control the streaming in several ways:

  • Endpoint property: you can add allowStreaming=false as an endpoint property to turn the streaming on or off.

  • Component property: the CxfComponent object has an allowStreaming property that can set the default for endpoints created from that component.

  • Global system property: you can add a system property to org.apache.camel.component.cxf.streaming to false to turn it off. That sets the global default, but the endpoint property will override this value (for that endpoint only).

Parsing incoming messages with DOM can require a lot of memory and time for large messages.

Using the generic CXF Dispatch mode

The camel-cxf component supports the generic CXF dispatch mode that can transport messages of arbitrary structures (that is not bound to a specific XML schema). To use this mode, you simply omit specifying the wsdlURL and serviceClass attributes of the CXF endpoint.

Endpoint in PAYLOAD mode:
<cxf:cxfEndpoint id="dispatchEndpoint" address="http://localhost:9000/SoapContext/SoapAnyPort">
    <cxf:properties>
        <entry key="dataFormat" value="PAYLOAD"/>
    </cxf:properties>
</cxf:cxfEndpoint>

The default CXF dispatch client does not send a specific SOAPAction header. Therefore, when the target service requires a specific SOAPAction value, you supply it in the Camel header using the key SOAPAction (case-insensitive).

Enabling CXF’s LoggingOutInterceptor in RAW mode

CXF’s LoggingOutInterceptor outputs an outbound message that goes on the wire to logging system (Java Util Logging).

Since the LoggingOutInterceptor is in PRE_STREAM phase, and the PRE_STREAM phase is removed in RAW mode, you have to configure LoggingOutInterceptor to be run during the WRITE phase:

LoggingOutInterceptor in RAW mode:
  • Java (Quarkus)

import java.util.List;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.cxf.common.DataFormat;
import org.apache.camel.component.cxf.jaxws.CxfEndpoint;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.phase.Phase;
import jakarta.enterprise.context.SessionScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Named;

...

@Produces
@SessionScoped
@Named
CxfEndpoint soapMtomEnabledServerPayloadModeEndpoint() {
    final CxfEndpoint result = new CxfEndpoint();
    result.setServiceClass(HelloService.class);
    result.setDataFormat(DataFormat.RAW);
    result.setOutFaultInterceptors(List.of(new LoggingOutInterceptor(Phase.WRITE)));;
    result.setAddress("/helloworld");
    return result;
}

The CxfHeaderFilterStrategy options

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

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, a CxfHeaderFilterStrategy instance should be set on the CXF endpoint, then relayHeaders property of the CxfHeaderFilterStrategy instance should be set to true, which is the default value. Plus, the CxfHeaderFilterStrategy instance also holds a list of MessageHeaderFilter interface, which decides if a specific header will be relayed or not.

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

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

Headers relaying/filtering is bi-directional.

When a route has a CXF endpoint, and you need on-the-wire headers (such as SOAP headers) relayed along the route to be consumed by for example another JAXWS endpoint, you must set relayHeaders to true, the default value.

You can find tests that show how you can relay/drop headers here:

  • CxfMessageHeadersRelayTest

  • The relayHeaders=true expresses an intent to relay the headers. The actual decision on whether a given header is relayed is delegated to a pluggable instance that implements the MessageHeaderFilter interface. A concrete implementation of MessageHeaderFilter will be consulted to decide if a header needs to be relayed or not. There is already an implementation of SoapMessageHeaderFilter which binds itself to well-known SOAP name spaces. If there is a header on the wire whose name space is unknown to the runtime, the header will simply be relayed.

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.

The camel-cxf component does not make any attempt to remove the in-band headers from the MessageContentList. If you require filtering of in-band headers, use PAYLOAD mode or plug in a CXF interceptor/JAXWS Handler to the CXF endpoint.

The Message Header Relay mechanism in POJO mode

The Message Header Relay mechanism is part of the CxfHeaderFilterStrategy and is a property of CxfHeaderFilterStrategy.

Here is an example of how you can configure it:

CxfHeaderFilterStrategy configuration:
<bean id="dropAllMessageHeadersStrategy" class="org.apache.camel.component.cxf.transport.header.CxfHeaderFilterStrategy">

    <!--  Set relayHeaders to false to drop all SOAP headers -->
    <property name="relayHeaders" value="false"/>

</bean>

When you have configured the strategy, you can reference the CxfHeaderFilterStrategy in your endpoint.

Referencing the CxfHeaderFilterStrategy:
<route>
    <from uri="cxf:bean:routerNoRelayEndpoint?headerFilterStrategy=#dropAllMessageHeadersStrategy"/>
    <to uri="cxf:bean:serviceNoRelayEndpoint?headerFilterStrategy=#dropAllMessageHeadersStrategy"/>
</route>
  • You can plug in your own MessageHeaderFilter implementations overriding or adding additional ones to the list of relays. In order to override a preloaded relay instance just make sure that your MessageHeaderFilter implementation services the same name spaces as the one you want to override.

Here is an example of configuring user-defined Message Header Filters:

Message Header Filters configuration:
<bean id="customMessageFilterStrategy" class="org.apache.camel.component.cxf.transport.header.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.common.header.SoapMessageHeaderFilter"/>

            <!--  Add custom filter here -->
            <bean class="org.apache.camel.component.cxf.soap.headers.CustomHeaderFilter"/>
        </list>
    </property>
</bean>

In addition to relayHeaders, you can configure the following properties in CxfHeaderFilterStrategy.

Name Required Description Type Default

relayHeaders

No

All message headers are processed by Message Header Filters.

boolean

true

relayAllMessageHeaders

No

All message headers are propagated (without processing by Message Header Filters).

boolean

false

allowFilterNamespaceClash

No

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

false

Making the camel-cxf component use log4j instead of java.util.logging

CXF’s default logger is java.util.logging.

To change the default logger to log4j, proceed as follows:

  1. Create a file in the classpath, named META-INF/cxf/org.apache.cxf.logger

  2. Add a single line, with no comments, with the fully-qualified name of the class (org.apache.cxf.common.logging.Log4jLogger).

Letting camel-cxf response start with xml processing instruction

CXF does not add the XML processing instruction <?xml version="1.0" encoding="utf-8"?>. This can cause this type of error for some SOAP clients (for example PHP):

Error:sendSms: SoapFault exception: [Client] looks like we got no XML document in [...]

To resolve this issue, you must tell StaxOutInterceptor to write the XML start document for you, as in this example:

public class WriteXmlDeclarationInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    public WriteXmlDeclarationInterceptor() {
        super(Phase.PRE_STREAM);
        addBefore(StaxOutInterceptor.class.getName());
    }

    public void handleMessage(SoapMessage message) throws Fault {
        message.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE);
    }

}

As an alternative you can add a message header for it as demonstrated here:

 // set up the response context which force start document
 Map<String, Object> map = new HashMap<String, Object>();
 map.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE);
 exchange.getMessage().setHeader(Client.RESPONSE_CONTEXT, map);

Configuring the data format

You can use cxf:properties in the configuration file to set the dataFormat for the camel-cxf endpoint and the setDefaultBus properties.

Configuration options:
  • Java (Quarkus)

import org.apache.camel.component.cxf.common.DataFormat;
import org.apache.camel.component.cxf.jaxws.CxfEndpoint;
import jakarta.enterprise.context.SessionScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Named;

...

@Produces
@SessionScoped
@Named
CxfEndpoint testEndpoint() {
    final CxfEndpoint result = new CxfEndpoint();
    result.setServiceClass(HelloService.class);
    result.setDataFormat(DataFormat.RAW);
    result.setDefaultBus(true);
    result.setAddress("/hello");
    return result;
}