Chapter 78. CXF
CXF Component
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>
If you want to learn about CXF dependencies, see the WHICH-JARS
text file.
When using CXF in streaming modes (see DataFormat option), then also read about Stream caching.
Camel on EAP deployment
This component is supported by the Camel on EAP (Wildfly Camel) framework, which offers a simplified deployment model on the Red Hat JBoss Enterprise Application Platform (JBoss EAP) container.
The CXF component integrates with the JBoss EAP webservices
susbsystem that also uses Apache CXF. For more information, see JAX-WS.
At present, the Camel on EAP subsystem does not support CXF or Restlet consumers. However, it is possible to mimic CXF consumer behaviour, using the CamelProxy
.
URI format
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 |
| No | The location of the WSDL. WSDL is obtained from endpoint address by default. For example:
|
| Yes | The name of the SEI (Service Endpoint Interface) class. This class can have, but does not require, JSR181 annotations. Since 2.0, 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.
Since 2.0, it is possible to use
Please be advised that the referenced object cannot be a Proxy (Spring AOP Proxy is OK) as it relies on Since 2.8, 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.
For example: |
|
Only if more than one |
The service name this service is implementing, it maps to the
|
|
Only if more than one |
The port name this service is implementing, it maps to the
|
| No |
Which message data format the CXF endpoint supports. Possible values are: |
| No |
Please see the Description of |
| No |
Which kind of operation the CXF endpoint producer will invoke. Possible values are: |
| No |
Since 2.5.0 The WSDL style that describes how parameters are represented in the SOAP body. If the value is |
| No |
Deprecated: Specifies whether or not to use the default CXF bus for this endpoint. Possible values are: |
| No |
Deprecated: Specifies whether or not to use the default CXF bus for this endpoint. Possible values are: |
| No |
Use By default, uses the default bus created by CXF Bus Factory. |
| No |
Use |
| No |
Use |
| No |
New in 2.3, this option enables CXF Logging Feature which writes inbound and outbound SOAP messages to log. Possible values are: |
| No |
New in 2.4, this option will set the default
|
| No | New in 2.4, this option will set the default operationNamespace that will be used by the CxfProducer which invokes the remote service. For example:
|
| 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 |
| No |
New in 2.5, this option overrides the endpoint URL that appears in the published WSDL that is accessed using the service address URL plus
|
| No |
Camel 2.8: Allows you to set custom CXF properties in the endpoint URI. For example, setting |
| No | New in 2.8.2. This option controls whether the CXF component, when running in PAYLOAD mode (see below), 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. |
| No | New in 2.11. This option controls whether the PhaseInterceptorChain skips logging the Fault that it catches. |
| No |
New in Camel 2.11. This option could apply the implementation of |
| No | New in Camel 2.12.3 This option is used to set the basic authentication information of username for the CXF client. |
| No | New in Camel 2.12.3 This option is used to set the basic authentication information of password for the CXF client. |
| 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 |
| 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. |
|
|
|
|
|
New in Camel 2.8.2, |
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
.
Configuring the CXF Endpoints with Apache Aries Blueprint.
Since Camel 2.8, there is support for using Aries blueprint dependency injection for your CXF endpoints. The schema is very similar to the Spring schema, so the transition is fairly transparent.
For example:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0" xmlns:camel-cxf="http://camel.apache.org/schema/blueprint/cxf" xmlns:cxfcore="http://cxf.apache.org/blueprint/core" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"> <camel-cxf:cxfEndpoint id="routerEndpoint" address="http://localhost:9001/router" serviceClass="org.apache.servicemix.examples.cxf.HelloWorld"> <camel-cxf:properties> <entry key="dataFormat" value="MESSAGE"/> </camel-cxf:properties> </camel-cxf:cxfEndpoint> <camel-cxf:cxfEndpoint id="serviceEndpoint" address="http://localhost:9000/SoapContext/SoapPort" serviceClass="org.apache.servicemix.examples.cxf.HelloWorld"> </camel-cxf:cxfEndpoint> <camelContext xmlns="http://camel.apache.org/schema/blueprint"> <route> <from uri="routerEndpoint"/> <to uri="log:request"/> </route> </camelContext> </blueprint>
Currently the endpoint element is the first supported CXF namespacehandler.
You can also use the bean references just as in spring
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0" xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws" xmlns:cxf="http://cxf.apache.org/blueprint/core" xmlns:camel="http://camel.apache.org/schema/blueprint" xmlns:camelcxf="http://camel.apache.org/schema/blueprint/cxf" xsi:schemaLocation=" http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/schemas/blueprint/jaxws.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd "> <camelcxf:cxfEndpoint id="reportIncident" address="/camel-example-cxf-blueprint/webservices/incident" wsdlURL="META-INF/wsdl/report_incident.wsdl" serviceClass="org.apache.camel.example.reportincident.ReportIncidentEndpoint"> </camelcxf:cxfEndpoint> <bean id="reportIncidentRoutes" class="org.apache.camel.example.reportincident.ReportIncidentRoutes" /> <camelContext xmlns="http://camel.apache.org/schema/blueprint"> <routeBuilder ref="reportIncidentRoutes"/> </camelContext> </blueprint>
How to enable CXF’s LoggingOutInterceptor in MESSAGE mode
CXF’s LoggingOutInterceptor
outputs outbound message that goes on the wire to 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="target/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.
Available only in POJO mode
The relayHeaders=true
setting 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 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.
You can plugin your own MessageHeadersRelay
implementations overriding or adding additional ones to the list of relays. In order to override a preloaded relay instance just make sure that your MessageHeadersRelay
implementation services the same name spaces as the one you looking to override. Also note, that the overriding relay has to service all of the name spaces as the one you looking to override, or else a runtime exception on route start up will be thrown as this would introduce an ambiguity in name spaces to relay instance mappings.
<cxf:cxfEndpoint ...> <cxf:properties> <entry key="org.apache.camel.cxf.message.headers.relays"> <list> <ref bean="customHeadersRelay"/> </list> </entry> </cxf:properties> </cxf:cxfEndpoint> <bean id="customHeadersRelay" class="org.apache.camel.component.cxf.soap.headers.CustomHeadersRelay"/>
Take a look at the tests that show how you’d be able to relay/drop headers here:
Changes since Release 2.0
-
POJO
andPAYLOAD
modes are supported. InPOJO
mode, only out-of-band message headers are available for filtering as the in-band headers have been processed and removed from the header list by CXF. The in-band headers are incorporated into theMessageContentList
inPOJO
mode. Thecamel-cxf
component does make any attempt to remove the in-band headers from theMessageContentList
If filtering of in-band headers is required, please usePAYLOAD
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
. TherelayHeaders
option, its semantics, and default value remain the same, but it is a property ofCxfHeaderFilterStrategy
. Here is an example of configuring it.<bean id="dropAllMessageHeadersStrategy" class="org.apache.camel.component.cxf.common.header.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 toMessageHeaderFilter
. It is a property ofCxfHeaderFilterStrategy
. Here is an example of configuring user defined Message Header Filters:<bean id="customMessageFilterStrategy" class="org.apache.camel.component.cxf.common.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>
-
Other than
relayHeaders
, there are new properties that can be configured inCxfHeaderFilterStrategy
.
Name | Description | type | Required? | Default value |
| All message headers will be processed by Message Header Filters |
| No |
|
| All message headers will be propagated (without processing by Message Header Filters) |
| No |
|
|
If two filters overlap in activation namespace, the property control how it should be handled. If the value is |
| No |
|
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.
NOTE In Camel 2.x we change to use http://camel.apache.org/schema/cxf
as the CXF endpoint’s target namespace.
<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 "> ...
In Apache Camel 2.x, the http://activemq.apache.org/camel/schema/cxfEndpoint
namespace was changed to http://camel.apache.org/schema/cxf
.
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 |
|
The endpoint name this service is implementing, it maps to the |
|
The service name this service is implementing, it maps to the |
| The location of the WSDL. Can be on the classpath, file system, or be hosted remotely. |
|
The |
| The service publish address. |
| The bus name that will be used in the JAX-WS endpoint. |
| 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 |
|
The incoming interceptors for this endpoint. A list of |
|
The incoming fault interceptors for this endpoint. A list of |
|
The outgoing interceptors for this endpoint. A list of |
|
The outgoing fault interceptors for this endpoint. A list of |
| A properties map which should be supplied to the JAX-WS endpoint. See below. |
| A JAX-WS handler list which should be supplied to the JAX-WS endpoint. See below. |
|
You can specify the which |
|
You can specify the |
|
The features that hold the interceptors for this endpoint. A list of |
|
The schema locations for endpoint to use. A list of |
|
The service factory for this endpoint to use. This can be supplied using the Spring |
You can find more advanced examples which show how to provide interceptors, properties and handlers here: http://cwiki.apache.org/CXF20DOC/jax-ws-configuration.html
You can use CXF:properties to set the CXF endpoint’s dataFormat
and setDefaultBus
properties from a Spring configuration file, as follows:
<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 make the camel-cxf component use log4j instead of java.util.logging
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.
How to let camel-cxf response message with xml start document
If you are using some SOAP client such as PHP, you will get this kind of error, because CXF doesn’t add the XML start document <?xml version="1.0" encoding="utf-8"?>
.
Error:sendSms: SoapFault exception: [Client] looks like we got no XML document in [...]
To resolved this issue, you just need to tell StaxOutInterceptor to write the XML start document for you.
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); } }
You can add a customer interceptor like this and configure it into you camel-cxf
endpont
<cxf:cxfEndpoint id="routerEndpoint" address="http://localhost:${CXFTestSupport.port2}/CXFGreeterRouterTest/CamelContext/RouterPort" serviceClass="org.apache.hello_world_soap_http.GreeterImpl" skipFaultLogging="true"> <cxf:outInterceptors> <!-- This interceptor will force the CXF server send the XML start document to client --> <bean class="org.apache.camel.component.cxf.WriteXmlDeclarationInterceptor"/> </cxf:outInterceptors> <cxf:properties> <!-- Set the publishedEndpointUrl which could override the service address from generated WSDL as you want --> <entry key="publishedEndpointUrl" value="http://www.simple.com/services/test" /> </cxf:properties> </cxf:cxfEndpoint>
Or adding a message header for it like this if you are using Camel 2.4.
// 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.getOut().setHeader(Client.RESPONSE_CONTEXT, map);
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 just 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.
If you don’t specify the operation name in the message header, CxfProducer
will try to use the defaultOperationName
from CxfEndpoint
. If there is no defaultOperationName
set on CxfEndpoint
, it will pick up the first operation name 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 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 an MessageContentsList which first element is the return value of the operation, // If there are some holder parameters, the holder parameter will be filled in the reset of List. // The result will be extract 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
In Apache Camel 2.0: CxfMessage.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 Apache 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<Source> inElements = requestPayload.getBodySources(); List<Source> outElements = new ArrayList<Source>(); // 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); outElements.add(new DOMSource(outDocument.getDocumentElement())); // set the payload header with null CxfPayload<SoapHeader> responsePayload = new CxfPayload<SoapHeader>(null, outElements, null); 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 CXF endpoint produces or consumes Camel exchanges. Even though Apache Camel exposes the message body as POJOs in this mode, the CXF component 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 in POJO mode.
The following example illustrates how to get/set SOAP headers. Suppose we have a route that forwards from one CXF endpoint to another. That is, SOAP Client
<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 Apache Camel Message headers. The Apache 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
are actually 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 { // You should be able to get the header if exchange is routed from camel-cxf endpoint List<SoapHeader> soapHeaders = CastUtils.cast((List<?>)exchange.getIn().getHeader(Header.HEADER_LIST)); if (soapHeaders == null) { // we just create a new soap headers in case the header is null soapHeaders = new ArrayList<SoapHeader>(); } // 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 have already shown how to access SOAP message (CxfPayload
object) in PAYLOAD
mode (see the section called “How to deal with the message for 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() { @SuppressWarnings("unchecked") public void process(Exchange exchange) throws Exception { CxfPayload<SoapHeader> payload = exchange.getIn().getBody(CxfPayload.class); List<Source> elements = payload.getBodySources(); assertNotNull("We should get the elements here", elements); assertEquals("Get the wrong elements size", 1, elements.size()); Element el = new XmlConverter().toDOMElement(elements.get(0)); elements.set(0, new DOMSource(el)); assertEquals("Get the wrong namespace URI", "http://camel.apache.org/pizza/types", el.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());
Since Camel 2.16.0, you can use the same approach as described in the section called “How to get and set SOAP headers in POJO mode” to set or get the SOAP headers. You can now use the org.apache.cxf.headers.Header.list
header to get and set a list of SOAP headers. This means that if you have a route that forwards from one Camel CXF endpoint to another (SOAP Client org.apache.cxf.headers.Header.list
Camel header.
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 Apache Camel
If you are using a 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 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)); } });
The same is true for the POJO data format. You can set the SOAP Fault on the Out body and also indicate it’s a fault by calling Message.setFault(true)
, as follows:
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(serviceURI);
How to propagate a 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 CXF endpoint producer to invoke the external Web service, you can set the request context and get the 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 themself. Attachments are propagated to Camel message’s attachments since 2.1. So, it is possible to retreive 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 is not supported as there is no SOAP processing in this mode.
To enable MTOM, set the CXF endpoint property "mtom_enabled" to true. (I believe you can only do it with Spring.)
<cxf:cxfEndpoint id="routerEndpoint" address="http://localhost:${CXFTestSupport.port1}/CxfMtomRouterPayloadModeTest/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>
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().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 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.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 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 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().getAttachment(photoId); assertEquals("application/octet-stream", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream())); dr = exchange.getIn().getAttachment(imageId); assertEquals("image/jpeg", dr.getContentType()); MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream())); // create response List<Source> elements = new ArrayList<Source>(); elements.add(new DOMSource(DOMUtils.readXml(new StringReader(MtomTestHelper.RESP_MESSAGE)).getDocumentElement())); CxfPayload<SoapHeader> sbody = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null); exchange.getOut().setBody(sbody); 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.
CXF_MESSAGE Mode: MTOM is supported, and Attachments can be retrieved by Camel Message APIs mentioned above. Note that when receiving a multipart (that is, MTOM) message the default SOAPMessage
to String
converter will provide the complete multi-part payload on 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.
How to propagate stack trace information
It is possible to configure a CXF endpoint so that, when a Java exception is thrown on the server side, the stack trace for the exception is marshalled into a fault message and returned to the client. To enable this feaure, set the dataFormat
to PAYLOAD
and set the faultStackTraceEnabled
property to true
in the cxfEndpoint
element, as follows:
<cxf:cxfEndpoint id="router" address="http://localhost:9002/TestMessage"
wsdlURL="ship.wsdl"
endpointName="s:TestSoapEndpoint"
serviceName="s:TestService"
xmlns:s="http://test">
<cxf:properties>
<!-- enable sending the stack trace back to client; the default value is false-->
<entry key="faultStackTraceEnabled" value="true" /> <entry key="dataFormat" value="PAYLOAD" />
</cxf:properties>
</cxf:cxfEndpoint>
For security reasons, the stack trace does not include the causing exception (that is, the part of a stack trace that follows Caused by
). If you want to include the causing exception in the stack trace, set the exceptionMessageCauseEnabled
property to true
in the cxfEndpoint
element, as follows:
<cxf:cxfEndpoint id="router" address="http://localhost:9002/TestMessage"
wsdlURL="ship.wsdl"
endpointName="s:TestSoapEndpoint"
serviceName="s:TestService"
xmlns:s="http://test">
<cxf:properties>
<!-- enable to show the cause exception message and the default value is false -->
<entry key="exceptionMessageCauseEnabled" value="true" />
<!-- enable to send the stack trace back to client, the default value is false-->
<entry key="faultStackTraceEnabled" value="true" />
<entry key="dataFormat" value="PAYLOAD" />
</cxf:properties>
</cxf:cxfEndpoint>
You should only enable the exceptionMessageCauseEnabled
flag for testing and diagnostic purposes. It is normal practice for servers to conceal the original cause of an exception to make it harder for hostile users to probe the server.
Streaming Support in PAYLOAD mode
In 2.8.2, the camel-cxf component now supports streaming of incoming messages when using PAYLOAD mode. Previously, the incoming messages would have been completely DOM parsed. For large messages, this is time consuming and uses a significant amount of memory. Starting in 2.8.2, 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 common "simple proxy" use cases (example: from("cxf:…").to("cxf:…")), this can provide very significant performance increases as well as significantly lowered 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 (like WS-Security or message tracing and such) in which case the advantages of the streaming is limited. At this point, there are two ways to control the streaming:
- Endpoint property: you can add "allowStreaming=false" as an endpoint property to turn the streaming on/off.
- Component property: the CxfComponent object also has an allowStreaming property that can set the default for endpoints created from that component.
- Global system property: you can add a system property of "org.apache.camel.component.cxf.streaming" to "false" to turn if off. That sets the global default, but setting the endpoint property above will override this value for that endpoint.
Using the generic CXF Dispatch mode
From 2.8.0, the camel-cxf component supports the generic CXF dispatch mode that can transport messages of arbitrary structures (i.e., not bound to a specific XML schema). To use this mode, you simply omit specifying the wsdlURL and serviceClass attributes of the CXF endpoint.
<cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/SoapContext/SoapAnyPort"> <cxf:properties> <entry key="dataFormat" value="PAYLOAD"/> </cxf:properties> </cxf:cxfEndpoint>
It is noted that the default CXF dispatch client does not send a specific SOAPAction header. Therefore, when the target service requires a specific SOAPAction value, it is supplied in the Camel header using the key SOAPAction (case-insensitive).
78.1. CXF consumers on WildFly
The configuration of camel-cxf consumers on WildFly is different to that of standalone Camel. Producer endpoints work as per normal.
On WildFly, camel-cxf consumers leverage the default Undertow HTTP server provided by the container. The server is defined within the undertow subsystem configuration. Here’s an excerpt of the default configuration from standalone.xml:
<subsystem xmlns="urn:jboss:domain:undertow:4.0"> <buffer-cache name="default" /> <server name="default-server"> <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true" /> <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true" /> <host name="default-host" alias="localhost"> <location name="/" handler="welcome-content" /> <filter-ref name="server-header" /> <filter-ref name="x-powered-by-header" /> <http-invoker security-realm="ApplicationRealm" /> </host> </server> </subsystem>
In this instance, Undertow is configured to listen on interfaces / ports specified by the http and https socket-binding. By default this is port 8080 for http and 8443 for https.
For example, if you configure an endpoint consumer using different host or port combinations, a warning will appear within the server log file. For example the following host & port configurations would be ignored:
<cxf:rsServer id="cxfRsConsumer" address="http://somehost:1234/path/to/resource" serviceClass="org.example.ServiceClass" />
<cxf:cxfEndpoint id="cxfWsConsumer" address="http://somehost:1234/path/to/resource" serviceClass="org.example.ServiceClass" />
[org.wildfly.extension.camel] (pool-2-thread-1) Ignoring configured host: http://somehost:1234/path/to/resource
However, the consumer is still available on the default host & port localhost:8080 or localhost:8443.
Applications which use camel-cxf consumers must be packaged as a WAR. In previous WildFly-Camel releases, other types of archive such as JAR were permitted, but this is no longer supported.
78.1.1. Configuring alternative ports
If alternative ports are to be accepted, then these must be configured via the WildFly subsystem configuration. This is explained in the server documentation:
78.1.2. Configuring SSL
To configure SSL, refer to the WildFly SSL configuration guide:
78.1.3. Configuring security with Elytron
WildFly-Camel supports securing camel-cxf consumer endpoints with the Elytron security framework.
78.1.3.1. Configuring a security domain
To secure a WildFly-Camel application with Elytron, an application security domain needs to be referenced within WEB-INF/jboss-web.xml
of your WAR deployment:
<jboss-web> <security-domain>my-application-security-domain</security-domain> </jboss-web>
The <security-domain>
configuration references the name of an <application-security-domain>
defined by the Undertow subsystem. For example, the Undertow subsystem <application-security-domain>
is configured within the WildFly server standalone.xml
configuration file as follows:
<subsystem xmlns="urn:jboss:domain:undertow:6.0"> ... <application-security-domains> <application-security-domain name="my-application-security-domain" http-authentication-factory="application-http-authentication"/> </application-security-domains> </subsystem>
The <http-authentication-factory>
application-http-authentication
is defined within the Elytron subsystem. application-http-authentication
is available by default in both the standalone.xml
and standalone-full.xml
server configuration files. For example:
<subsystem xmlns="urn:wildfly:elytron:1.2"> ... <http> ... <http-authentication-factory name="application-http-authentication" http-server-mechanism-factory="global" security-domain="ApplicationDomain"> <mechanism-configuration> <mechanism mechanism-name="BASIC"> <mechanism-realm realm-name="Application Realm" /> </mechanism> <mechanism mechanism-name="FORM" /> </mechanism-configuration> </http-authentication-factory> <provider-http-server-mechanism-factory name="global" /> </http> ... </subsystem>
The <http-authentication-factory>
named application-http-authentication
, holds a reference to a Elytron security domain called ApplicationDomain
.
For more information on how to configure the Elytron subsystem, refer to the Elytron documentation.
78.1.3.2. Configuring security constraints, authentication methods and security roles
Security constraints, authentication methods and security roles for camel-cxf consumer endpoints can be configured within your WAR deployment WEB-INF/web.xml
. For example, to configure BASIC Authentication:
<web-app> <security-constraint> <web-resource-collection> <web-resource-name>secure</web-resource-name> <url-pattern>/webservices/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>my-role</role-name> </auth-constraint> </security-constraint> <security-role> <description>The role that is required to log in to /webservices/*</description> <role-name>my-role</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> <realm-name>my-realm</realm-name> </login-config> </web-app>
Note that the <url-pattern>
defined by the Servlet Specification is relative to the context path of the web application. If your application is packaged as my-app.war
, WildFly will make it accessible under the context path /my-app
and the <url-patternpattern>
/webservices/*
will be applied to paths relative to /my-app
.
For example, requests against http://my-server/my-app/webservices/my-endpoint
will match the /webservices/*
pattern, while http://my-server/webservices/my-endpoint
will not match.
This is important because WildFly-Camel allows the creation of camel-cxf endpoint consumers whose base path is outside of the host web application context path. For example, it is possible to create a camel-cxf consumer for http://my-server/webservices/my-endpoint
inside my-app.war
.
In order to define security constraints for such out-of-context endpoints, WildFly-Camel supports a custom, non-standard <url-pattern>
convention where prefixing the pattern with three forward slashes ///
will be interpreted as absolute to server host name. For example, to secure http://my-server/webservices/my-endpoint
inside my-app.war
, you would add the following configuration to web.xml
:
<web-app> <security-constraint> <web-resource-collection> <web-resource-name>secure</web-resource-name> <url-pattern>///webservices/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>my-role</role-name> </auth-constraint> </security-constraint> <security-role> <description>The role that is required to log in to /webservices/*</description> <role-name>my-role</role-name> </security-role> <login-config> <auth-method>BASIC</auth-method> <realm-name>my-realm</realm-name> </login-config> </web-app>