Apache CXF Development Guide
Develop applications with Apache CXF Web services
Copyright © 2011-2015 Red Hat, Inc. and/or its affiliates.
Abstract
Part I. Writing WSDL Contracts
Abstract
Chapter 1. Introducing WSDL Contracts
Abstract
1.1. Structure of a WSDL document
Overview
definition
element. These elements describe a service and how an endpoint implementing that service is accessed.
- A logical part that defines the service in implementation neutral terms
- A concrete part that defines how an endpoint implementing the service is exposed on a network
The logical part
types
, the message
, and the portType
elements. It describes the service’s interface and the messages exchanged by the service. Within the types
element, XML Schema is used to define the structure of the data that makes up the messages. A number of message
elements are used to define the structure of the messages used by the service. The portType
element contains one or more operation
elements that define the messages sent by the operations exposed by the service.
The concrete part
binding
and the service
elements. It describes how an endpoint that implements the service connects to the outside world. The binding
elements describe how the data units described by the message
elements are mapped into a concrete, on-the-wire data format, such as SOAP. The service
elements contain one or more port
elements which define the endpoints implementing the service.
1.2. WSDL elements
definitions
— The root element of a WSDL document. The attributes of this element specify the name of the WSDL document, the document’s target namespace, and the shorthand definitions for the namespaces referenced in the WSDL document.types
— The XML Schema definitions for the data units that form the building blocks of the messages used by a service. For information about defining data types see Chapter 2, Defining Logical Data Units.message
— The description of the messages exchanged during invocation of a services operations. These elements define the arguments of the operations making up your service. For information on defining messages see Chapter 3, Defining Logical Messages Used by a Service.portType
— A collection ofoperation
elements describing the logical interface of a service. For information about defining port types see Chapter 4, Defining Your Logical Interfaces.operation
— The description of an action performed by a service. Operations are defined by the messages passed between two endpoints when the operation is invoked. For information on defining operations see the section called “Operations”.binding
— The concrete data format specification for an endpoint. Abinding
element defines how the abstract messages are mapped into the concrete data format used by an endpoint. This element is where specifics such as parameter order and return values are specified.service
— A collection of relatedport
elements. These elements are repositories for organizing endpoint definitions.port
— The endpoint defined by a binding and a physical address. These elements bring all of the abstract definitions together, combined with the definition of transport details, and they define the physical endpoint on which a service is exposed.
1.3. Designing a contract
- Define the data types used by your services.
- Define the messages used by your services.
- Define the interfaces for your services.
- Define the bindings between the messages used by each interface and the concrete representation of the data on the wire.
- Define the transport details for each of the services.
Chapter 2. Defining Logical Data Units
Abstract
2.1. Introduction to Logical Data Units
- Breaking the data into logical units that can be mapped into the data types used by the physical implementations of the service
- Combining the logical units into messages that are passed between endpoints to carry out the operations
2.2. Mapping data into logical data units
Overview
Available type systems for defining service data units
XML Schema as a type system
Considerations for creating your data units
- Use elements, not attributes.
- Do not use protocol-specific types as base types.
2.3. Adding data units to a contract
Overview
Procedure
- Determine all the data units used in the interface described by the contract.
- Create a
types
element in your contract. - Create a
schema
element, shown in Example 2.1, “Schema entry for a WSDL contract”, as a child of thetype
element.ThetargetNamespace
attribute specifies the namespace under which new data types are defined. The remaining entries should not be changed.Example 2.1. Schema entry for a WSDL contract
<schema targetNamespace="http://schemas.iona.com/bank.idl" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
- For each complex type that is a collection of elements, define the data type using a
complexType
element. See Section 2.5.1, “Defining data structures”. - For each array, define the data type using a
complexType
element. See Section 2.5.2, “Defining arrays”. - For each complex type that is derived from a simple type, define the data type using a
simpleType
element. See Section 2.5.4, “Defining types by restriction”. - For each enumerated type, define the data type using a
simpleType
element. See Section 2.5.5, “Defining enumerated types”. - For each element, define it using an
element
element. See Section 2.6, “Defining elements”.
2.4. XML Schema simple types
Overview
Entering simple types
element
elements used in the types section of your contract. They are also used in the base
attribute of restriction
elements and extension
elements.
xsd
prefix. For example, to specify that an element is of type int, you would enter xsd:int in its type
attribute as shown in Example 2.2, “Defining an element with a simple type”.
Example 2.2. Defining an element with a simple type
<element name="simpleInt" type="xsd:int" />
Supported XSD simple types
- xsd:string
- xsd:normalizedString
- xsd:int
- xsd:unsignedInt
- xsd:long
- xsd:unsignedLong
- xsd:short
- xsd:unsignedShort
- xsd:float
- xsd:double
- xsd:boolean
- xsd:byte
- xsd:unsignedByte
- xsd:integer
- xsd:positiveInteger
- xsd:negativeInteger
- xsd:nonPositiveInteger
- xsd:nonNegativeInteger
- xsd:decimal
- xsd:dateTime
- xsd:time
- xsd:date
- xsd:QName
- xsd:base64Binary
- xsd:hexBinary
- xsd:ID
- xsd:token
- xsd:language
- xsd:Name
- xsd:NCName
- xsd:NMTOKEN
- xsd:anySimpleType
- xsd:anyURI
- xsd:gYear
- xsd:gMonth
- xsd:gDay
- xsd:gYearMonth
- xsd:gMonthDay
2.5. Defining complex data types
Abstract
2.5.1. Defining data structures
Overview
complexType
elements. Specifying a complex type requires three pieces of information:
- The name of the defined type is specified in the
name
attribute of thecomplexType
element. - The first child element of the
complexType
describes the behavior of the structure’s fields when it is put on the wire. See the section called “Complex type varieties”. - Each of the fields of the defined structure are defined in
element
elements that are grandchildren of thecomplexType
element. See the section called “Defining the parts of a structure”.
Example 2.3. Simple Structure
struct personalInfo { string name; int age; };
Example 2.4. A complex type
<complexType name="personalInfo"> <sequence> <element name="name" type="xsd:string" /> <element name="age" type="xsd:int" /> </sequence> </complexType>
Complex type varieties
complexType
element determines which variety of complex type is being used. Table 2.1, “Complex type descriptor elements” shows the elements used to define complex type behavior.
sequence
element, an all
element, or a choice
is not specified, then a sequence
is assumed. For example, the structure defined in Example 2.4, “A complex type” generates a message containing two elements: name
and age
.
choice
element, as shown in Example 2.5, “Simple complex choice type”, it generates a message with either a name
element or an age
element.
Example 2.5. Simple complex choice type
<complexType name="personalInfo"> <choice> <element name="name" type="xsd:string"/> <element name="age" type="xsd:int"/> </choice> </complexType>
Defining the parts of a structure
element
elements. Every complexType
element should contain at least one element
element. Each element
element in the complexType
element represents a field in the defined data structure.
element
elements have two required attributes:
name
and type
, element
elements have two other commonly used optional attributes: minOcurrs
and maxOccurs
. These attributes place bounds on the number of times the field occurs in the structure. By default, each field occurs only once in a complex type. Using these attributes, you can change how many times a field must or can appear in a structure. For example, you can define a field, previousJobs
, that must occur at least three times, and no more than seven times, as shown in Example 2.6, “Simple complex type with occurrence constraints”.
Example 2.6. Simple complex type with occurrence constraints
<complexType name="personalInfo> <all> <element name="name" type="xsd:string"/> <element name="age" type="xsd:int"/> <element name="previousJobs" type="xsd:string: minOccurs="3" maxOccurs="7"/> </all> </complexType>
minOccurs
to make the age
field optional by setting the minOccurs
to zero as shown in Example 2.7, “Simple complex type with minOccurs set to zero”. In this case age
can be omitted and the data will still be valid.
Example 2.7. Simple complex type with minOccurs set to zero
<complexType name="personalInfo> <choice> <element name="name" type="xsd:string"/> <element name="age" type="xsd:int" minOccurs="0"/> </choice> </complexType>
Defining attributes
complexType
element name
is an attribute. They are specified using the attribute
element. It comes after the all
, sequence
, or choice
element and are a direct child of the complexType
element. Example 2.8, “Complex type with an attribute” shows a complex type with an attribute.
Example 2.8. Complex type with an attribute
<complexType name="personalInfo> <all> <element name="name" type="xsd:string"/> <element name="previousJobs" type="xsd:string" minOccurs="3" maxOccurs="7"/> </all> <attribute name="age" type="xsd:int" use="optional" /> </complexType>
attribute
element has three attributes:
default
. The default
attribute allows you to specify a default value for the attribute.
2.5.2. Defining arrays
Overview
maxOccurs
attribute has a value greater than one. The second is to use SOAP arrays. SOAP arrays provide added functionality such as the ability to easily define multi-dimensional arrays and to transmit sparsely populated arrays.
Complex type arrays
maxOccurs
attribute. For example, to define an array of twenty floating point numbers you use a complex type similar to the one shown in Example 2.9, “Complex type array”.
Example 2.9. Complex type array
<complexType name="personalInfo"> <element name="averages" type="xsd:float" maxOccurs="20"/> </complexType>
minOccurs
attribute.
SOAP arrays
wsdl:arrayType
element. The syntax for this is shown in Example 2.10, “Syntax for a SOAP array derived using wsdl:arrayType”.
Example 2.10. Syntax for a SOAP array derived using wsdl:arrayType
<complexType name="TypeName"> <complexContent> <restriction base="SOAP-ENC:Array"> <attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="ElementType<ArrayBounds>"/> </restriction> </complexContent> </complexType>
[]
; to specify a two-dimensional array use either [][]
or [,]
.
wsdl:arrayType
attribute specifies the type of the array elements, xsd:string, and the number of dimensions, with []
implying one dimension.
Example 2.11. Definition of a SOAP array
<complexType name="SOAPStrings"> <complexContent> <restriction base="SOAP-ENC:Array"> <attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:string[]"/> </restriction> </complexContent> </complexType>
Example 2.12. Syntax for a SOAP array derived using an element
<complexType name="TypeName"> <complexContent> <restriction base="SOAP-ENC:Array"> <sequence> <element name="ElementName" type="ElementType" maxOccurs="unbounded"/> </sequence> </restriction> </complexContent> </complexType>
maxOccurs
attribute must always be set to unbounded
.
2.5.3. Defining types by extension
alienInfo
, that extends the personalInfo
structure defined in Example 2.4, “A complex type” by adding a new element called planet
.
- The name of the type is defined by the
name
attribute of thecomplexType
element. - The
complexContent
element specifies that the new type will have more than one element.NoteIf you are only adding new attributes to the complex type, you can use asimpleContent
element. - The type from which the new type is derived, called the base type, is specified in the
base
attribute of theextension
element. - The new type’s elements and attributes are defined in the
extension
element, the same as they are for a regular complex type.
alienInfo
is defined as shown in Example 2.13, “Type defined by extension”.
Example 2.13. Type defined by extension
<complexType name="alienInfo"> <complexContent> <extension base="personalInfo"> <sequence> <element name="planet" type="xsd:string"/> </sequence> </extension> </complexContent> </complexType>
2.5.4. Defining types by restriction
Overview
SSN
, which is a string of exactly nine characters. New types defined by restricting simple types are defined using a simpleType
element.
- The name of the new type is specified by the
name
attribute of thesimpleType
element. - The simple type from which the new type is derived, called the base type, is specified in the
restriction
element. See the section called “Specifying the base type”. - The rules, called facets, defining the restrictions placed on the base type are defined as children of the
restriction
element. See the section called “Defining the restrictions”.
Specifying the base type
restriction
element. The restriction
element is the only child of a simpleType
element and has one attribute, base
, that specifies the base type. The base type can be any of the XML Schema simple types.
Example 2.14. Using int as the base type
<simpleType name="restrictedInt"> <restriction base="xsd:int"> ... </restriction> </simpleType>
Defining the restrictions
value
, that defines how the facet is enforced. The available facets and their valid value
settings depend on the base type. For example, xsd:string supports six facets, including:
length
minLength
maxLength
pattern
whitespace
enumeration
restriction
element.
Example
SSN
, which represents a social security number. The resulting type is a string of the form xxx-xx-xxxx
. <SSN>032-43-9876<SSN> is a valid value for an element of this type, but <SSN>032439876</SSN> is not.
Example 2.15. SSN simple type description
<simpleType name="SSN"> <restriction base="xsd:string"> <pattern value="\d{3}-\d{2}-\d{4}"/> </restriction> </simpleType>
2.5.5. Defining enumerated types
Overview
enumeration
facet which is supported by all XML Schema primitive types. As with enumerated types in most modern programming languages, a variable of this type can only have one of the specified values.
Defining an enumeration in XML Schema
Example 2.16. Syntax for an enumeration
<simpleType name="EnumName"> <restriction base="EnumType"> <enumeration value="Case1Value"/> <enumeration value="Case2Value"/> ... <enumeration value="CaseNValue"/> </restriction> </simpleType>
Example
widgetSize
, shown in Example 2.17, “widgetSize enumeration”, would be valid if it contained <widgetSize>big</widgetSize>, but it would not be valid if it contained <widgetSize>big,mungo</widgetSize>.
Example 2.17. widgetSize enumeration
<simpleType name="widgetSize"> <restriction base="xsd:string"> <enumeration value="big"/> <enumeration value="large"/> <enumeration value="mungo"/> </restriction> </simpleType>
2.6. Defining elements
element
element. Like the element
element used to define the members of a complex type, they have three attributes:
name
— A required attribute that specifies the name of the element as it appears in an XML document.type
— Specifies the type of the element. The type can be any XML Schema primitive type or any named complex type defined in the contract. This attribute can be omitted if the type has an in-line definition.nillable
— Specifies whether an element can be omitted from a document entirely. Ifnillable
is set totrue
, the element can be omitted from any document generated using the schema.
complexType
element or a simpleType
element. Once you specify if the type of data is complex or simple, you can define any type of data needed using the tools available for each type of data. In-line type definitions are discouraged because they are not reusable.
Chapter 3. Defining Logical Messages Used by a Service
Abstract
message
element. The messages are made up of one or more parts that are defined using part
elements.
Overview
message
element in your contracts. Each logical message consists of one or more parts, defined in part
elements.
Messages and parameter lists
Message design for integrating with legacy systems
types
element of the contract. Your input message contains one part for each input parameter in the method. Your output message contains one part for each output parameter, plus a part to represent the return value, if needed. If a parameter is both an input and an output parameter, it is listed as a part for both the input message and the output message.
Message design for SOAP services
types
element of the contract. The wrapper element has the following characteristics:
- It is a complex type containing a sequence of elements. For more information see Section 2.5, “Defining complex data types”.
- If it is a wrapper for an input message:
- It has one element for each of the method’s input parameters.
- Its name is the same as the name of the operation with which it is associated.
- If it is a wrapper for an output message:
- It has one element for each of the method’s output parameters and one element for each of the method’s inout parameters.
- Its first element represents the method’s return parameter.
- Its name would be generated by appending
Response
to the name of the operation with which the wrapper is associated.
Message naming
- Messages should only be used by a single operation.
- Input message names are formed by appending
Request
to the name of the operation. - Output message names are formed by appending
Response
to the name of the operation. - Fault message names should represent the reason for the fault.
Message parts
part
element, and is identified by a name
attribute and either a type
attribute or an element
attribute that specifies its data type. The data type attributes are listed in Table 3.1, “Part data type attributes”.
foo
, that is passed by reference or is an in/out, it can be a part in both the request message and the response message, as shown in Example 3.1, “Reused part”.
Example 3.1. Reused part
<message name="fooRequest"> <part name="foo" type="xsd:int"/> <message> <message name="fooReply"> <part name="foo" type="xsd:int"/> <message>
Example
Example 3.2. personalInfo lookup method
personalInfo lookup(long empId)
Example 3.3. RPC WSDL message definitions
<message name="personalLookupRequest"> <part name="empId" type="xsd:int"/> <message/> <message name="personalLookupResponse> <part name="return" element="xsd1:personalInfo"/> <message/>
Example 3.4. Wrapped document WSDL message definitions
<types> <schema ... > ... <element name="personalLookup"> <complexType> <sequence> <element name="empID" type="xsd:int" /> </sequence> </complexType> </element> <element name="personalLookupResponse"> <complexType> <sequence> <element name="return" type="personalInfo" /> </sequence> </complexType> </element> </schema> </types> <message name="personalLookupRequest"> <part name="empId" element="xsd1:personalLookup"/> <message/> <message name="personalLookupResponse"> <part name="return" element="xsd1:personalLookupResponse"/> <message/>
Chapter 4. Defining Your Logical Interfaces
Abstract
portType
element.
Overview
portType
element. The portType
element is a collection of abstract operation definitions. Each operation is defined by the input, output, and fault messages used to complete the transaction the operation represents. When code is generated to implement the service interface defined by a portType
element, each operation is converted into a method containing the parameters defined by the input, output, and fault messages specified in the contract.
Process
- Create a
portType
element to contain the interface definition and give it a unique name. See the section called “Port types”. - Create an
operation
element for each operation defined in the interface. See the section called “Operations”. - For each operation, specify the messages used to represent the operation’s parameter list, return type, and exceptions. See the section called “Operation messages”.
Port types
portType
element is the root element in a logical interface definition. While many Web service implementations map portType
elements directly to generated implementation objects, a logical interface definition does not specify the exact functionality provided by the the implemented service. For example, a logical interface named ticketSystem
can result in an implementation that either sells concert tickets or issues parking tickets.
portType
element is the unit of a WSDL document that is mapped into a binding to define the physical data used by an endpoint exposing the defined service.
portType
element in a WSDL document must have a unique name, which is specified using the name
attribute, and is made up of a collection of operations, which are described in operation
elements. A WSDL document can describe any number of port types.
Operations
operation
elements, define the interaction between two endpoints. For example, a request for a checking account balance and an order for a gross of widgets can both be defined as operations.
portType
element must have a unique name, specified using the name
attribute. The name
attribute is required to define an operation.
Operation messages
Element | Description |
---|---|
input | Specifies the message the client endpoint sends to the service provider when a request is made. The parts of this message correspond to the input parameters of the operation. |
output | Specifies the message that the service provider sends to the client endpoint in response to a request. The parts of this message correspond to any operation parameters that can be changed by the service provider, such as values passed by reference. This includes the return value of the operation. |
fault | Specifies a message used to communicate an error condition between the endpoints. |
input
or one output
element. An operation can have both input
and output
elements, but it can only have one of each. Operations are not required to have any fault
elements, but can, if required, have any number of fault
elements.
Attribute | Description |
---|---|
name | Identifies the message so it can be referenced when mapping the operation to a concrete data format. The name must be unique within the enclosing port type. |
message | Specifies the abstract message that describes the data being sent or received. The value of the message attribute must correspond to the name attribute of one of the abstract messages defined in the WSDL document. |
name
attribute for all input
and output
elements; WSDL provides a default naming scheme based on the enclosing operation’s name. If only one element is used in the operation, the element name defaults to the name of the operation. If both an input
and an output
element are used, the element name defaults to the name of the operation with either Request
or Response
respectively appended to the name.
Return values
operation
element is an abstract definition of the data passed during an operation, WSDL does not provide for return values to be specified for an operation. If a method returns a value it will be mapped into the output
element as the last part of that message.
Example
Example 4.1. personalInfo lookup interface
interface personalInfoLookup { personalInfo lookup(in int empID) raises(idNotFound); }
Example 4.2. personalInfo lookup port type
<message name="personalLookupRequest"> <part name="empId" element="xsd1:personalLookup"/> <message/> <message name="personalLookupResponse"> <part name="return" element="xsd1:personalLookupResponse"/> <message/> <message name="idNotFoundException"> <part name="exception" element="xsd1:idNotFound"/> <message/> <portType name="personalInfoLookup"> <operation name="lookup"> <input name="empID" message="personalLookupRequest"/> <output name="return" message="personalLookupResponse"/> <fault name="exception" message="idNotFoundException"/> </operation> </portType>
Part II. Web Services Bindings
Abstract
Chapter 5. Understanding Bindings in WSDL
Abstract
Overview
Port types and bindings
The WSDL elements
binding
element. The binding element has a single attribute, name
, that specifies a unique name for the binding. The value of this attribute is used to associate the binding with an endpoint as discussed in Chapter 4, Defining Your Logical Interfaces.
binding
element. These elements vary depending on the type of payload format you decide to use. The different payload formats and the elements used to specify their mappings are discussed in the following chapters.
Adding to a contract
Supported bindings
- SOAP 1.1
- SOAP 1.2
- CORBA
- Pure XML
Chapter 6. Using SOAP 1.1 Messages
Abstract
6.1. Adding a SOAP 1.1 Binding
Using wsdl2soap
wsdl2soap
{
-i port-type-name
} [
-b binding-name
] [
-d output-directory
] [
-o output-file
] [
-n soap-body-namespace
] [
-style (document/rpc)
] [
-use (literal/encoded)
] [
-v
] [[
-verbose
] | [
-quiet
]]
wsdlurl
Option | Interpretation |
---|---|
-i port-type-name |
Specifies the
portType element for which a binding is generated.
|
wsdlurl | The path and name of the WSDL file containing the portType element definition. |
Option | Interpretation |
---|---|
-b binding-name | Specifies the name of the generated SOAP binding. |
-d output-directory | Specifies the directory to place the generated WSDL file. |
-o output-file | Specifies the name of the generated WSDL file. |
-n soap-body-namespace | Specifies the SOAP body namespace when the style is RPC. |
-style (document /rpc ) | Specifies the encoding style (document or RPC) to use in the SOAP binding. The default is document . |
-use (literal /encoded ) | Specifies the binding use (encoded or literal) to use in the SOAP binding. The default is literal . |
-v | Displays the version number for the tool. |
-verbose | Displays comments during the code generation process. |
-quiet | Suppresses comments during the code generation process. |
-i
port-type-name and wsdlurl arguments are required. If the -style rpc
argument is specified, the -n
soap-body-namspace argument is also required. All other arguments are optional and may be listed in any order.
document/encoded
SOAP bindings.
Example
Example 6.1. Ordering System Interface
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> ... </definitions>
orderWidgets
is shown in Example 6.2, “SOAP 1.1 Binding for orderWidgets
”.
Example 6.2. SOAP 1.1 Binding for orderWidgets
<binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap:operation soapAction="" style="document"/> <input name="order"> <soap:body use="literal"/> </input> <output name="bill"> <soap:body use="literal"/> </output> <fault name="sizeFault"> <soap:body use="literal"/> </fault> </operation> </binding>
document/literal
message style.
6.2. Adding SOAP Headers to a SOAP 1.1 Binding
Overview
soap:header
elements to your default SOAP 1.1 binding. The soap:header
element is an optional child of the input
, output
, and fault
elements of the binding. The SOAP header becomes part of the parent message. A SOAP header is defined by specifying a message and a message part. Each SOAP header can only contain one message part, but you can insert as many SOAP headers as needed.
Syntax
message
attribute of soap:header
is the qualified name of the message from which the part being inserted into the header is taken. The part
attribute is the name of the message part inserted into the SOAP header. Because SOAP headers are always document style, the WSDL message part inserted into the SOAP header must be defined using an element. Together the message
and the part
attributes fully describe the data to insert into the SOAP header.
Example 6.3. SOAP Header Syntax
<binding name="headwig"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="weave"> <soap:operation soapAction="" style="document"/> <input name="grain"> <soap:body ... /> <soap:header message="QName" part="partName"/> </input> ... </binding>
message
and part
attributes, soap:header
also supports the namespace
, the use
, and the encodingStyle
attributes. These optional attributes function the same for soap:header
as they do for soap:body
.
Splitting messages between body and header
soap:body
element has an optional attribute, parts
, that takes a space delimited list of part names. When parts
is defined, only the message parts listed are inserted into the SOAP body. You can then insert the remaining parts into the SOAP header.
Example
orderWidgets
service shown in Example 6.1, “Ordering System Interface”. This version has been modified so that each order has an xsd:base64binary value placed in the SOAP header of the request and response. The SOAP header is defined as being the keyVal
part from the widgetKey
message. In this case you are responsible for adding the SOAP header to your application logic because it is not part of the input or output message.
Example 6.4. SOAP 1.1 Binding with a SOAP Header
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <types> <schema targetNamespace="http://widgetVendor.com/types/widgetTypes" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <element name="keyElem" type="xsd:base64Binary"/> </schema> </types> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <message name="widgetKey"> <part name="keyVal" element="xsd1:keyElem"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> <binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap:operation soapAction="" style="document"/> <input name="order"> <soap:body use="literal"/> <soap:header message="tns:widgetKey" part="keyVal"/> </input> <output name="bill"> <soap:body use="literal"/> <soap:header message="tns:widgetKey" part="keyVal"/> </output> <fault name="sizeFault"> <soap:body use="literal"/> </fault> </operation> </binding> ... </definitions>
keyVal
is a part of the input and output messages. In the soap:body
element's parts
attribute specifies that keyVal
cannot be inserted into the body. However, it is inserted into the SOAP header.
Example 6.5. SOAP 1.1 Binding for orderWidgets with a SOAP Header
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <types> <schema targetNamespace="http://widgetVendor.com/types/widgetTypes" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <element name="keyElem" type="xsd:base64Binary"/> </schema> </types> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> <part name="keyVal" element="xsd1:keyElem"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> <part name="keyVal" element="xsd1:keyElem"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> <binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap:operation soapAction="" style="document"/> <input name="order"> <soap:body use="literal" parts="numOrdered"/> <soap:header message="tns:widgetOrder" part="keyVal"/> </input> <output name="bill"> <soap:body use="literal" parts="bill"/> <soap:header message="tns:widgetOrderBill" part="keyVal"/> </output> <fault name="sizeFault"> <soap:body use="literal"/> </fault> </operation> </binding> ... </definitions>
Chapter 7. Using SOAP 1.2 Messages
Abstract
7.1. Adding a SOAP 1.2 Binding to a WSDL Document
Using wsdl2soap
wsdl2soap
{
-i port-type-name
} [
-b binding-name
] {
-soap12
} [
-d output-directory
] [
-o output-file
] [
-n soap-body-namespace
] [
-style (document/rpc)
] [
-use (literal/encoded)
] [
-v
] [[
-verbose
] | [
-quiet
]]
wsdlurl
Option | Interpretation |
---|---|
-i port-type-name |
Specifies the
portType element for which a binding is generated.
|
-soap12 | Specifies that the generated binding uses SOAP 1.2. |
wsdlurl | The path and name of the WSDL file containing the portType element definition. |
Option | Interpretation |
---|---|
-b binding-name | Specifies the name of the generated SOAP binding. |
-soap12 | Specifies that the generated binding will use SOAP 1.2. |
-d output-directory | Specifies the directory to place the generated WSDL file. |
-o output-file | Specifies the name of the generated WSDL file. |
-n soap-body-namespace | Specifies the SOAP body namespace when the style is RPC. |
-style (document /rpc ) | Specifies the encoding style (document or RPC) to use in the SOAP binding. The default is document . |
-use (literal /encoded ) | Specifies the binding use (encoded or literal) to use in the SOAP binding. The default is literal . |
-v | Displays the version number for the tool. |
-verbose | Displays comments during the code generation process. |
-quiet | Suppresses comments during the code generation process. |
-i
port-type-name and wsdlurl arguments are required. If the -style rpc
argument is specified, the -n
soap-body-namspace argument is also required. All other arguments are optional and can be listed in any order.
document/encoded
SOAP 1.2 bindings.
Example
Example 7.1. Ordering System Interface
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> ... </definitions>
orderWidgets
is shown in Example 7.2, “SOAP 1.2 Binding for orderWidgets”.
Example 7.2. SOAP 1.2 Binding for orderWidgets
<binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap12:operation soapAction="" style="document"/> <input name="order"> <soap12:body use="literal"/> </input> <output name="bill"> <wsoap12:body use="literal"/> </output> <fault name="sizeFault"> <soap12:body use="literal"/> </fault> </operation> </binding>
document/literal
message style.
7.2. Adding Headers to a SOAP 1.2 Message
Overview
soap12:header
elements to your SOAP 1.2 message. The soap12:header
element is an optional child of the input
, output
, and fault
elements of the binding. The SOAP header becomes part of the parent message. A SOAP header is defined by specifying a message and a message part. Each SOAP header can only contain one message part, but you can insert as many headers as needed.
Syntax
Example 7.3. SOAP Header Syntax
<binding name="headwig"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="weave"> <soap12:operation soapAction="" style="documment"/> <input name="grain"> <soap12:body ... /> <soap12:header message="QName" part="partName" use="literal|encoded" encodingStyle="encodingURI" namespace="namespaceURI" /> </input> ... </binding>
soap12:header
element’s attributes are described in Table 7.1, “soap12:header
Attributes”.
Splitting messages between body and header
soap12:body
element has an optional attribute, parts
, that takes a space delimited list of part names. When parts
is defined, only the message parts listed are inserted into the body of the SOAP 1.2 message. You can then insert the remaining parts into the message's header.
Example
orderWidgets
service shown in Example 7.1, “Ordering System Interface”. This version is modified so that each order has an xsd:base64binary value placed in the header of the request and the response. The header is defined as being the keyVal
part from the widgetKey
message. In this case you are responsible for adding the application logic to create the header because it is not part of the input or output message.
Example 7.4. SOAP 1.2 Binding with a SOAP Header
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <types> <schema targetNamespace="http://widgetVendor.com/types/widgetTypes" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <element name="keyElem" type="xsd:base64Binary"/> </schema> </types> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <message name="widgetKey"> <part name="keyVal" element="xsd1:keyElem"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> <binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap12:operation soapAction="" style="document"/> <input name="order"> <soap12:body use="literal"/> <soap12:header message="tns:widgetKey" part="keyVal"/> </input> <output name="bill"> <soap12:body use="literal"/> <soap12:header message="tns:widgetKey" part="keyVal"/> </output> <fault name="sizeFault"> <soap12:body use="literal"/> </fault> </operation> </binding> ... </definitions>
keyVal
is a part of the input and output messages. In the soap12:body
elements the parts
attribute specifies that keyVal
should not be inserted into the body. However, it is inserted into the header.
Example 7.5. SOAP 1.2 Binding for orderWidgets with a SOAP Header
<?xml version="1.0" encoding="UTF-8"?> <definitions name="widgetOrderForm.wsdl" targetNamespace="http://widgetVendor.com/widgetOrderForm" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://widgetVendor.com/widgetOrderForm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsd1="http://widgetVendor.com/types/widgetTypes" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"> <types> <schema targetNamespace="http://widgetVendor.com/types/widgetTypes" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"> <element name="keyElem" type="xsd:base64Binary"/> </schema> </types> <message name="widgetOrder"> <part name="numOrdered" type="xsd:int"/> <part name="keyVal" element="xsd1:keyElem"/> </message> <message name="widgetOrderBill"> <part name="price" type="xsd:float"/> <part name="keyVal" element="xsd1:keyElem"/> </message> <message name="badSize"> <part name="numInventory" type="xsd:int"/> </message> <portType name="orderWidgets"> <operation name="placeWidgetOrder"> <input message="tns:widgetOrder" name="order"/> <output message="tns:widgetOrderBill" name="bill"/> <fault message="tns:badSize" name="sizeFault"/> </operation> </portType> <binding name="orderWidgetsBinding" type="tns:orderWidgets"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="placeWidgetOrder"> <soap12:operation soapAction="" style="document"/> <input name="order"> <soap12:body use="literal" parts="numOrdered"/> <soap12:header message="tns:widgetOrder" part="keyVal"/> </input> <output name="bill"> <soap12:body use="literal" parts="bill"/> <soap12:header message="tns:widgetOrderBill" part="keyVal"/> </output> <fault name="sizeFault"> <soap12:body use="literal"/> </fault> </operation> </binding> ... </definitions>
Chapter 8. Sending Binary Data Using SOAP with Attachments
Abstract
Overview
Namespace
mime
. The entry in the WSDL definitions
element to set this up is shown in Example 8.1, “MIME Namespace Specification in a Contract”.
Example 8.1. MIME Namespace Specification in a Contract
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
Changing the message binding
input
, output
, and fault
elements is a soap:body
element describing the body of the SOAP message representing the data. When using SOAP with attachments, the soap:body
element is replaced with a mime:multipartRelated
element.
mime:multipartRelated
for fault
messages.
mime:multipartRelated
element tells Apache CXF that the message body is a multipart message that potentially contains binary data. The contents of the element define the parts of the message and their contents. mime:multipartRelated
elements contain one or more mime:part
elements that describe the individual parts of the message.
mime:part
element must contain the soap:body
element that would normally appear in a default SOAP binding. The remaining mime:part
elements define the attachments that are being sent in the message.
Describing a MIME multipart message
mime:multipartRelated
element that contains a number of mime:part
elements. To fully describe a MIME multipart message you must do the following:
- Inside the
input
oroutput
message you are sending as a MIME multipart message, add amime:mulipartRelated
element as the first child element of the enclosing message. - Add a
mime:part
child element to themime:multipartRelated
element and set itsname
attribute to a unique string. - Add a
soap:body
element as the child of themime:part
element and set its attributes appropriately.NoteIf the contract had a default SOAP binding, you can copy thesoap:body
element from the corresponding message from the default binding into the MIME multipart message. - Add another
mime:part
child element to themime:multipartReleated
element and set itsname
attribute to a unique string. - Add a
mime:content
child element to themime:part
element to describe the contents of this part of the message.To fully describe the contents of a MIME message part themime:content
element has the following attributes:Table 8.1. mime:content Attributes Attribute Description part
Specifies the name of the WSDL message part
, from the parent message definition, that is used as the content of this part of the MIME multipart message being placed on the wire.type
The MIME type of the data in this message part. MIME types are defined as a type and a subtype using the syntax type/
subtype.There are a number of predefined MIME types such asimage/jpeg
andtext/plain
. The MIME types are maintained by the Internet Assigned Numbers Authority (IANA) and described in detail in Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies and Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types.
Example
xRay
, is stored as an xsd:base64binary and is packed into the MIME multipart message's second part, imageData
. The remaining two parts of the input message, patientName
and patientNumber
, are sent in the first part of the MIME multipart image as part of the SOAP body.
Example 8.2. Contract using SOAP with Attachments
<?xml version="1.0" encoding="UTF-8"?> <definitions name="XrayStorage" targetNamespace="http://mediStor.org/x-rays" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://mediStor.org/x-rays" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="storRequest"> <part name="patientName" type="xsd:string"/> <part name="patientNumber" type="xsd:int"/> <part name="xRay" type="xsd:base64Binary"/> </message> <message name="storResponse"> <part name="success" type="xsd:boolean"/> </message> <portType name="xRayStorage"> <operation name="store"> <input message="tns:storRequest" name="storRequest"/> <output message="tns:storResponse" name="storResponse"/> </operation> </portType> <binding name="xRayStorageBinding" type="tns:xRayStorage"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="store"> <soap:operation soapAction="" style="document"/> <input name="storRequest"> <mime:multipartRelated> <mime:part name="bodyPart"> <soap:body use="literal"/> </mime:part> <mime:part name="imageData"> <mime:content part="xRay" type="image/jpeg"/> </mime:part> </mime:multipartRelated> </input> <output name="storResponse"> <soap:body use="literal"/> </output> </operation> </binding> <service name="xRayStorageService"> <port binding="tns:xRayStorageBinding" name="xRayStoragePort"> <soap:address location="http://localhost:9000"/> </port> </service> </definitions>
Chapter 9. Sending Binary Data with SOAP MTOM
Abstract
9.1. Overview of MTOM
- Annotate the data that you are going to send as an attachment.You can annotate either your WSDL or the Java class that implements your data.
- Enable the runtime's MTOM support.This can be done either programmatically or through configuration.
- Develop a
DataHandler
for the data being passed as an attachment.NoteDevelopingDataHandler
s is beyond the scope of this book.
9.2. Annotating Data Types to use MTOM
Overview
WSDL first
Example 9.1. Message for MTOM
<?xml version="1.0" encoding="UTF-8"?> <definitions name="XrayStorage" targetNamespace="http://mediStor.org/x-rays" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://mediStor.org/x-rays" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:xsd1="http://mediStor.org/types/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <types> <schema targetNamespace="http://mediStor.org/types/" xmlns="http://www.w3.org/2001/XMLSchema"> <complexType name="xRayType"> <sequence> <element name="patientName" type="xsd:string" /> <element name="patientNumber" type="xsd:int" /> <element name="imageData" type="xsd:base64Binary" /> </sequence> </complexType> <element name="xRay" type="xsd1:xRayType" /> </schema> </types> <message name="storRequest"> <part name="record" element="xsd1:xRay"/> </message> <message name="storResponse"> <part name="success" type="xsd:boolean"/> </message> <portType name="xRayStorage"> <operation name="store"> <input message="tns:storRequest" name="storRequest"/> <output message="tns:storResponse" name="storResponse"/> </operation> </portType> <binding name="xRayStorageSOAPBinding" type="tns:xRayStorage"> <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="store"> <soap12:operation soapAction="" style="document"/> <input name="storRequest"> <soap12:body use="literal"/> </input> <output name="storResponse"> <soap12:body use="literal"/> </output> </operation> </binding> ... </definitions>
xmime:expectedContentTypes
attribute to the element containing the binary data. This attribute is defined in the http://www.w3.org/2005/05/xmlmime namespace and specifies the MIME types that the element is expected to contain. You can specify a comma separated list of MIME types. The setting of this attribute changes how the code generators create the JAXB class for the data. For most MIME types, the code generator creates a DataHandler
. Some MIME types, such as those for images, have defined mappings.
application/octet-stream
.
Example 9.2. Binary Data for MTOM
... <types> <schema targetNamespace="http://mediStor.org/types/" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xmime="http://www.w3.org/2005/05/xmlmime"> <complexType name="xRayType"> <sequence> <element name="patientName" type="xsd:string" /> <element name="patientNumber" type="xsd:int" /> <element name="imageData" type="xsd:base64Binary" xmime:expectedContentTypes="application/octet-stream"/> </sequence> </complexType> <element name="xRay" type="xsd1:xRayType" /> </schema> </types> ...
xmime:expectedContentTypes
attribute and generates a DataHandler
for the imageData field.
binding
element to use MTOM. The runtime makes the appropriate changes when the data is sent.
Java first
- Make sure the field holding the binary data is a
DataHandler
. - Add the
@XmlMimeType()
annotation to the field containing the data you want to stream as an MTOM attachment.
Example 9.3. JAXB Class for MTOM
@XmlType
public class XRayType {
protected String patientName;
protected int patientNumber;
@XmlMimeType("application/octet-stream")
protected DataHandler imageData;
...
}
9.3. Enabling MTOM
9.3.1. Using JAX-WS APIs
Overview
Service provider
- Access the
Endpoint
object for your published service.The easiest way to access theEndpoint
object is when you publish the endpoint. For more information see Chapter 31, Publishing a Service. - Get the SOAP binding from the
Endpoint
using itsgetBinding()
method, as shown in Example 9.4, “Getting the SOAP Binding from an Endpoint”.Example 9.4. Getting the SOAP Binding from an Endpoint
// Endpoint ep is declared previously SOAPBinding binding = (SOAPBinding)ep.getBinding();
You must cast the returned binding object to aSOAPBinding
object to access the MTOM property. - Set the binding's MTOM enabled property to
true
using the binding'ssetMTOMEnabled()
method, as shown in Example 9.5, “Setting a Service Provider's MTOM Enabled Property”.Example 9.5. Setting a Service Provider's MTOM Enabled Property
binding.setMTOMEnabled(true);
Consumer
- Cast the consumer's proxy to a
BindingProvider
object.TipFor information on getting a consumer proxy see Chapter 25, Developing a Consumer Without a WSDL Contract or Chapter 28, Developing a Consumer From a WSDL Contract. - Get the SOAP binding from the
BindingProvider
using itsgetBinding()
method, as shown in Example 9.6, “Getting a SOAP Binding from aBindingProvider
”.Example 9.6. Getting a SOAP Binding from a
BindingProvider
// BindingProvider bp declared previously SOAPBinding binding = (SOAPBinding)bp.getBinding();
- Set the bindings MTOM enabled property to
true
using the binding'ssetMTOMEnabled()
method, as shown in Example 9.7, “Setting a Consumer's MTOM Enabled Property”.Example 9.7. Setting a Consumer's MTOM Enabled Property
binding.setMTOMEnabled(true);
9.3.2. Using configuration
Overview
Procedure
jaxws:endpoint
element for your endpoint. To enable MTOM do the following:
- Add a
jaxws:property
child element to the endpoint'sjaxws:endpoint
element. - Add a
entry
child element to thejaxws:property
element. - Set the
entry
element'skey
attribute tomtom-enabled
. - Set the
entry
element'svalue
attribute totrue
.
Example
Example 9.8. Configuration for Enabling MTOM
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd"> <jaxws:endpoint id="xRayStorage" implementor="demo.spring.xRayStorImpl" address="http://localhost/xRayStorage"> <jaxws:properties> <entry key="mtom-enabled" value="true"/> </jaxws:properties> </jaxws:endpoint> </beans>
Chapter 10. Using XML Documents
Abstract
XML binding namespace
xformat
to represent the XML binding extensions. Add the following line to your contracts:
xmlns:xformat="http://cxf.apache.org/bindings/xformat"
Hand editing
- Add the namespace declaration to include the extensions defining the XML binding. See the section called “XML binding namespace”.
- Add a standard WSDL
binding
element to your contract to hold the XML binding, give the binding a uniquename
, and specify the name of the WSDLportType
element that represents the interface being bound. - Add an
xformat:binding
child element to thebinding
element to identify that the messages are being handled as pure XML documents without SOAP envelopes. - Optionally, set the
xformat:binding
element'srootNode
attribute to a valid QName. For more information on the effect of therootNode
attribute see the section called “XML messages on the wire”. - For each operation defined in the bound interface, add a standard WSDL
operation
element to hold the binding information for the operation's messages. - For each operation added to the binding, add the
input
,output
, andfault
children elements to represent the messages used by the operation.These elements correspond to the messages defined in the interface definition of the logical operation. - Optionally add an
xformat:body
element with a validrootNode
attribute to the addedinput
,output
, andfault
elements to override the value ofrootNode
set at the binding level.
rootNode
attribute for the message to ensure that the message written on the wire is a valid, but empty, XML document.
XML messages on the wire
rootNode
attribute on either the global xformat:binding
element or on the individual message’s xformat:body
elements. The rootNode
attribute specifies the QName for the element that serves as the root node for the XML document generated by Apache CXF. When the rootNode
attribute is not set, Apache CXF uses the root element of the message part as the root element when using doc style messages, or an element using the message part name as the root element when using rpc style messages.
rootNode
attribute is not set the message defined in Example 10.1, “Valid XML Binding Message” would generate an XML document with the root element lineNumber
.
Example 10.1. Valid XML Binding Message
<type ... > ... <element name="operatorID" type="xsd:int"/> ... </types> <message name="operator"> <part name="lineNumber" element="ns1:operatorID"/> </message>
rootNode
attribute is not set. However, the message in Example 10.2, “Invalid XML Binding Message” would generate an invalid XML document.
Example 10.2. Invalid XML Binding Message
<types> ... <element name="pairName" type="xsd:string"/> <element name="entryNum" type="xsd:int"/> ... </types> <message name="matildas"> <part name="dancing" element="ns1:pairName"/> <part name="number" element="ns1:entryNum"/> </message>
rootNode
attribute specified in the XML binding, Apache CXF will generate an XML document similar to Example 10.3, “Invalid XML Document” for the message defined in Example 10.2, “Invalid XML Binding Message”. The generated XML document is invalid because it has two root elements: pairName
and entryNum
.
Example 10.3. Invalid XML Document
<pairName> Fred&Linda </pairName> <entryNum> 123 </entryNum>
rootNode
attribute, as shown in Example 10.4, “XML Binding with rootNode set” Apache CXF will wrap the elements in the specified root element. In this example, the rootNode
attribute is defined for the entire binding and specifies that the root element will be named entrants.
Example 10.4. XML Binding with rootNode set
<portType name="danceParty"> <operation name="register"> <input message="tns:matildas" name="contestant"/> </operation> </portType> <binding name="matildaXMLBinding" type="tns:dancingMatildas"> <xmlformat:binding rootNode="entrants"/> <operation name="register"> <input name="contestant"/> <output name="entered"/> </binding>
Example 10.5. XML Document generated using the rootNode attribute
<entrants> <pairName> Fred&Linda <entryNum> 123 </entryNum> </entrants>
Overriding the binding's rootNode attribute setting
rootNode
attribute for each individual message, or override the global setting for a particular message, by using the xformat:body
element inside of the message binding. For example, if you wanted the output message defined in Example 10.4, “XML Binding with rootNode set” to have a different root element from the input message, you could override the binding's root element as shown in Example 10.6, “Using xformat:body
”.
Example 10.6. Using xformat:body
<binding name="matildaXMLBinding" type="tns:dancingMatildas"> <xmlformat:binding rootNode="entrants"/> <operation name="register"> <input name="contestant"/> <output name="entered"> <xformat:body rootNode="entryStatus" /> </output> </operation> </binding>
Part III. Web Services Transports
Abstract
Chapter 11. Understanding How Endpoints are Defined in WSDL
Abstract
Overview
Endpoints and services
The WSDL elements
service
element and the WSDL port
element. The service
element is a collection of related port
elements. The port
elements define the actual endpoints.
service
element has a single attribute, name
, that specifies a unique name. The service
element is used as the parent element of a collection of related port
elements. WSDL makes no specification about how the port
elements are related. You can associate the port
elements in any manner you see fit.
port
element has a single attribute, binding
, that specifies the binding used by the endpoint. The port
element is the parent element of the elements that specify the actual transport details used by the endpoint. The elements used to specify the transport details are discussed in the following sections.
Adding endpoints to a contract
Supported transports
- HTTP
- CORBA
- Java Messaging Service
Chapter 12. Using HTTP
Abstract
12.1. Adding a Basic HTTP Endpoint
Alternative HTTP runtimes
- Jetty, which is described in detail in Section 12.4, “Configuring the Jetty Runtime”.
- Netty, which is described in detail in Section 12.5, “Configuring the Netty Runtime”.
Netty HTTP URL
netty://http://RestOfURL
Payload types
- SOAP 1.1 uses the standardized
soap:address
element. - SOAP 1.2 uses the
soap12:address
element. - All other payload formats use the
http:address element.
SOAP 1.1
address
element to specify the endpoint’s address. It has one attribute, location
, that specifies the endpoint’s address as a URL. The SOAP 1.1 address
element is defined in the namespace http://schemas.xmlsoap.org/wsdl/soap/.
port
element used to send SOAP 1.1 messages over HTTP.
Example 12.1. SOAP 1.1 Port Element
<definitions ... xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" ...> ... <service name="SOAP11Service"> <port binding="SOAP11Binding" name="SOAP11Port"> <soap:address location="http://artie.com/index.xml"> </port> </service> ... <definitions>
SOAP 1.2
address
element to specify the endpoint’s address. It has one attribute, location
, that specifies the endpoint’s address as a URL. The SOAP 1.2 address
element is defined in the namespace http://schemas.xmlsoap.org/wsdl/soap12/.
port
element used to send SOAP 1.2 messages over HTTP.
Example 12.2. SOAP 1.2 Port Element
<definitions ... xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" ... > <service name="SOAP12Service"> <port binding="SOAP12Binding" name="SOAP12Port"> <soap12:address location="http://artie.com/index.xml"> </port> </service> ... </definitions>
Other messages types
address
element to specify the endpoint’s address. It has one attribute, location
, that specifies the endpoint’s address as a URL. The HTTP address
element is defined in the namespace http://schemas.xmlsoap.org/wsdl/http/.
port
element used to send an XML message.
Example 12.3. HTTP Port Element
<definitions ... xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" ... > <service name="HTTPService"> <port binding="HTTPBinding" name="HTTPPort"> <http:address location="http://artie.com/index.xml"> </port> </service> ... </definitions>
12.2. Configuring a Consumer
12.2.1. Mechanisms for HTTP Consumer Endpoints
12.2.2. Using Configuration
Namespace
http-conf
. In order to use the HTTP configuration elements you must add the lines shown in Example 12.4, “HTTP Consumer Configuration Namespace” to the beans
element of your endpoint's configuration file. In addition, you must add the configuration elements' namespace to the xsi:schemaLocation
attribute.
Example 12.4. HTTP Consumer Configuration Namespace
<beans ... xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" ... xsi:schemaLocation="... http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd ...">
Jetty runtime or Netty runtime
http-conf
namespace to configure either the Jetty runtime or the Netty runtime.
The conduit element
http-conf:conduit
element and its children. The http-conf:conduit
element takes a single attribute, name
, that specifies the WSDL port
element corresponding to the endpoint. The value for the name
attribute takes the form portQName.http-conduit
. Example 12.5, “http-conf:conduit
Element” shows the http-conf:conduit
element that would be used to add configuration for an endpoint that is specified by the WSDL fragment <port binding="widgetSOAPBinding" name="widgetSOAPPort> when the endpoint's target namespace is http://widgets.widgetvendor.net.
Example 12.5. http-conf:conduit
Element
... <http-conf:conduit name="{http://widgets/widgetvendor.net}widgetSOAPPort.http-conduit"> ... </http-conf:conduit> ...
http-conf:conduit
element has child elements that specify configuration information. They are described in Table 12.1, “Elements Used to Configure an HTTP Consumer Endpoint”.
Element | Description |
---|---|
http-conf:client |
Specifies the HTTP connection properties such as timeouts, keep-alive requests, content types, etc. See the section called “The client element”.
|
http-conf:authorization |
Specifies the parameters for configuring the basic authentication method that the endpoint uses preemptively.
The preferred approach is to supply a Basic Authentication Supplier object.
|
http-conf:proxyAuthorization |
Specifies the parameters for configuring basic authentication against outgoing HTTP proxy servers.
|
http-conf:tlsClientParameters |
Specifies the parameters used to configure SSL/TLS.
|
http-conf:basicAuthSupplier |
Specifies the bean reference or class name of the object that supplies the basic authentication information used by the endpoint, either preemptively or in response to a
401 HTTP challenge.
|
http-conf:trustDecider |
Specifies the bean reference or class name of the object that checks the HTTP(S)
URLConnection object to establish trust for a connection with an HTTPS service provider before any information is transmitted.
|
The client element
http-conf:client
element is used to configure the non-security properties of a consumer endpoint's HTTP connection. Its attributes, described in Table 12.2, “HTTP Consumer Configuration Attributes”, specify the connection's properties.
Attribute | Description |
---|---|
ConnectionTimeout |
Specifies the amount of time, in milliseconds, that the consumer attempts to establish a connection before it times out. The default is
30000 .
0 specifies that the consumer will continue to send the request indefinitely.
|
ReceiveTimeout |
Specifies the amount of time, in milliseconds, that the consumer will wait for a response before it times out. The default is
30000 .
0 specifies that the consumer will wait indefinitely.
|
AutoRedirect |
Specifies if the consumer will automatically follow a server issued redirection. The default is
false .
|
MaxRetransmits |
Specifies the maximum number of times a consumer will retransmit a request to satisfy a redirect. The default is
-1 which specifies that unlimited retransmissions are allowed.
|
AllowChunking |
Specifies whether the consumer will send requests using chunking. The default is
true which specifies that the consumer will use chunking when sending requests.
Chunking cannot be used if either of the following are true:
In both cases the value of
AllowChunking is ignored and chunking is disallowed.
|
Accept |
Specifies what media types the consumer is prepared to handle. The value is used as the value of the HTTP Accept property. The value of the attribute is specified using multipurpose internet mail extensions (MIME) types.
|
AcceptLanguage |
Specifies what language (for example, American English) the consumer prefers for the purpose of receiving a response. The value is used as the value of the HTTP AcceptLanguage property.
Language tags are regulated by the International Organization for Standards (ISO) and are typically formed by combining a language code, determined by the ISO-639 standard, and country code, determined by the ISO-3166 standard, separated by a hyphen. For example, en-US represents American English.
|
AcceptEncoding |
Specifies what content encodings the consumer is prepared to handle. Content encoding labels are regulated by the Internet Assigned Numbers Authority (IANA). The value is used as the value of the HTTP AcceptEncoding property.
|
ContentType |
Specifies the media type of the data being sent in the body of a message. Media types are specified using multipurpose internet mail extensions (MIME) types. The value is used as the value of the HTTP ContentType property. The default is
text/xml .
For web services, this should be set to
text/xml . If the client is sending HTML form data to a CGI script, this should be set to application/x-www-form-urlencoded . If the HTTP POST request is bound to a fixed payload format (as opposed to SOAP), the content type is typically set to application/octet-stream .
|
Host |
Specifies the Internet host and port number of the resource on which the request is being invoked. The value is used as the value of the HTTP Host property.
This attribute is typically not required. It is only required by certain DNS scenarios or application designs. For example, it indicates what host the client prefers for clusters (that is, for virtual servers mapping to the same Internet protocol (IP) address).
|
Connection |
Specifies whether a particular connection is to be kept open or closed after each request/response dialog. There are two valid values:
|
CacheControl |
Specifies directives about the behavior that must be adhered to by caches involved in the chain comprising a request from a consumer to a service provider. See Section 12.2.4, “Consumer Cache Control Directives”.
|
Cookie |
Specifies a static cookie to be sent with all requests.
|
BrowserType |
Specifies information about the browser from which the request originates. In the HTTP specification from the World Wide Web consortium (W3C) this is also known as the user-agent. Some servers optimize based on the client that is sending the request.
|
Referer |
Specifies the URL of the resource that directed the consumer to make requests on a particular service. The value is used as the value of the HTTP Referer property.
This HTTP property is used when a request is the result of a browser user clicking on a hyperlink rather than typing a URL. This can allow the server to optimize processing based upon previous task flow, and to generate lists of back-links to resources for the purposes of logging, optimized caching, tracing of obsolete or mistyped links, and so on. However, it is typically not used in web services applications.
If the
AutoRedirect attribute is set to true and the request is redirected, any value specified in the Referer attribute is overridden. The value of the HTTP Referer property is set to the URL of the service that redirected the consumer’s original request.
|
DecoupledEndpoint |
Specifies the URL of a decoupled endpoint for the receipt of responses over a separate provider->consumer connection. For more information on using decoupled endpoints see, Section 12.6, “Using the HTTP Transport in Decoupled Mode”.
You must configure both the consumer endpoint and the service provider endpoint to use WS-Addressing for the decoupled endpoint to work.
|
ProxyServer |
Specifies the URL of the proxy server through which requests are routed.
|
ProxyServerPort |
Specifies the port number of the proxy server through which requests are routed.
|
ProxyServerType |
Specifies the type of proxy server used to route requests. Valid values are:
|
Example
Example 12.6. HTTP Consumer Endpoint Configuration
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xsi:schemaLocation="http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <http-conf:conduit name="{http://apache.org/hello_world_soap_http}SoapPort.http-conduit"> <http-conf:client Connection="Keep-Alive" MaxRetransmits="1" AllowChunking="false" /> </http-conf:conduit> </beans>
More information
12.2.3. Using WSDL
Namespace
http-conf
. In order to use the HTTP configuration elements you must add the line shown in Example 12.7, “HTTP Consumer WSDL Element's Namespace” to the definitions
element of your endpoint's WSDL document.
Example 12.7. HTTP Consumer WSDL Element's Namespace
<definitions ... xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
Jetty runtime or Netty runtime
http-conf
namespace to configure either the Jetty runtime or the Netty runtime.
The client element
http-conf:client
element is used to specify the connection properties of an HTTP consumer in a WSDL document. The http-conf:client
element is a child of the WSDL port
element. It has the same attributes as the client
element used in the configuration file. The attributes are described in Table 12.2, “HTTP Consumer Configuration Attributes”.
Example
Example 12.8. WSDL to Configure an HTTP Consumer Endpoint
<service ... > <port ... > <soap:address ... /> <http-conf:client CacheControl="no-cache" /> </port> </service>
12.2.4. Consumer Cache Control Directives
http-conf:client
Cache Control Directives” lists the cache control directives supported by an HTTP consumer.
Directive | Behavior |
---|---|
no-cache |
Caches cannot use a particular response to satisfy subsequent requests without first revalidating that response with the server. If specific response header fields are specified with this value, the restriction applies only to those header fields within the response. If no response header fields are specified, the restriction applies to the entire response.
|
no-store |
Caches must not store either any part of a response or any part of the request that invoked it.
|
max-age |
The consumer can accept a response whose age is no greater than the specified time in seconds.
|
max-stale |
The consumer can accept a response that has exceeded its expiration time. If a value is assigned to max-stale, it represents the number of seconds beyond the expiration time of a response up to which the consumer can still accept that response. If no value is assigned, the consumer can accept a stale response of any age.
|
min-fresh |
The consumer wants a response that is still fresh for at least the specified number of seconds indicated.
|
no-transform |
Caches must not modify media type or location of the content in a response between a provider and a consumer.
|
only-if-cached |
Caches should return only responses that are currently stored in the cache, and not responses that need to be reloaded or revalidated.
|
cache-extension |
Specifies additional extensions to the other cache directives. Extensions can be informational or behavioral. An extended directive is specified in the context of a standard directive, so that applications not understanding the extended directive can adhere to the behavior mandated by the standard directive.
|
12.3. Configuring a Service Provider
12.3.1. Mechanisms for a HTTP Service Provider
12.3.2. Using Configuration
Namespace
http-conf
. In order to use the HTTP configuration elements you must add the lines shown in Example 12.9, “HTTP Provider Configuration Namespace” to the beans
element of your endpoint's configuration file. In addition, you must add the configuration elements' namespace to the xsi:schemaLocation
attribute.
Example 12.9. HTTP Provider Configuration Namespace
<beans ... xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" ... xsi:schemaLocation="... http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd ...">
Jetty runtime or Netty runtime
http-conf
namespace to configure either the Jetty runtime or the Netty runtime.
The destination element
http-conf:destination
element and its children. The http-conf:destination
element takes a single attribute, name
, that specifies the WSDL port
element that corresponds to the endpoint. The value for the name
attribute takes the form portQName.http-destination
. Example 12.10, “http-conf:destination
Element” shows the http-conf:destination
element that is used to add configuration for an endpoint that is specified by the WSDL fragment <port binding="widgetSOAPBinding" name="widgetSOAPPort> when the endpoint's target namespace is http://widgets.widgetvendor.net.
Example 12.10. http-conf:destination
Element
... <http-conf:destination name="{http://widgets/widgetvendor.net}widgetSOAPPort.http-destination"> ... </http-conf:destination> ...
http-conf:destination
element has a number of child elements that specify configuration information. They are described in Table 12.4, “Elements Used to Configure an HTTP Service Provider Endpoint”.
Element | Description |
---|---|
http-conf:server |
Specifies the HTTP connection properties. See the section called “The server element”.
|
http-conf:contextMatchStrategy |
Specifies the parameters that configure the context match strategy for processing HTTP requests.
|
http-conf:fixedParameterOrder |
Specifies whether the parameter order of an HTTP request handled by this destination is fixed.
|
The server element
http-conf:server
element is used to configure the properties of a service provider endpoint's HTTP connection. Its attributes, described in Table 12.5, “HTTP Service Provider Configuration Attributes”, specify the connection's properties.
Attribute | Description |
---|---|
ReceiveTimeout |
Sets the length of time, in milliseconds, the service provider attempts to receive a request before the connection times out. The default is
30000 .
0 specifies that the provider will not timeout.
|
SuppressClientSendErrors |
Specifies whether exceptions are to be thrown when an error is encountered on receiving a request. The default is
false ; exceptions are thrown on encountering errors.
|
SuppressClientReceiveErrors |
Specifies whether exceptions are to be thrown when an error is encountered on sending a response to a consumer. The default is
false ; exceptions are thrown on encountering errors.
|
HonorKeepAlive |
Specifies whether the service provider honors requests for a connection to remain open after a response has been sent. The default is
false ; keep-alive requests are ignored.
|
RedirectURL |
Specifies the URL to which the client request should be redirected if the URL specified in the client request is no longer appropriate for the requested resource. In this case, if a status code is not automatically set in the first line of the server response, the status code is set to
302 and the status description is set to Object Moved . The value is used as the value of the HTTP RedirectURL property.
|
CacheControl |
Specifies directives about the behavior that must be adhered to by caches involved in the chain comprising a response from a service provider to a consumer. See Section 12.3.4, “Service Provider Cache Control Directives”.
|
ContentLocation |
Sets the URL where the resource being sent in a response is located.
|
ContentType |
Specifies the media type of the information being sent in a response. Media types are specified using multipurpose internet mail extensions (MIME) types. The value is used as the value of the HTTP ContentType location.
|
ContentEncoding |
Specifies any additional content encodings that have been applied to the information being sent by the service provider. Content encoding labels are regulated by the Internet Assigned Numbers Authority (IANA). Possible content encoding values include
zip , gzip , compress , deflate , and identity . This value is used as the value of the HTTP ContentEncoding property.
The primary use of content encodings is to allow documents to be compressed using some encoding mechanism, such as zip or gzip. Apache CXF performs no validation on content codings. It is the user’s responsibility to ensure that a specified content coding is supported at application level.
|
ServerType |
Specifies what type of server is sending the response. Values take the form
program-name/version ; for example, Apache/1.2.5 .
|
Example
Example 12.11. HTTP Service Provider Endpoint Configuration
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xsi:schemaLocation="http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <http-conf:destination name="{http://apache.org/hello_world_soap_http}SoapPort.http-destination"> <http-conf:server SuppressClientSendErrors="true" SuppressClientReceiveErrors="true" HonorKeepAlive="true" /> </http-conf:destination> </beans>
12.3.3. Using WSDL
Namespace
http-conf
. To use the HTTP configuration elements you must add the line shown in Example 12.12, “HTTP Provider WSDL Element's Namespace” to the definitions
element of your endpoint's WSDL document.
Example 12.12. HTTP Provider WSDL Element's Namespace
<definitions ... xmlns:http-conf="http://cxf.apache.org/transports/http/configuration"
Jetty runtime or Netty runtime
http-conf
namespace to configure either the Jetty runtime or the Netty runtime.
The server element
http-conf:server
element is used to specify the connection properties of an HTTP service provider in a WSDL document. The http-conf:server
element is a child of the WSDL port
element. It has the same attributes as the server
element used in the configuration file. The attributes are described in Table 12.5, “HTTP Service Provider Configuration Attributes”.
Example
Example 12.13. WSDL to Configure an HTTP Service Provider Endpoint
<service ... > <port ... > <soap:address ... /> <http-conf:server CacheControl="no-cache" /> </port> </service>
12.3.4. Service Provider Cache Control Directives
http-conf:server
Cache Control Directives” lists the cache control directives supported by an HTTP service provider.
Directive | Behavior |
---|---|
no-cache |
Caches cannot use a particular response to satisfy subsequent requests without first revalidating that response with the server. If specific response header fields are specified with this value, the restriction applies only to those header fields within the response. If no response header fields are specified, the restriction applies to the entire response.
|
public |
Any cache can store the response.
|
private |
Public (shared) caches cannot store the response because the response is intended for a single user. If specific response header fields are specified with this value, the restriction applies only to those header fields within the response. If no response header fields are specified, the restriction applies to the entire response.
|
no-store |
Caches must not store any part of the response or any part of the request that invoked it.
|
no-transform |
Caches must not modify the media type or location of the content in a response between a server and a client.
|
must-revalidate |
Caches must revalidate expired entries that relate to a response before that entry can be used in a subsequent response.
|
proxy-revalidate |
Does the same as must-revalidate, except that it can only be enforced on shared caches and is ignored by private unshared caches. When using this directive, the public cache directive must also be used.
|
max-age |
Clients can accept a response whose age is no greater that the specified number of seconds.
|
s-max-age |
Does the same as max-age, except that it can only be enforced on shared caches and is ignored by private unshared caches. The age specified by s-max-age overrides the age specified by max-age. When using this directive, the proxy-revalidate directive must also be used.
|
cache-extension |
Specifies additional extensions to the other cache directives. Extensions can be informational or behavioral. An extended directive is specified in the context of a standard directive, so that applications not understanding the extended directive can adhere to the behavior mandated by the standard directive.
|
12.4. Configuring the Jetty Runtime
Overview
Maven dependency
pom.xml
file:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>${cxf-version}</version> </dependency>
Namespace
httpj
. In order to use the Jetty configuration elements you must add the lines shown in Example 12.14, “Jetty Runtime Configuration Namespace” to the beans
element of your endpoint's configuration file. In addition, you must add the configuration elements' namespace to the xsi:schemaLocation
attribute.
Example 12.14. Jetty Runtime Configuration Namespace
<beans ... xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" ... xsi:schemaLocation="... http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd ...">
The engine-factory element
httpj:engine-factory
element is the root element used to configure the Jetty runtime used by an application. It has a single required attribute, bus
, whose value is the name of the Bus
that manages the Jetty instances being configured.
cxf
which is the name of the default Bus
instance.
httpj:engine-factory
element has three children that contain the information used to configure the HTTP ports instantiated by the Jetty runtime factory. The children are described in Table 12.7, “Elements for Configuring a Jetty Runtime Factory”.
Element | Description |
---|---|
httpj:engine |
Specifies the configuration for a particular Jetty runtime instance. See the section called “The engine element”.
|
httpj:identifiedTLSServerParameters |
Specifies a reusable set of properties for securing an HTTP service provider. It has a single attribute,
id , that specifies a unique identifier by which the property set can be referred.
|
httpj:identifiedThreadingParameters |
Specifies a reusable set of properties for controlling a Jetty instance's thread pool. It has a single attribute,
id , that specifies a unique identifier by which the property set can be referred.
|
The engine element
httpj:engine
element is used to configure specific instances of the Jetty runtime. It has a single attribute, port
, that specifies the number of the port being managed by the Jetty instance.
0
for the port
attribute. Any threading properties specified in an httpj:engine
element with its port
attribute set to 0
are used as the configuration for all Jetty listeners that are not explicitly configured.
httpj:engine
element can have two children: one for configuring security properties and one for configuring the Jetty instance's thread pool. For each type of configuration you can either directly provide the configuration information or you can provide a reference to a set of configuration properties defined in the parent httpj:engine-factory
element.
Element | Description |
---|---|
httpj:tlsServerParameters |
Specifies a set of properties for configuring the security used for the specific Jetty instance.
|
httpj:tlsServerParametersRef |
Refers to a set of security properties defined by a
identifiedTLSServerParameters element. The id attribute provides the id of the referred identifiedTLSServerParameters element.
|
httpj:threadingParameters |
Specifies the size of the thread pool used by the specific Jetty instance. See the section called “Configuring the thread pool”.
|
httpj:threadingParametersRef |
Refers to a set of properties defined by a
identifiedThreadingParameters element. The id attribute provides the id of the referred identifiedThreadingParameters element.
|
Configuring the thread pool
- Specifying the size of the thread pool using a
identifiedThreadingParameters
element in theengine-factory
element. You then refer to the element using athreadingParametersRef
element. - Specifying the size of the of the thread pool directly using a
threadingParameters
element.
threadingParameters
has two attributes to specify the size of a thread pool. The attributes are described in Table 12.9, “Attributes for Configuring a Jetty Thread Pool”.
httpj:identifiedThreadingParameters
element has a single child threadingParameters
element.
Example
Example 12.15. Configuring a Jetty Instance
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xsi:schemaLocation="http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> ... <httpj:engine-factory bus="cxf"> <httpj:identifiedTLSServerParameters id="secure"> <sec:keyManagers keyPassword="password"> <sec:keyStore type="JKS" password="password" file="certs/cherry.jks"/> </sec:keyManagers> </httpj:identifiedTLSServerParameters> <httpj:engine port="9001"> <httpj:tlsServerParametersRef id="secure" /> <httpj:threadingParameters minThreads="5" maxThreads="15" /> </httpj:engine> </httpj:engine-factory> </beans>
12.5. Configuring the Netty Runtime
Overview
Maven dependencies
pom.xml
file:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-netty-server</artifactId> <version>${cxf-version}</version> </dependency>
pom.xml
file:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-netty-client</artifactId> <version>${cxf-version}</version> </dependency>
Namespace
httpn
. In order to use the Netty configuration elements you must add the lines shown in Example 12.16, “Netty Runtime Configuration Namespace” to the beans
element of your endpoint's configuration file. In addition, you must add the configuration elements' namespace to the xsi:schemaLocation
attribute.
Example 12.16. Netty Runtime Configuration Namespace
<beans ... xmlns:httpn="http://cxf.apache.org/transports/http-netty-server/configuration" ... xsi:schemaLocation="... http://cxf.apache.org/transports/http-netty-server/configuration http://cxf.apache.org/schemas/configuration/http-netty-server.xsd ...">
The engine-factory element
httpn:engine-factory
element is the root element used to configure the Netty runtime used by an application. It has a single required attribute, bus
, whose value is the name of the Bus
that manages the Netty instances being configured.
cxf
, which is the name of the default Bus
instance.
httpn:engine-factory
element has three children that contain the information used to configure the HTTP ports instantiated by the Netty runtime factory. The children are described in Table 12.10, “Elements for Configuring a Netty Runtime Factory”.
Element | Description |
---|---|
httpn:engine |
Specifies the configuration for a particular Netty runtime instance. See the section called “The engine element”.
|
httpn:identifiedTLSServerParameters |
Specifies a reusable set of properties for securing an HTTP service provider. It has a single attribute,
id , that specifies a unique identifier by which the property set can be referred.
|
httpn:identifiedThreadingParameters |
Specifies a reusable set of properties for controlling a Netty instance's thread pool. It has a single attribute,
id , that specifies a unique identifier by which the property set can be referred.
|
The engine element
httpn:engine
element is used to configure specific instances of the Netty runtime. Table 12.11, “Attributes for Configuring a Netty Runtime Instance” shows the attributes supported by the httpn:engine
element.
Attribute | Description |
---|---|
port | Specifies the port used by the Netty HTTP server instance. You can specify a value of 0 for the port attribute. Any threading properties specified in an engine element with its port attribute set to 0 are used as the configuration for all Netty listeners that are not explicitly configured. |
host | Specifies the listen address used by the Netty HTTP server instance. The value can be a hostname or an IP address. If not specified, Netty HTTP server will listen on all local addresses. |
readIdleTime | Specifies the maximum read idle time for a Netty connection. The timer is reset whenever there are any read actions on the underlying stream. |
writeIdleTime | Specifies the maximum write idle time for a Netty connection. The timer is reset whenever there are any write actions on the underlying stream. |
maxChunkContentSize | Specifies the maximum aggregated content size for a Netty connection. The default value is 10MB. |
httpn:engine
element has one child element for configuring security properties and one child element for configuring the Netty instance's thread pool. For each type of configuration you can either directly provide the configuration information or you can provide a reference to a set of configuration properties defined in the parent httpn:engine-factory
element.
httpn:engine
are shown in Table 12.12, “Elements for Configuring a Netty Runtime Instance”.
Element | Description |
---|---|
httpn:tlsServerParameters |
Specifies a set of properties for configuring the security used for the specific Netty instance.
|
httpn:tlsServerParametersRef |
Refers to a set of security properties defined by a
identifiedTLSServerParameters element. The id attribute provides the id of the referred identifiedTLSServerParameters element.
|
httpn:threadingParameters |
Specifies the size of the thread pool used by the specific Netty instance. See the section called “Configuring the thread pool”.
|
httpn:threadingParametersRef |
Refers to a set of properties defined by a
identifiedThreadingParameters element. The id attribute provides the id of the referred identifiedThreadingParameters element.
|
httpn:sessionSupport | When true , enables support for HTTP sessions. Default is false . |
httpn:reuseAddress | Specifies a boolean value to set the ReuseAddress TCP socket option. Default is false . |
Configuring the thread pool
- Specifying the size of the thread pool using a
identifiedThreadingParameters
element in theengine-factory
element. You then refer to the element using athreadingParametersRef
element. - Specifying the size of the of the thread pool directly using a
threadingParameters
element.
threadingParameters
element has one attribute to specify the size of a thread pool, as described in Table 12.13, “Attributes for Configuring a Netty Thread Pool”.
httpn:identifiedThreadingParameters
element has a single child threadingParameters
element.
Attribute | Description |
---|---|
threadPoolSize |
Specifies the number of threads available to the Netty instance for processing requests.
|
Example
Example 12.17. Configuring a Netty Instance
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:h="http://cxf.apache.org/transports/http/configuration" xmlns:httpn="http://cxf.apache.org/transports/http-netty-server/configuration" xmlns:sec="http://cxf.apache.org/configuration/security" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/transports/http-netty-server/configuration http://cxf.apache.org/schemas/configuration/http-netty-server.xsd" > ... <httpn:engine-factory bus="cxf"> <httpn:identifiedTLSServerParameters id="sample1"> <httpn:tlsServerParameters jsseProvider="SUN" secureSocketProtocol="TLS"> <sec:clientAuthentication want="false" required="false"/> </httpn:tlsServerParameters> </httpn:identifiedTLSServerParameters> <httpn:identifiedThreadingParameters id="sampleThreading1"> <httpn:threadingParameters threadPoolSize="120"/> </httpn:identifiedThreadingParameters> <httpn:engine port="9000" readIdleTime="30000" writeIdleTime="90000"> <httpn:threadingParametersRef id="sampleThreading1"/> </httpn:engine> <httpn:engine port="0"> <httpn:threadingParameters threadPoolSize="400"/> </httpn:engine> <httpn:engine port="9001" readIdleTime="40000" maxChunkContentSize="10000"> <httpn:threadingParameters threadPoolSize="99" /> <httpn:sessionSupport>true</httpn:sessionSupport> </httpn:engine> <httpn:engine port="9002"> <httpn:tlsServerParameters> <sec:clientAuthentication want="true" required="true"/> </httpn:tlsServerParameters> </httpn:engine> <httpn:engine port="9003"> <httpn:tlsServerParametersRef id="sample1"/> </httpn:engine> </httpn:engine-factory> </beans>
12.6. Using the HTTP Transport in Decoupled Mode
Overview
200
.
202 Accepted
response to the consumer over the back-channel of the HTTP connection on which the request was received. It then processes the request and sends the response back to the consumer using a new decoupled server->client HTTP connection. The consumer runtime receives the incoming response and correlates it with the appropriate request before returning to the application code.
Configuring decoupled interactions
- Configure the consumer to use WS-Addressing.
- Configure the consumer to use a decoupled endpoint.
- Configure any service providers that the consumer interacts with to use WS-Addressing.
Configuring an endpoint to use WS-Addressing
- Adding the
wswa:UsingAddressing
element to the endpoint's WSDLport
element as shown in Example 12.18, “Activating WS-Addressing using WSDL”.Example 12.18. Activating WS-Addressing using WSDL
... <service name="WidgetSOAPService"> <port name="WidgetSOAPPort" binding="tns:WidgetSOAPBinding"> <soap:address="http://widgetvendor.net/widgetSeller" /> <wswa:UsingAddressing xmlns:wswa="http://www.w3.org/2005/02/addressing/wsdl"/> </port> </service> ...
- Adding the WS-Addressing policy to the endpoint's WSDL
port
element as shown in Example 12.19, “Activating WS-Addressing using a Policy”.Example 12.19. Activating WS-Addressing using a Policy
... <service name="WidgetSOAPService"> <port name="WidgetSOAPPort" binding="tns:WidgetSOAPBinding"> <soap:address="http://widgetvendor.net/widgetSeller" /> <wsp:Policy xmlns:wsp="http://www.w3.org/2006/07/ws-policy"> <wsam:Addressing xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsp:Policy/> </wsam:Addressing> </wsp:Policy> </port> </service> ...
wswa:UsingAddressing
WSDL element.
Configuring the consumer
DecoupledEndpoint
attribute of the http-conf:conduit
element.
Example 12.20. Configuring a Consumer to Use a Decoupled HTTP Endpoint
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:http="http://cxf.apache.org/transports/http/configuration" xsi:schemaLocation="http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <http:conduit name="{http://widgetvendor.net/services}WidgetSOAPPort.http-conduit"> <http:client DecoupledEndpoint="http://widgetvendor.net:9999/decoupled_endpoint" /> </http:conduit> </beans>
How messages are processed
Figure 12.1. Message Flow in for a Decoupled HTTP Transport
- The consumer implementation invokes an operation and a request message is generated.
- The WS-Addressing layer adds the WS-A headers to the message.When a decoupled endpoint is specified in the consumer's configuration, the address of the decoupled endpoint is placed in the WS-A ReplyTo header.
- The message is sent to the service provider.
- The service provider receives the message.
- The request message from the consumer is dispatched to the provider's WS-A layer.
- Because the WS-A ReplyTo header is not set to anonymous, the provider sends back a message with the HTTP status code set to
202
, acknowledging that the request has been received. - The HTTP layer sends a
202 Accepted
message back to the consumer using the original connection's back-channel. - The consumer receives the
202 Accepted
reply on the back-channel of the HTTP connection used to send the original message.When the consumer receives the202 Accepted
reply, the HTTP connection closes. - The request is passed to the service provider's implementation where the request is processed.
- When the response is ready, it is dispatched to the WS-A layer.
- The WS-A layer adds the WS-Addressing headers to the response message.
- The HTTP transport sends the response to the consumer's decoupled endpoint.
- The consumer's decoupled endpoint receives the response from the service provider.
- The response is dispatched to the consumer's WS-A layer where it is correlated to the proper request using the WS-A RelatesTo header.
- The correlated response is returned to the client implementation and the invoking call is unblocked.
Chapter 13. Using SOAP Over JMS
Abstract
13.1. Basic configuration
Overview
- Specify that the transport type is SOAP/JMS.
- Specify the target destination using a JMS URI.
- Optionally, configure the JNDI connection.
- Optionally, add additional JMS configuration.
Specifying the JMS transport type
soap:binding
element's transport
attribute to http://www.w3.org/2010/soapjms/
. Example 13.1, “SOAP over JMS binding specification” shows a WSDL binding that uses SOAP/JMS.
Example 13.1. SOAP over JMS binding specification
<wsdl:binding ... > <soap:binding style="document" transport="http://www.w3.org/2010/soapjms/" /> ... </wsdl:binding>
Specifying the target destination
soap:address
element and attribute as a SOAP/HTTP endpoint. The difference is the address specification. JMS endpoints use a JMS URI as defined in the URI Scheme for JMS 1.0. Example 13.2, “JMS URI syntax” shows the syntax for a JMS URI.
Example 13.2. JMS URI syntax
jms:variant:destination?options
Variant | Description |
---|---|
jndi | Specifies that the destination name is a JNDI queue name. When using this variant, you must provide the configuration for accessing the JNDI provider. |
jndi-topic | Specifies that the destination name is a JNDI topic name. When using this variant, you must provide the configuration for accessing the JNDI provider. |
queue | Specifies that the destination is a queue name resolved using JMS. The string provided is passed into Session.createQueue() to create a representation of the destination. |
topic | Specifies that the destination is a topic name resolved using JMS. The string provided is passed into Session.createTopic() to create a representation of the destination. |
Example 13.3. SOAP/JMS endpoint address
<wsdl:port ... > ... <soap:address location="jms:jndi:dynamicQueues/test.cxf.jmstransport.queue" /> </wsdl:port>
Configuring JNDI and the JMS transport
13.2. JMS URIs
Overview
Syntax
?
). Multiple options are separated by an ampersand(&
). Example 13.4, “Syntax for JMS URI options” shows the syntax for using multiple options in a JMS URI.
Example 13.4. Syntax for JMS URI options
jms:variant:jmsAddress?option1=value1&option2=value2&...optionN=valueN
JMS properties
Property | Default | Description |
---|---|---|
conduitIdSelectorPrefix | [Optional] A string value that is prefixed to all correlation IDs that the conduit creates. The selector can use it to listen for replies. | |
deliveryMode | PERSISTENT | Specifies whether to use JMS PERSISTENT or NON_PERSISTENT message semantics. In the case of PERSISTENT delivery mode, the JMS broker stores messages in persistent storage before acknowledging them; whereas NON_PERSISTENT messages are kept in memory only. |
durableSubscriptionClientID | [Optional] Specifies the client identifier for the connection. This property is used to associate a connection with a state that the provider maintains on behalf of the client. This enables subsequent subscribers with the same identity to resume the subscription in the state that the preceding subscriber left it. | |
durableSubscriptionName | [Optional] Specifies the name of the subscription. | |
messageType | byte |
Specifies the JMS message type used by CXF. Valid values are:
|
password | [Optional] Specifies the password for creating the connection. Appending this property to the URI is discouraged. | |
priority | 4 | Specifies the JMS message priority, which ranges from 0 (lowest) to 9 (highest). |
receiveTimout | 60000 | Specifies the time, in milliseconds, the client will wait for a reply when request/reply exchanges are used. |
reconnectOnException | true |
[Deprecated in CXF 3.0] Specifies whether the transport should reconnect when exceptions occur.
As of 3.0, the transport will always reconnect when an exception occurs.
|
replyToName |
[Optional] Specifies the reply destination for queue messages. The reply destination appears in the
JMSReplyTo header. Setting this property is recommended for applications that have request-reply semantics because the JMS provider will assign a temporary reply queue if one is not specified.
The value of this property is interpreted according to the variant specified in the JMS URI:
| |
sessionTransacted | false |
Specifies the transaction type. Valid values are:
|
timeToLive | 0 | Specifies the time, in milliseconds, after which the JMS provider will discard the message. A value of 0 indicates an infinite lifetime. |
topicReplyToName |
[Optional] Specifies the reply destination for topic messages. The value of this property is interpreted according to the variant specified in the JMS URI:
| |
useConduitIdSelector | true |
Specifies whether the conduit's UUID will be used as the prefix for all correlation IDs.
As all conduits are assigned a unique UUID, setting this property to
true enables multiple endpoints to share a JMS queue or topic.
|
username | [Optional] Specifies the username to use to create the connection. |
JNDI properties
Property | Description |
---|---|
jndiConnectionFactoryName | Specifies the JNDI name of the JMS connection factory. |
jndiInitialContextFactory | Specifies the fully qualified Java class name of the JNDI provider (which must be of javax.jms.InitialContextFactory type). Equivalent to setting the java.naming.factory.initial Java system property. |
jndiTransactionManagerName | Specifies the name of the JTA transaction manager that will be searched for in Spring, Blueprint, or JNDI. If a transaction manager is found, JTA transactions will be enabled. See the sessionTransacted JMS property. |
jndiURL | Specifies the URL that initializes the JNDI provider. Equivalent to setting the java.naming.provider.url Java system property. |
Additional JNDI properties
java.naming.factory.initial
and java.naming.provider.url
, are standard properties, which are required to initialize any JNDI provider. Sometimes, however, a JNDI provider might support custom properties in addition to the standard ones. In this case, you can set an arbitrary JNDI property by setting a URI option of the form jndi-PropertyName
.
java.naming.factory.control
, in a JMS URI as shown in Example 13.5, “Setting a JNDI property in a JMS URI”.
Example 13.5. Setting a JNDI property in a JMS URI
jms:queue:FOO.BAR?jndi-java.naming.factory.control=com.sun.jndi.ldap.ResponseControlFactory
Example
test.cxf.jmstransport.queue
, use the URI shown in Example 13.6, “JMS URI that configures a JNDI connection”.
Example 13.6. JMS URI that configures a JNDI connection
jms:jndi:dynamicQueues/test.cxf.jmstransport.queue ?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory &jndiConnectionFactoryName=ConnectionFactory &jndiURL=tcp://localhost:61616
Publishing a service
publish()
method cannot be used to publish a SOAP/JMS service. Instead, you must use the Apache CXF's JaxWsServerFactoryBean
class as shown in Example 13.7, “Publishing a SOAP/JMS service”.
Example 13.7. Publishing a SOAP/JMS service
1String address = "jms:jndi:dynamicQueues/test.cxf.jmstransport.queue3" + "?jndiInitialContextFactory" + "=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&jndiConnectionFactoryName=ConnectionFactory" + "&jndiURL=tcp://localhost:61500"; Hello implementor = new HelloImpl(); 2JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean(); svrFactory.setServiceClass(Hello.class); 3svrFactory.setAddress(address); 4svrFactory.setTransportId(JMSSpecConstants.SOAP_JMS_SPECIFICIATION_TRANSPORTID); svrFactory.setServiceBean(implementor); svrFactory.create();
Consuming a service
JaxWsProxyFactoryBean
class as shown in Example 13.8, “Consuming a SOAP/JMS service”.
Example 13.8. Consuming a SOAP/JMS service
// Java public void invoke() throws Exception { 1 String address = "jms:jndi:dynamicQueues/test.cxf.jmstransport.queue3" + "?jndiInitialContextFactory" + "=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&jndiConnectionFactoryName=ConnectionFactory&jndiURL=tcp://localhost:61500"; 2 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); 3 factory.setAddress(address); 4 factory.setTransportId(JMSSpecConstants.SOAP_JMS_SPECIFICIATION_TRANSPORTID); factory.setServiceClass(Hello.class); Hello client = (Hello)factory.create(); String reply = client.sayHi(" HI"); System.out.println(reply); }
13.3. WSDL extensions
Overview
InitialContext
, which can then be used to look up JMS destinations. You can also set some properties that affect the behavior of the JMS transport layer.
SOAP/JMS namespace
http://www.w3.org/2010/soapjms/
namespace. To use them in your WSDL contracts add the following setting to the wsdl:definitions
element:
<wsdl:definitions ... xmlns:soapjms="http://www.w3.org/2010/soapjms/" ... >
WSDL extension elements
Element | Default | Description |
---|---|---|
soapjms:jndiInitialContextFactory | Specifies the fully qualified Java class name of the JNDI provider. Equivalent to setting the java.naming.factory.initial Java system property. | |
soapjms:jndiURL | Specifies the URL that initializes the JNDI provider. Equivalent to setting the java.naming.provider.url Java system property. | |
soapjms:jndiContextParameter | Specifies an additional property for creating the JNDI InitialContext . Use the name and value attributes to specify the property. | |
soapjms:jndiConnectionFactoryName | Specifies the JNDI name of the JMS connection factory. | |
soapjms:deliveryMode | PERSISTENT | Specifies whether to use JMS PERSISTENT or NON_PERSISTENT message semantics. In the case of PERSISTENT delivery mode, the JMS broker stores messages in persistent storage before acknowledging them; whereas NON_PERSISTENT messages are kept in memory only. |
soapjms:replyToName |
[Optional] Specifies the reply destination for queue messages. The reply destination appears in the
JMSReplyTo header. Setting this property is recommended for applications that have request-reply semantics because the JMS provider will assign a temporary reply queue if one is not specified.
The value of this property is interpreted according to the variant specified in the JMS URI:
| |
soapjms:priority | 4 | Specifies the JMS message priority, which ranges from 0 (lowest) to 9 (highest). |
soapjms:timeToLive | 0 | Time, in milliseconds, after which the JMS provider will discard the message. A value of 0 represents an infinite lifetime. |
Configuration scopes
wsdl:binding
element, the wsdl:service
element, or the wsdl:port
element. The parent of the SOAP/JMS elements determine which of the following scopes the configuration is placed into.
- Binding scope
- You can configure the JMS transport at the binding scope by placing extension elements inside the
wsdl:binding
element. Elements in this scope define the default configuration for all endpoints that use this binding. Any settings in the binding scope can be overridden at the service scope or the port scope. - Service scope
- You can configure the JMS transport at the service scope by placing extension elements inside a
wsdl:service
element. Elements in this scope define the default configuration for all endpoints in this service. Any settings in the service scope can be overridden at the port scope. - Port scope
- You can configure the JMS transport at the port scope by placing extension elements inside a
wsdl:port
element. Elements in the port scope define the configuration for this port. They override the defaults of the same extension elements defined at the service scope or at the binding scope.
Example
Example 13.9. WSDL contract with SOAP/JMS configuration
<wsdl:definitions ... 1 xmlns:soapjms="http://www.w3.org/2010/soapjms/" ... > ... <wsdl:binding name="JMSGreeterPortBinding" type="tns:JMSGreeterPortType"> ... 2 <soapjms:jndiInitialContextFactory> org.apache.activemq.jndi.ActiveMQInitialContextFactory </soapjms:jndiInitialContextFactory> <soapjms:jndiURL>tcp://localhost:61616</soapjms:jndiURL> <soapjms:jndiConnectionFactoryName> ConnectionFactory </soapjms:jndiConnectionFactoryName> ... </wsdl:binding> ... <wsdl:service name="JMSGreeterService"> ... 3 <soapjms:deliveryMode>NON_PERSISTENT</soapjms:deliveryMode> <soapjms:timeToLive>60000</soapjms:timeToLive> ... <wsdl:port binding="tns:JMSGreeterPortBinding" name="GreeterPort"> 4 <soap:address location="jms:jndi:dynamicQueues/test.cxf.jmstransport.queue" /> 5 <soapjms:replyToName> dynamicQueues/greeterReply.queue </soapjms:replyToName> ... </wsdl:port> ... </wsdl:service> ... </wsdl:definitions>
- 1
- Declares the namespace for the SOAP/JMS extensions.
- 2
- Configures the JNDI connections in the binding scope.
- 3
- Sets the JMS delivery style to non-persistent and each message to live for one minute.
- 4
- Specifies the target destination.
- 5
- Configures the JMS transport so that reply messages are delivered on the
greeterReply.queue
queue.
Chapter 14. Using Generic JMS
Abstract
14.1. Approaches to Configuring JMS
TextMessage
or ByteMessage
.
14.2. Using the JMS configuration bean
Overview
org.apache.cxf.transport.jms.JMSConfiguration
class. It can be used to either configure endpoint's directly or to configure the JMS conduits and destinations.
Configuration namespace
Example 14.1. Declaring the Spring p-namespace
<beans ... xmlns:p="http://www.springframework.org/schema/p" ... > ... </beans>
Specifying the configuration
org.apache.cxf.transport.jms.JMSConfiguration
. The properties of the bean provide the configuration settings for the transport.
Property | Default | Description |
---|---|---|
connectionFactory | [Required] Specifies a reference to a bean that defines a JMS ConnectionFactory . | |
wrapInSingleConnectionFactory | true [pre v3.0] |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies whether to wrap the
ConnectionFactory with a Spring SingleConnectionFactory .
Enable this property when using a
ConnectionFactory that does not pool connections, as it will improve the performance of the JMS transport. This is so because the JMS transport creates a new connection for each message, and the SingleConnectionFactory is needed to cache the connection, so it can be reused.
|
reconnectOnException | false |
[Deprecated in CXF 3.0] CXF always reconnects when an exception occurs.
[pre CXF 3.0] Specifies whether to create a new connection when an exception occurs.
When wrapping the
ConnectionFactory with a Spring SingleConnectionFactory :
|
targetDestination | Specifies the JNDI name or provider-specific name of a destination. | |
replyDestination | Specifies the JMS name of the JMS destination where replies are sent. This property allows the use of a user-defined destination for replies. For more details see Section 14.6, “Using a Named Reply Destination”. | |
destinationResolver | DynamicDestinationResolver |
Specifies a reference to a Spring
DestinationResolver .
This property allows you to define how destination names are resolved to JMS destinations. Valid values are:
|
transactionManager | Specifies a reference to a Spring transaction manager. This enables the service to participate in JTA transactions. | |
taskExecutor | SimpleAsyncTaskExecutor |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies a reference to a Spring
TaskExecutor . This is used in listeners to decide how to handle incoming messages.
|
useJms11 | false |
[Removed in CXF 3.0] CXF 3.0 supports JMS 1.1 features only.
[pre CXF 3.0] Specifies whether JMS 1.1 features are used. Valid values are:
|
messageIdEnabled | true |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies whether the JMS transport wants the JMS broker to provide message IDs. Valid values are:
|
messageTimestampEnabled | true |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies whether the JMS transport wants the JMS broker to provide message time stamps. Valid values are:
|
cacheLevel | -1 (feature disabled) |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies the level of caching that the JMS listener container may apply. Valid values are:
For details, see Class DefaultMessageListenerContainer
|
pubSubNoLocal | false
|
Specifies whether to receive your own messages when using topics.
|
receiveTimeout | 60000
| Specifies the time, in milliseconds, to wait for response messages. |
explicitQosEnabled | false | Specifies whether the QoS settings (such as priority, persistence, time to live) are explicitly set for each message (true ) or use the default values (false ). |
deliveryMode | 2 |
Specifies whether a message is persistent. Valid values are:
|
priority | 4 | Specifies message priority. JMS priority values range from 0 (lowest) to 9 (highest). See your JMS provider's documentation for details. |
timeToLive | 0 (indefinitely) | Specifies the time, in milliseconds, before a message that has been sent is discarded. |
sessionTransacted | false | Specifies whether JMS transactions are used. |
concurrentConsumers | 1 |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies the minimum number of concurrent consumers for the listener.
|
maxConcurrentConsumers | 1 |
[Removed in CXF 3.0]
[pre CXF 3.0] Specifies the maximum number of concurrent consumers for the listener.
|
messageSelector | Specifies the string value of the selector used to filter incoming messages. This property enables multiple connections to share a queue. For more information on the syntax used to specify message selectors, see the JMS 1.1 specification. | |
subscriptionDurable | false | Specifies whether the server uses durable subscriptions. |
durableSubscriptionName | Specifies the name (string) used to register the durable subscription. | |
messageType | text |
Specifies how the message data will be packaged as a JMS message. Valid values are:
|
pubSubDomain | false |
Specifies whether the target destination is a topic or a queue. Valid values are:
|
jmsProviderTibcoEms | false |
Specifies whether the JMS provider is Tibco EMS.
When set to
true , the principal in the security context is populated from the JMS_TIBCO_SENDER header.
|
useMessageIDAsCorrelationID | false |
[Removed in CXF 3.0]
Specifies whether JMS will use the message ID to correlate messages.
When set to
true , the client sets a generated correlation ID.
|
maxSuspendedContinuations | -1 (feature disabled) |
[CXF 3.0] Specifies the maximum number of suspended continuations the JMS destination may have. When the current number exceeds the specified maximum, the JMSListenerContainer is stopped.
|
reconnectPercentOfMax | 70 |
[CXF 3.0] Specifies when to restart the JMSListenerContainer stopped for exceeding
maxSuspendedContinuations .
The listener container is restarted when its current number of suspended continuations falls below the value of
(maxSuspendedContinuations * reconnectPercentOfMax/100) .
|
bean
element. They are all declared in the Spring p
namespace.
Example 14.2. JMS configuration bean
<bean id="jmsConfig" class="org.apache.cxf.transport.jms.JMSConfiguration" p:connectionFactory="jmsConnectionFactory" p:targetDestination="dynamicQueues/greeter.request.queue" p:pubSubDomain="false" />
Applying the configuration to an endpoint
JMSConfiguration
bean can be applied directly to both server and client endpoints using the Apache CXF features mechanism. To do so:
- Set the endpoint's
address
attribute tojms://
. - Add a
jaxws:feature
element to the endpoint's configuration. - Add a bean of type
org.apache.cxf.transport.jms.JMSConfigFeature
to the feature. - Set the
bean
element'sp:jmsConfig-ref
attribute to the ID of theJMSConfiguration
bean.
Example 14.3. Adding JMS configuration to a JAX-WS client
<jaxws:client id="CustomerService" xmlns:customer="http://customerservice.example.com/" serviceName="customer:CustomerServiceService" endpointName="customer:CustomerServiceEndpoint" address="jms://" serviceClass="com.example.customerservice.CustomerService"> <jaxws:features> <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.cxf.transport.jms.JMSConfigFeature" p:jmsConfig-ref="jmsConfig"/> </jaxws:features> </jaxws:client>
Applying the configuration to the transport
JMSConfiguration
bean can be applied to JMS conduits and JMS destinations using the jms:jmsConfig-ref
element. The jms:jmsConfig-ref
element's value is the ID of the JMSConfiguration
bean.
Example 14.4. Adding JMS configuration to a JMS conduit
<jms:conduit name="{http://cxf.apache.org/jms_conf_test}HelloWorldQueueBinMsgPort.jms-conduit"> ... <jms:jmsConfig-ref>jmsConf</jms:jmsConfig-ref> </jms:conduit>
14.3. Optimizing Client-Side JMS Performance
Overview
Pooling
import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.pool.PooledConnectionFactory; ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); PooledConnectionFactory pcf = new PooledConnectionFactory(); //Set expiry timeout because the default (0) prevents reconnection on failure pcf.setExpiryTimeout(5000); pcf.setConnectionFactory(cf); JMSConfiguration jmsConfig = new JMSConfiguration(); jmsConfig.setConnectionFactory(pdf);
Avoiding synchronous receives
MessageListener
.
Consumer.receive()
method when it needs to share queues between endpoints. This scenario requires the MessageListener
to use a message selector to filter the messages. The message selector must be known in advance, so the MessageListener
is opened only once.
- When JMSMessageID is used as the JMSCorrelationIDIf the JMS properties useConduitIdSelector and conduitSelectorPrefix are not set on the JMS transport, the client does not set a JMSCorrelationId. This causes the server to use the JMSMessageId of the request message as the JMSCorrelationId. As JMSMessageID cannot be known in advance, the client has to use a synchronous
Consumer.receive()
method.Note that you must use theConsumer.receive()
method with IBM JMS endpoints (their default). - The user sets the JMStype in the request message and then sets a custom JMSCorrelationID.Again, as the custom JMSCorrelationID cannot be known in advance, the client has to use a synchronous
Consumer.receive()
method.
14.4. Configuring JMS Transactions
Overview
Local transactions
true
.
JTA transactions
- Defining a transaction manager
- bean method
- Define a transaction manager
<bean id="transactionManager" class="org.apache.geronimo.transaction.manager.GeronimoTransactionManager"/>
- Set the name of the transaction manager in the JMS URI
jms:queue:myqueue?jndiTransactionManager=TransactionManager
This example finds a bean with the IDTransactionManager
.
- OSGi reference method
- Look up the transaction manager as an OSGi service using Blueprint
<reference id="TransactionManager" interface="javax.transaction.TransactionManager"/>
- Set the name of the transaction manager in the JMS URI
jms:jndi:myqueue?jndiTransactionManager=java:comp/env/TransactionManager
This example looks up the transaction manager in JNDI.
- Configuring a JCA pooled connection factoryUsing Spring to define the JCA pooled connection factory:
<bean id="xacf" class="org.apache.activemq.ActiveMQXAConnectionFactory"> <property name="brokerURL" value="tcp://localhost:61616" /> </bean> <bean id="ConnectionFactory" class="org.apache.activemq.jms.pool.JcaPooledConnectionFactory"> <property name="transactionManager" ref="transactionManager" /> <property name="connectionFactory" ref="xacf" /> </bean>
In this example, the first bean defines an ActiveMQ XA connection factory, which is given to aJcaPooledConnectionFactory
. TheJcaPooledConnectionFactory
is then provided as the default bean with idConnectionFactory
.Note that theJcaPooledConnectionFactory
looks like a normal ConnectionFactory. But when a new connection and session are opened, it checks for an XA transaction and, if found, automatically registers the JMS session as an XA resource. This allows the JMS session to participate in the JMS transaction.ImportantDirectly setting an XA ConnectionFactory on the JMS transport will not work!
14.5. Using WSDL to configure JMS
14.5.1. JMS WSDL Extension Namespance
Example 14.5. JMS WSDL extension namespace
xmlns:jms="http://cxf.apache.org/transports/jms"
14.5.2. Basic JMS configuration
Overview
jms:address
element and its child, the jms:JMSNamingProperties
element. The jms:address
element’s attributes specify the information needed to identify the JMS broker and the destination. The jms:JMSNamingProperties
element specifies the Java properties used to connect to the JNDI service.
Specifying the JMS address
jms:address
element as the child of your service’s port
element. The jms:address
element used in WSDL is identical to the one used in the configuration file. Its attributes are listed in Table 14.2, “JMS endpoint attributes”.
Attribute | Description |
---|---|
destinationStyle | Specifies if the JMS destination is a JMS queue or a JMS topic. |
jndiConnectionFactoryName | Specifies the JNDI name bound to the JMS connection factory to use when connecting to the JMS destination. |
jmsDestinationName | Specifies the JMS name of the JMS destination to which requests are sent. |
jmsReplyDestinationName | Specifies the JMS name of the JMS destinations where replies are sent. This attribute allows you to use a user defined destination for replies. For more details see Section 14.6, “Using a Named Reply Destination”. |
jndiDestinationName | Specifies the JNDI name bound to the JMS destination to which requests are sent. |
jndiReplyDestinationName | Specifies the JNDI name bound to the JMS destinations where replies are sent. This attribute allows you to use a user defined destination for replies. For more details see Section 14.6, “Using a Named Reply Destination”. |
connectionUserName | Specifies the user name to use when connecting to a JMS broker. |
connectionPassword | Specifies the password to use when connecting to a JMS broker. |
jms:address
WSDL element uses a jms:JMSNamingProperties
child element to specify additional information needed to connect to a JNDI provider.
Specifying JNDI properties
jms:address
element has a child element, jms:JMSNamingProperties
, that allows you to specify the values used to populate the properties used when connecting to the JNDI provider. The jms:JMSNamingProperties
element has two attributes: name
and value
. name
specifies the name of the property to set. value
attribute specifies the value for the specified property. jms:JMSNamingProperties
element can also be used for specification of provider specific properties.
java.naming.factory.initial
java.naming.provider.url
java.naming.factory.object
java.naming.factory.state
java.naming.factory.url.pkgs
java.naming.dns.url
java.naming.authoritative
java.naming.batchsize
java.naming.referral
java.naming.security.protocol
java.naming.security.authentication
java.naming.security.principal
java.naming.security.credentials
java.naming.language
java.naming.applet
Example
port
specification.
Example 14.6. JMS WSDL port specification
<service name="JMSService"> <port binding="tns:Greeter_SOAPBinding" name="SoapPort"> <jms:address jndiConnectionFactoryName="ConnectionFactory" jndiDestinationName="dynamicQueues/test.Celtix.jmstransport" > <jms:JMSNamingProperty name="java.naming.factory.initial" value="org.activemq.jndi.ActiveMQInitialContextFactory" /> <jms:JMSNamingProperty name="java.naming.provider.url" value="tcp://localhost:61616" /> </jms:address> </port> </service>
14.5.3. JMS client configuration
Overview
ByteMessage
or a JMS TextMessage
.
ByteMessage
the consumer endpoint uses a byte[] as the method for storing data into and retrieving data from the JMS message body. When messages are sent, the message data, including any formating information, is packaged into a byte[] and placed into the message body before it is placed on the wire. When messages are received, the consumer endpoint will attempt to unmarshall the data stored in the message body as if it were packed in a byte[].
TextMessage
, the consumer endpoint uses a string as the method for storing and retrieving data from the message body. When messages are sent, the message information, including any format-specific information, is converted into a string and placed into the JMS message body. When messages are received the consumer endpoint will attempt to unmarshall the data stored in the JMS message body as if it were packed into a string.
TextMessage
, the receiving JMS application will get a text message containing all of the SOAP envelope information.
Specifying the message type
jms:client
element. The jms:client
element is a child of the WSDL port
element and has one attribute:
Example
Example 14.7. WSDL for a JMS consumer endpoint
<service name="JMSService"> <port binding="tns:Greeter_SOAPBinding" name="SoapPort"> <jms:address jndiConnectionFactoryName="ConnectionFactory" jndiDestinationName="dynamicQueues/test.Celtix.jmstransport" > <jms:JMSNamingProperty name="java.naming.factory.initial" value="org.activemq.jndi.ActiveMQInitialContextFactory" /> <jms:JMSNamingProperty name="java.naming.provider.url" value="tcp://localhost:61616" /> </jms:address> <jms:client messageType="binary" /> </port> </service>
14.5.4. JMS provider configuration
Overview
- how messages are correlated
- the use of durable subscriptions
- if the service uses local JMS transactions
- the message selectors used by the endpoint
Specifying the configuration
jms:server
element. The jms:server
element is a child of the WSDL wsdl:port
element and has the following attributes:
Attribute | Description |
---|---|
useMessageIDAsCorrealationID | Specifies whether JMS will use the message ID to correlate messages. The default is false . |
durableSubscriberName | Specifies the name used to register a durable subscription. |
messageSelector | Specifies the string value of a message selector to use. For more information on the syntax used to specify message selectors, see the JMS 1.1 specification. |
transactional | Specifies whether the local JMS broker will create transactions around message processing. The default is false . [a] |
Example
Example 14.8. WSDL for a JMS provider endpoint
<service name="JMSService"> <port binding="tns:Greeter_SOAPBinding" name="SoapPort"> <jms:address jndiConnectionFactoryName="ConnectionFactory" jndiDestinationName="dynamicQueues/test.Celtix.jmstransport" > <jms:JMSNamingProperty name="java.naming.factory.initial" value="org.activemq.jndi.ActiveMQInitialContextFactory" /> <jms:JMSNamingProperty name="java.naming.provider.url" value="tcp://localhost:61616" /> </jms:address> <jms:server messageSelector="cxf_message_selector" useMessageIDAsCorrelationID="true" transactional="true" durableSubscriberName="cxf_subscriber" /> </port> </service>
14.6. Using a Named Reply Destination
Overview
Setting the reply destination name
jmsReplyDestinationName
attribute or the jndiReplyDestinationName
attribute in the endpoint's JMS configuration. A client endpoint will listen for replies on the specified destination and it will specify the value of the attribute in the ReplyTo
field of all outgoing requests. A service endpoint will use the value of the jndiReplyDestinationName
attribute as the location for placing replies if there is no destination specified in the request’s ReplyTo
field.
Example
Example 14.9. JMS Consumer Specification Using a Named Reply Queue
<jms:conduit name="{http://cxf.apache.org/jms_endpt}HelloWorldJMSPort.jms-conduit">
<jms:address destinationStyle="queue"
jndiConnectionFactoryName="myConnectionFactory"
jndiDestinationName="myDestination"
jndiReplyDestinationName="myReplyDestination" >
<jms:JMSNamingProperty name="java.naming.factory.initial"
value="org.apache.cxf.transport.jms.MyInitialContextFactory" />
<jms:JMSNamingProperty name="java.naming.provider.url"
value="tcp://localhost:61616" />
</jms:address>
</jms:conduit>
Appendix A. Integrating with Apache ActiveMQ
Overview
The initial context factory
ActiveMQInitialContextFactory
class. This class is used to create a JNDI InitialContext
instance, which you can then use to access JMS destinations in the JMS broker.
InitialContext
that is integrated with Apache ActiveMQ.
Example A.1. SOAP/JMS WSDL to connect to Apache ActiveMQ
<soapjms:jndiInitialContextFactory> org.apache.activemq.jndi.ActiveMQInitialContextFactory </soapjms:jndiInitialContextFactory> <soapjms:jndiURL>tcp://localhost:61616</soapjms:jndiURL>
tcp://localhost:61616
.
Looking up the connection factory
InitialContext
instance, you must specify the JNDI name that is bound to a javax.jms.ConnectionFactory
instance. In the case of Apache ActiveMQ, there is a predefined binding in the InitialContext
instance, which maps the JNDI name ConnectionFactory
to an ActiveMQConnectionFactory
instance. Example A.2, “SOAP/JMS WSDL for specifying the Apache ActiveMQ connection factory” shaows the SOAP/JMS extension element for specifying the Apache ActiveMQ connection factory.
Example A.2. SOAP/JMS WSDL for specifying the Apache ActiveMQ connection factory
<soapjms:jndiConnectionFactoryName> ConnectionFactory </soapjms:jndiConnectionFactoryName>
Syntax for dynamic destinations
dynamicQueues/QueueName dynamicTopics/TopicName
Example A.3. WSDL port specification with a dynamically created queue
<service name="JMSService"> <port binding="tns:GreeterBinding" name="JMSPort"> <jms:address jndiConnectionFactoryName="ConnectionFactory" jndiDestinationName="dynamicQueues/greeter.request.queue" > <jms:JMSNamingProperty name="java.naming.factory.initial" value="org.activemq.jndi.ActiveMQInitialContextFactory" /> <jms:JMSNamingProperty name="java.naming.provider.url" value="tcp://localhost:61616" /> </jms:address> </port> </service>
greeter.request.queue
exists. If it does not exist, it will create a new queue and bind it to the JNDI name greeter.request.queue
.
Appendix B. Conduits
Abstract
Overview
Conduit
interface. This allows for a standardized interface between the application level functionality and the transports.
- Implementing a custom transport
- Advanced application tuning to manage limited resources
Conduit life-cycle
- When the client implementation object is created, it is given a reference to a
ConduitSelector
object. - When the client needs to send a message is request's a reference to a conduit from the conduit selector.If the message is for a new endpoint, the conduit selector creates a new conduit and passes it to the client implementation. Otherwise, it passes the client a reference to the conduit for the target endpoint.
- The conduit sends messages when needed.
- When the client implementation object is destroyed, all of the conduits associated with it are destroyed.
Conduit weight
Session
object and one or more JMSListenerContainer
objects.
Part IV. Configuring Web Service Endpoints
Abstract
Chapter 15. Configuring JAX-WS Endpoints
Abstract
jaxws:client
element. For service providers you can use either the jaxws:endpoint
element or the jaxws:server
element.
15.1. Configuring Service Providers
15.1.1. Elements for Configuring Service Providers
jaxws:endpoint
element injects properties into the org.apache.cxf.jaxws.EndpointImpl
object created to support a service endpoint. The jaxws:server
element injects properties into the org.apache.cxf.jaxws.support.JaxWsServerFactoryBean
object created to support the endpoint. The EndpointImpl
object passes the configuration data to the JaxWsServerFactoryBean
object. The JaxWsServerFactoryBean
object is used to create the actual service object. Because either configuration element will configure a service endpoint, you can choose based on the syntax you prefer.
15.1.2. Using the jaxws:endpoint Element
Overview
jaxws:endpoint
element is the default element for configuring JAX-WS service providers. Its attributes and children specify all of the information needed to instantiate a service provider. Many of the attributes map to information in the service's contract. The children are used to configure interceptors and other advanced features.
Identifying the endpoint being configured
jaxws:endpoint
element's implementor
attribute.
- a combination of the
serviceName
attribute and theendpointName
attributeTheserviceName
attribute specifies thewsdl:service
element defining the service's endpoint. TheendpointName
attribute specifies the specificwsdl:port
element defining the service's endpoint. Both attributes are specified as QNames using the formatns:name
. ns is the namespace of the element and name is the value of the element'sname
attribute.NoteIf thewsdl:service
element only has onewsdl:port
element, theendpointName
attribute can be omitted. - the
name
attributeThename
attribute specifies the QName of the specificwsdl:port
element defining the service's endpoint. The QName is provided in the format{ns}localPart
. ns is the namespace of thewsdl:port
element and localPart is the value of thewsdl:port
element'sname
attribute.
Attributes
jaxws:endpoint
element configure the basic properties of the endpoint. These properties include the address of the endpoint, the class that implements the endpoint, and the bus
that hosts the endpoint.
jaxws:endpoint
element.
Attribute | Description |
---|---|
id | Specifies a unique identifier that other configuration elements can use to refer to the endpoint. |
implementor | Specifies the class implementing the service. You can specify the implementation class using either the class name or an ID reference to a Spring bean configuring the implementation class. This class must be on the classpath. |
implementorClass | Specifies the class implementing the service. This attribute is useful when the value provided to the implementor attribute is a reference to a bean that is wrapped using Spring AOP. |
address | Specifies the address of an HTTP endpoint. This value overrides the value specified in the services contract. |
wsdlLocation | Specifies the location of the endpoint's WSDL contract. The WSDL contract's location is relative to the folder from which the service is deployed. |
endpointName | Specifies the value of the service's wsdl:port element's name attribute. It is specified as a QName using the format ns:name where ns is the namespace of the wsdl:port element. |
serviceName | Specifies the value of the service's wsdl:service element's name attribute. It is specified as a QName using the format ns:name where ns is the namespace of the wsdl:service element. |
publish | Specifies if the service should be automatically published. If this is set to false , the developer must explicitly publish the endpoint as described in Chapter 31, Publishing a Service. |
bus | Specifies the ID of the Spring bean configuring the bus used to manage the service endpoint. This is useful when configuring several endpoints to use a common set of features. |
bindingUri | Specifies the ID of the message binding the service uses. A list of valid binding IDs is provided in Appendix C, Apache CXF Binding IDs. |
name | Specifies the stringified QName of the service's wsdl:port element. It is specified as a QName using the format {ns}localPart . ns is the namespace of the wsdl:port element and localPart is the value of the wsdl:port element's name attribute. |
abstract | Specifies if the bean is an abstract bean. Abstract beans act as parents for concrete bean definitions and are not instantiated. The default is false . Setting this to true instructs the bean factory not to instantiate the bean. |
depends-on | Specifies a list of beans that the endpoint depends on being instantiated before it can be instantiated. |
createdFromAPI |
Specifies that the user created that bean using Apache CXF APIs, such as
Endpoint.publish() or Service.getPort() .
The default is
false .
Setting this to
true does the following:
|
publishedEndpointUrl | The URL that is placed in the address element of the generated WSDL. If this value is not specified, the value of the address attribute is used. This attribute is useful when the "public" URL is not be the same as the URL on which the service is deployed. |
xmlns:shortName
attributes to declare the namespaces used by the endpointName
and serviceName
attributes.
Example
Example 15.1. Simple JAX-WS Endpoint Configuration
<beans ... xmlns:jaxws="http://cxf.apache.org/jaxws" ... schemaLocation="... http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ..."> <jaxws:endpoint id="example" implementor="org.apache.cxf.example.DemoImpl" address="http://localhost:8080/demo" /> </beans>
serviceName
attribute.
Example 15.2. JAX-WS Endpoint Configuration with a Service Name
<beans ... xmlns:jaxws="http://cxf.apache.org/jaxws" ... schemaLocation="... http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ..."> <jaxws:endpoint id="example2" implementor="org.apache.cxf.example.DemoImpl" serviceName="samp:demoService2" xmlns:samp="http://org.apache.cxf/wsdl/example" /> </beans>
xmlns:samp
attribute specifies the namespace in which the WSDL service
element is defined.
15.1.3. Using the jaxws:server Element
Overview
jaxws:server
element is an element for configuring JAX-WS service providers. It injects the configuration information into the org.apache.cxf.jaxws.support.JaxWsServerFactoryBean
. This is a Apache CXF specific object. If you are using a pure Spring approach to building your services, you will not be forced to use Apache CXF specific APIs to interact with the service.
jaxws:server
element specify all of the information needed to instantiate a service provider. The attributes specify the information that is required to instantiate an endpoint. The children are used to configure interceptors and other advanced features.
Identifying the endpoint being configured
jaxws:server
element's serviceBean
attribute.
- a combination of the
serviceName
attribute and theendpointName
attributeTheserviceName
attribute specifies thewsdl:service
element defining the service's endpoint. TheendpointName
attribute specifies the specificwsdl:port
element defining the service's endpoint. Both attributes are specified as QNames using the formatns:name
. ns is the namespace of the element and name is the value of the element'sname
attribute.NoteIf thewsdl:service
element only has onewsdl:port
element, theendpointName
attribute can be omitted. - the
name
attributeThename
attribute specifies the QName of the specificwsdl:port
element defining the service's endpoint. The QName is provided in the format{ns}localPart
. ns is the namespace of thewsdl:port
element and localPart is the value of thewsdl:port
element'sname
attribute.
Attributes
jaxws:server
element configure the basic properties of the endpoint. These properties include the address of the endpoint, the class that implements the endpoint, and the bus
that hosts the endpoint.
jaxws:server
element.
Attribute | Description |
---|---|
id | Specifies a unique identifier that other configuration elements can use to refer to the endpoint. |
serviceBean | Specifies the class implementing the service. You can specify the implementation class using either the class name or an ID reference to a Spring bean configuring the implementation class. This class must be on the classpath. |
serviceClass | Specifies the class implementing the service. This attribute is useful when the value provided to the implementor attribute is a reference to a bean that is wrapped using Spring AOP. |
address | Specifies the address of an HTTP endpoint. This value will override the value specified in the services contract. |
wsdlLocation | Specifies the location of the endpoint's WSDL contract. The WSDL contract's location is relative to the folder from which the service is deployed. |
endpointName | Specifies the value of the service's wsdl:port element's name attribute. It is specified as a QName using the format ns:name , where ns is the namespace of the wsdl:port element. |
serviceName | Specifies the value of the service's wsdl:service element's name attribute. It is specified as a QName using the format ns:name , where ns is the namespace of the wsdl:service element. |
publish | Specifies if the service should be automatically published. If this is set to false , the developer must explicitly publish the endpoint as described in Chapter 31, Publishing a Service. |
bus | Specifies the ID of the Spring bean configuring the bus used to manage the service endpoint. This is useful when configuring several endpoints to use a common set of features. |
bindingId | Specifies the ID of the message binding the service uses. A list of valid binding IDs is provided in Appendix C, Apache CXF Binding IDs. |
name | Specifies the stringified QName of the service's wsdl:port element. It is specified as a QName using the format {ns}localPart , where ns is the namespace of the wsdl:port element and localPart is the value of the wsdl:port element's name attribute. |
abstract | Specifies if the bean is an abstract bean. Abstract beans act as parents for concrete bean definitions and are not instantiated. The default is false . Setting this to true instructs the bean factory not to instantiate the bean. |
depends-on | Specifies a list of beans that the endpoint depends on being instantiated before the endpoint can be instantiated. |
createdFromAPI |
Specifies that the user created that bean using Apache CXF APIs, such as
Endpoint.publish() or Service.getPort() .
The default is
false .
Setting this to
true does the following:
|
xmlns:shortName
attributes to declare the namespaces used by the endpointName
and serviceName
attributes.
Example
Example 15.3. Simple JAX-WS Server Configuration
<beans ... xmlns:jaxws="http://cxf.apache.org/jaxws" ... schemaLocation="... http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ..."> <jaxws:server id="exampleServer" serviceBean="org.apache.cxf.example.DemoImpl" address="http://localhost:8080/demo" /> </beans>
15.1.4. Adding Functionality to Service Providers
Overview
jaxws:endpoint
and the jaxws:server
elements provide the basic configuration information needed to instantiate a service provider. To add functionality to your service provider or to perform advanced configuration you must add child elements to the configuration.
Elements
jaxws:endpoint
supports.
Element | Description |
---|---|
jaxws:handlers | Specifies a list of JAX-WS Handler implementations for processing messages. For more information on JAX-WS Handler implementations see Chapter 43, Writing Handlers. |
jaxws:inInterceptors | Specifies a list of interceptors that process inbound requests. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:inFaultInterceptors | Specifies a list of interceptors that process inbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:outInterceptors | Specifies a list of interceptors that process outbound replies. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:outFaultInterceptors | Specifies a list of interceptors that process outbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:binding | Specifies a bean configuring the message binding used by the endpoint. Message bindings are configured using implementations of the org.apache.cxf.binding.BindingFactory interface.[a] |
jaxws:dataBinding [b] | Specifies the class implementing the data binding used by the endpoint. This is specified using an embedded bean definition. |
jaxws:executor | Specifies a Java executor that is used for the service. This is specified using an embedded bean definition. |
jaxws:features | Specifies a list of beans that configure advanced features of Apache CXF. You can provide either a list of bean references or a list of embedded beans. |
jaxws:invoker | Specifies an implementation of the org.apache.cxf.service.Invoker interface used by the service. [c] |
jaxws:properties | Specifies a Spring map of properties that are passed along to the endpoint. These properties can be used to control features like enabling MTOM support. |
jaxws:serviceFactory | Specifies a bean configuring the JaxWsServiceFactoryBean object used to instantiate the service. |
[a]
The SOAP binding is configured using the soap:soapBinding bean.
[c]
The Invoker implementation controls how a service is invoked. For example, it controls whether each request is handled by a new instance of the service implementation or if state is preserved across invocations.
|
15.2. Configuring Consumer Endpoints
Overview
jaxws:client
element. The element's attributes provide the basic information necessary to create a consumer.
jaxws:client
element. Child elements are also used to configure the endpoint's logging behavior and to inject other properties into the endpoint's implementation.
Basic Configuration Properties
Attribute | Description |
---|---|
address | Specifies the HTTP address of the endpoint where the consumer will make requests. This value overrides the value set in the contract. |
bindingId | Specifies the ID of the message binding the consumer uses. A list of valid binding IDs is provided in Appendix C, Apache CXF Binding IDs. |
bus | Specifies the ID of the Spring bean configuring the bus managing the endpoint. |
endpointName | Specifies the value of the wsdl:port element's name attribute for the service on which the consumer is making requests. It is specified as a QName using the format ns:name , where ns is the namespace of the wsdl:port element. |
serviceName | Specifies the value of the wsdl:service element's name attribute for the service on which the consumer is making requests. It is specified as a QName using the format ns:name where ns is the namespace of the wsdl:service element. |
username | Specifies the username used for simple username/password authentication. |
password | Specifies the password used for simple username/password authentication. |
serviceClass | Specifies the name of the service endpoint interface(SEI). |
wsdlLocation | Specifies the location of the endpoint's WSDL contract. The WSDL contract's location is relative to the folder from which the client is deployed. |
name | Specifies the stringified QName of the wsdl:port element for the service on which the consumer is making requests. It is specified as a QName using the format {ns}localPart , where ns is the namespace of the wsdl:port element and localPart is the value of the wsdl:port element's name attribute. |
abstract | Specifies if the bean is an abstract bean. Abstract beans act as parents for concrete bean definitions and are not instantiated. The default is false . Setting this to true instructs the bean factory not to instantiate the bean. |
depends-on | Specifies a list of beans that the endpoint depends on being instantiated before it can be instantiated. |
createdFromAPI |
Specifies that the user created that bean using Apache CXF APIs like
Service.getPort() .
The default is
false .
Setting this to
true does the following:
|
xmlns:shortName
attributes to declare the namespaces used by the endpointName
and the serviceName
attributes.
Adding functionality
Element | Description |
---|---|
jaxws:binding | Specifies a bean configuring the message binding used by the endpoint. Message bindings are configured using implementations of the org.apache.cxf.binding.BindingFactory interface.[a] |
jaxws:dataBinding | Specifies the class implementing the data binding used by the endpoint. You specify this using an embedded bean definition. The class implementing the JAXB data binding is org.apache.cxf.jaxb.JAXBDataBinding . |
jaxws:features | Specifies a list of beans that configure advanced features of Apache CXF. You can provide either a list of bean references or a list of embedded beans. |
jaxws:handlers | Specifies a list of JAX-WS Handler implementations for processing messages. For more information in JAX-WS Handler implementations see Chapter 43, Writing Handlers. |
jaxws:inInterceptors | Specifies a list of interceptors that process inbound responses. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:inFaultInterceptors | Specifies a list of interceptors that process inbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:outInterceptors | Specifies a list of interceptors that process outbound requests. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:outFaultInterceptors | Specifies a list of interceptors that process outbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxws:properties | Specifies a map of properties that are passed to the endpoint. |
jaxws:conduitSelector | Specifies an org.apache.cxf.endpoint.ConduitSelector implementation for the client to use. A ConduitSelector implementation will override the default process used to select the Conduit object that is used to process outbound requests. |
[a]
The SOAP binding is configured using the soap:soapBinding bean.
|
Example
Example 15.4. Simple Consumer Configuration
<beans ... xmlns:jaxws="http://cxf.apache.org/jaxws" ... schemaLocation="... http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd ..."> <jaxws:client id="bookClient" serviceClass="org.apache.cxf.demo.BookClientImpl" address="http://localhost:8080/books"/> ... </beans>
Chapter 16. Configuring JAX-RS Endpoints
Abstract
16.1. Configuring JAX-RS Server Endpoints
16.1.1. Defining a JAX-RS Server Endpoint
Basic server endpoint definition
- A
jaxrs:server
element, which is used to define the endpoint in XML. Note that thejaxrs:
namespace prefix maps to different namespaces in Blueprint and in Spring respectively. - The base URL of the JAX-RS service, using the
address
attribute of thejaxrs:server
element. Note that there are two different ways of specifying the address URL, which affects how the endpoint gets deployed:- As a relative URL—for example,
/customers
. In this case, the endpoint is deployed into the default HTTP container, and the endpoint's base URL is implicitly obtained by combining the CXF servlet base URL with the specified relative URL.For example, if you deploy a JAX-RS endpoint to the JBoss Fuse container, the specified/customers
URL would get resolved to the URL,http://Hostname:8181/cxf/customers
(assuming that the container is using the default8181
port). - As an absolute URL—for example,
http://0.0.0.0:8200/cxf/customers
. In this case, a new HTTP listener port is opened for the JAX-RS endpoint (if it is not already open). For example, in the context of JBoss Fuse, a new Jetty container would implicitly be created to host the JAX-RS endpoint. The special IP address,0.0.0.0
, acts as a wildcard, matching any of the hostnames assigned to the current host (which can be useful on multi-homed host machines).
- One or more JAX-RS root resource classes, which provide the implementation of the JAX-RS service. The simplest way to specify the resource classes is to list them inside a
jaxrs:serviceBeans
element.
Blueprint example
/customers
(so that it deploys into the default HTTP container) and is implemented by the service.CustomerService
resource class:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs" xmlns:cxf="http://cxf.apache.org/blueprint/core" xsi:schemaLocation=" http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd "> <cxf:bus> <cxf:features> <cxf:logging/> </cxf:features> </cxf:bus> <jaxrs:server id="customerService" address="/customers"> <jaxrs:serviceBeans> <ref component-id="serviceBean" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="serviceBean" class="service.CustomerService"/> </blueprint>
Blueprint XML namespaces
Prefix | Namespace |
---|---|
(default) | http://www.osgi.org/xmlns/blueprint/v1.0.0 |
cxf | http://cxf.apache.org/blueprint/core |
jaxrs | http://cxf.apache.org/blueprint/jaxrs |
Spring example
/customers
(so that it deploys into the default HTTP container) and is implemented by the service.CustomerService
resource class:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <jaxrs:server id="customerService" address="/customers"> <jaxrs:serviceBeans> <ref bean="serviceBean"/> </jaxrs:serviceBeans> </jaxrs:server> <bean id="serviceBean" class="service.CustomerService"/> </beans>
Spring XML namespaces
Prefix | Namespace |
---|---|
(default) | http://www.springframework.org/schema/beans |
cxf | http://cxf.apache.org/core |
jaxrs | http://cxf.apache.org/jaxrs |
Auto-discovery in Spring XML
@Path
) and all of the discovered resource classes are automatically attached to the endpoint. In this case, you need to specify just the address
attribute and the basePackages
attribute in the jaxrs:server
element.
a.b.c
Java package, you can define the endpoint in Spring XML, as follows:
<jaxrs:server address="/customers" basePackages="a.b.c"/>
Lifecycle management in Spring XML
scope
attribute on a bean
element. The following scope values are supported by Spring:
singleton
- (Default) Creates a single bean instance, which is used everywhere and lasts for the entire lifetime of the Spring container.
prototype
- Creates a new bean instance every time the bean is injected into another bean or when a bean is obtained by invoking
getBean()
on the bean registry. request
- (Only available in a Web-aware container) Creates a new bean instance for every request invoked on the bean.
session
- (Only available in a Web-aware container) Creates a new bean for the lifetime of a single HTTP session.
globalSession
- (Only available in a Web-aware container) Creates a new bean for the lifetime of a single HTTP session that is shared between portlets.
jaxrs:serviceBeans
element. If you specify the scope
attribute on the resource beans in this case, the scope
attribute is effectively ignored.
beanNames
attribute on the jaxrs:server
element, as follows:
<beans ... > <jaxrs:server id="customerService" address="/service1" beanNames="customerBean1 customerBean2"/> <bean id="customerBean1" class="demo.jaxrs.server.CustomerRootResource1" scope="prototype"/> <bean id="customerBean2" class="demo.jaxrs.server.CustomerRootResource2" scope="prototype"/> </beans>
customerBean1
and customerBean2
. The beanNames
attribute is specified as a space-separated list of resource bean IDs.
jaxrs:serviceFactories
element. This more verbose approach has the advantage that you can replace the default service factory implementation with your custom implementation, thus giving you ultimate control over the bean lifecycle. The following example shows how to configure the two resource beans, customerBean1
and customerBean2
, using this approach:
<beans ... > <jaxrs:server id="customerService" address="/service1"> <jaxrs:serviceFactories> <ref bean="sfactory1" /> <ref bean="sfactory2" /> </jaxrs:serviceFactories> </jaxrs:server> <bean id="sfactory1" class="org.apache.cxf.jaxrs.spring.SpringResourceFactory"> <property name="beanId" value="customerBean1"/> </bean> <bean id="sfactory2" class="org.apache.cxf.jaxrs.spring.SpringResourceFactory"> <property name="beanId" value="customerBean2"/> </bean> <bean id="customerBean1" class="demo.jaxrs.server.CustomerRootResource1" scope="prototype"/> <bean id="customerBean2" class="demo.jaxrs.server.CustomerRootResource2" scope="prototype"/> </beans>
org.apache.cxf.service.Invoker
bean (where the instance can be registered by referencing it from a jaxrs:server/jaxrs:invoker
element).
Attaching a WADL document
docLocation
attribute on the jaxrs:server
element. For example:
<jaxrs:server address="/rest" docLocation="wadl/bookStore.wadl"> <jaxrs:serviceBeans> <bean class="org.bar.generated.BookStore"/> </jaxrs:serviceBeans> </jaxrs:server>
Schema validation
jaxrs:schemaLocations
element.
<jaxrs:server address="/rest" docLocation="wadl/bookStore.wadl"> <jaxrs:serviceBeans> <bean class="org.bar.generated.BookStore"/> </jaxrs:serviceBeans> <jaxrs:schemaLocations> <jaxrs:schemaLocation>classpath:/schemas/a.xsd</jaxrs:schemaLocation> <jaxrs:schemaLocation>classpath:/schemas/b.xsd</jaxrs:schemaLocation> </jaxrs:schemaLocations> </jaxrs:server>
*.xsd
, in a given directory, you can just specify the directory name, as follows:
<jaxrs:server address="/rest" docLocation="wadl/bookStore.wadl"> <jaxrs:serviceBeans> <bean class="org.bar.generated.BookStore"/> </jaxrs:serviceBeans> <jaxrs:schemaLocations> <jaxrs:schemaLocation>classpath:/schemas/</jaxrs:schemaLocation> </jaxrs:schemaLocations> </jaxrs:server>
Specifying the data binding
jaxrs:dataBinding
element to specify the data binding that encodes the message body in request and reply messages. For example, to specify the JAX-B data binding, you could configure a JAX-RS endpoint as follows:
<jaxrs:server id="jaxbbook" address="/jaxb"> <jaxrs:serviceBeans> <ref bean="serviceBean" /> </jaxrs:serviceBeans> <jaxrs:dataBinding> <bean class="org.apache.cxf.jaxb.JAXBDataBinding"/> </jaxrs:dataBinding> </jaxrs:server>>
<jaxrs:server id="aegisbook" address="/aegis"> <jaxrs:serviceBeans> <ref bean="serviceBean" /> </jaxrs:serviceBeans> <jaxrs:dataBinding> <bean class="org.apache.cxf.aegis.databinding.AegisDatabinding"> <property name="aegisContext"> <bean class="org.apache.cxf.aegis.AegisContext"> <property name="writeXsiTypes" value="true"/> </bean> </property> </bean> </jaxrs:dataBinding> </jaxrs:server>
Using the JMS transport
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://cxf.apache.org/transports/jms" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation=" http://cxf.apache.org/transports/jms http://cxf.apache.org/schemas/configuration/jms.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/> <bean id="ConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:${testutil.ports.EmbeddedJMSBrokerLauncher}" /> </bean> <jaxrs:server xmlns:s="http://books.com" serviceName="s:BookService" transportId= "http://cxf.apache.org/transports/jms" address="jms:queue:test.jmstransport.text?replyToName=test.jmstransport.response"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.systest.jaxrs.JMSBookStore"/> </jaxrs:serviceBeans> </jaxrs:server> </beans>
- JMS implementation—the JMS implementation is provided by the
ConnectionFactory
bean, which instantiates an Apache ActiveMQ connection factory object. After you instantiate the connection factory, it is automatically installed as the default JMS implementation layer. - JMS conduit or destination object—Apache CXF implicitly instantiates a JMS conduit object (to represent a JMS consumer) or a JMS destination object (to represent a JMS provider). This object must be uniquely identified by a QName, which is defined through the attribute setttings
xmlns:s="http://books.com"
(defining the namespace prefix) andserviceName="s:BookService"
(defining the QName). - Transport ID—to select the JMS transport, the
transportId
attribute must be set tohttp://cxf.apache.org/transports/jms
. - JMS address—the
jaxrs:server/@address
attribute uses a standardized syntax to specify the JMS queue or JMS topic to send to. For details of this syntax, see https://tools.ietf.org/id/draft-merrick-jms-uri-06.txt.
Extension mappings and language mappings
GET /resource.xml
.xml
suffix automatically, as follows:
<jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.jaxrs.systests.CustomerService" /> </jaxrs:serviceBeans> <jaxrs:extensionMappings> <entry key="json" value="application/json"/> <entry key="xml" value="application/xml"/> </jaxrs:extensionMappings> </jaxrs:server>
application/xml
, and strips the .xml
suffix from the resource URL.
GET /resource.en
.en
suffix automatically, as follows:
<jaxrs:server id="customerService" address="/"> <jaxrs:serviceBeans> <bean class="org.apache.cxf.jaxrs.systests.CustomerService" /> </jaxrs:serviceBeans> <jaxrs:languageMappings> <entry key="en" value="en-gb"/> </jaxrs:languageMappings> </jaxrs:server>
en-gb
, and strips the .en
suffix from the resource URL.
16.1.2. jaxrs:server Attributes
Attributes
jaxrs:server
element.
Attribute | Description |
---|---|
id | Specifies a unique identifier that other configuration elements can use to refer to the endpoint. |
address | Specifies the address of an HTTP endpoint. This value will override the value specified in the services contract. |
basePackages | (Spring only) Enables auto-discovery, by specifying a comma-separated list of Java packages, which are searched to discover JAX-RS root resource classes and/or JAX-RS provider classes. |
beanNames | Specifies a space-separated list of bean IDs of JAX-RS root resource beans. In the context of Spring XML, it is possible to define a root resource beans' lifecycle by setting the scope attribute on the root resource bean element. |
bindingId | Specifies the ID of the message binding the service uses. A list of valid binding IDs is provided in Appendix C, Apache CXF Binding IDs. |
bus | Specifies the ID of the Spring bean configuring the bus used to manage the service endpoint. This is useful when configuring several endpoints to use a common set of features. |
docLocation | Specifies the location of an external WADL document. |
modelRef | Specifies a model schema as a classpath resource (for example, a URL of the form classpath:/path/to/model.xml ). For details of how to define a JAX-RS model schema, see Section 16.3, “Defining REST Services with the Model Schema”. |
publish | Specifies if the service should be automatically published. If set to false , the developer must explicitly publish the endpoint. |
publishedEndpointUrl | Specifies the URL base address, which gets inserted into the wadl:resources/@base attribute of the auto-generated WADL interface. |
serviceAnnotation | (Spring only) Specifies the service annotation class name for auto-discovery in Spring. When used in combination with the basePackages property, this option restricts the collection of auto-discovered classes to include only the classes that are annotated by this annotation type.
|
serviceClass | Specifies the name of a JAX-RS root resource class (which implements a JAX-RS service). In this case, the class is instantiated by Apache CXF, not by Blueprint or Spring. If you want to instantiate the class in Blueprint or Spring, use the jaxrs:serviceBeans child element instead. |
serviceName | Specifies the service QName (using the format ns:name ) for the JAX-RS endpoint in the special case where a JMS transport is used. For details, see the section called “Using the JMS transport”. |
staticSubresourceResolution | If true , disables dynamic resolution of static sub-resources. Default is false . |
transportId | For selecting a non-standard transport layer (in place of HTTP). In particular, you can select the JMS transport by setting this property to http://cxf.apache.org/transports/jms . For details, see the section called “Using the JMS transport”. |
abstract | (Spring only) Specifies if the bean is an abstract bean. Abstract beans act as parents for concrete bean definitions and are not instantiated. The default is false . Setting this to true instructs the bean factory not to instantiate the bean. |
depends-on | (Spring only) Specifies a list of beans that the endpoint depends on being instantiated before the endpoint can be instantiated. |
16.1.3. jaxrs:server Child Elements
Child elements
jaxrs:server
element.
Element | Description |
---|---|
jaxrs:executor | Specifies a Java Executor (thread pool implementation) that is used for the service. This is specified using an embedded bean definition. |
jaxrs:features | Specifies a list of beans that configure advanced features of Apache CXF. You can provide either a list of bean references or a list of embedded beans. |
jaxrs:binding | Not used. |
jaxrs:dataBinding | Specifies the class implementing the data binding used by the endpoint. This is specified using an embedded bean definition. For more details, see the section called “Specifying the data binding”. |
jaxrs:inInterceptors | Specifies a list of interceptors that process inbound requests. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:inFaultInterceptors | Specifies a list of interceptors that process inbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:outInterceptors | Specifies a list of interceptors that process outbound replies. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:outFaultInterceptors | Specifies a list of interceptors that process outbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:invoker | Specifies an implementation of the org.apache.cxf.service.Invoker interface used by the service. [a] |
jaxrs:serviceFactories | Provides you with the maximum degree of control over the lifecycle of the JAX-RS root resources associated with this endpoint. The children of this element (which must be instances of org.apache.cxf.jaxrs.lifecycle.ResourceProvider type) are used to create JAX-RS root resource instances. |
jaxrs:properties | Specifies a Spring map of properties that are passed along to the endpoint. These properties can be used to control features like enabling MTOM support. |
jaxrs:serviceBeans | The children of this element are instances of (bean element) or references to (ref element) JAX-RS root resources. Note that in this case the scope attribute (Spring only), if present in the bean element, is ignored. |
jaxrs:modelBeans | Consists of a list of references to one or more org.apache.cxf.jaxrs.model.UserResource beans, which are the basic elements of a resource model (corresponding to jaxrs:resource elements). For details, see Section 16.3, “Defining REST Services with the Model Schema”. |
jaxrs:model | Defines a resource model directly in this endpoint (that is, this jaxrs:model element can contain one or more jaxrs:resource elements). For details, see Section 16.3, “Defining REST Services with the Model Schema”. |
jaxrs:providers | Enables you to register one or more custom JAX-RS providers with this endpoint. The children of this element are instances of (bean element) or references to (ref element) JAX-RS providers. |
jaxrs:extensionMappings | When the URL of a REST invocation ends in a file extension, you can use this element to associate it automatically with a particular content type. For example, the .xml file extension could be associated with the application/xml content type. For details, see the section called “Extension mappings and language mappings”. |
jaxrs:languageMappings | When the URL of a REST invocation ends in a language suffix, you can use this element to map this to a particular language. For example, the .en language suffix could be associated with the en-GB language. For details, see the section called “Extension mappings and language mappings”. |
jaxrs:schemaLocations | Specifies one or more XML schemas used for validating XML message content. This element can contain one or more jaxrs:schemaLocation elements, each specifying the location of an XML schema file (usually as a classpath URL). For details, see the section called “Schema validation”. |
jaxrs:resourceComparator | Enables you to register a custom resource comparator, which implements the algorithm used to match an incoming URL path to a particular resource class or method. |
jaxrs:resourceClasses | (Blueprint only) Can be used instead of the jaxrs:server/@serviceClass attribute, if you want to create multiple resources from class names. The children of jaxrs:resourceClasses must be class elements with a name attribute set to the name of the resource class. In this case, the classes are instantiated by Apache CXF, not by Blueprint or Spring. |
[a]
The Invoker implementation controls how a service is invoked. For example, it controls whether each request is handled by a new instance of the service implementation or if state is preserved across invocations.
|
16.2. Configuring JAX-RS Client Endpoints
16.2.1. Defining a JAX-RS Client Endpoint
Injecting client proxies
jaxrs:client
element.
Namespaces
XML Language | Namespace for client endpoint |
---|---|
Blueprint | http://cxf.apache.org/blueprint/jaxrs-client |
Spring | http://cxf.apache.org/jaxrs-client |
Basic client endpoint definition
<jaxrs:client id="restClient" address="http://localhost:8080/test/services/rest" serviceClass="org.apache.cxf.systest.jaxrs.BookStoreJaxrsJaxws"/>
id
- The bean ID of the client proxy can be used to inject the client proxy into other beans in your XML configuration.
address
- The address attribute specifies the base URL of the REST invocations.
serviceClass
- The
serviceClass
attribute provides a description of the REST service by specifying a root resource class (annotated by@Path
). In fact, this is a server class, but it is not used directly by the client. The specified class is used only for its metadata (through Java reflection and JAX-RS annotations), which is used to construct the client proxy dynamically.
Specifying headers
jaxrs:headers
child elements, as follows:
<jaxrs:client id="restClient" address="http://localhost:8080/test/services/rest" serviceClass="org.apache.cxf.systest.jaxrs.BookStoreJaxrsJaxws" inheritHeaders="true"> <jaxrs:headers> <entry key="Accept" value="text/xml"/> </jaxrs:headers> </jaxrs:client>
16.2.2. jaxrs:client Attributes
Attributes
jaxrs:client
element.
Attribute | Description |
---|---|
address | Specifies the HTTP address of the endpoint where the consumer will make requests. This value overrides the value set in the contract. |
bindingId | Specifies the ID of the message binding the consumer uses. A list of valid binding IDs is provided in Appendix C, Apache CXF Binding IDs. |
bus | Specifies the ID of the Spring bean configuring the bus managing the endpoint. |
inheritHeaders | Specifies whether the headers set for this proxy will be inherited, if a subresource proxy is created from this proxy. Default is false . |
username | Specifies the username used for simple username/password authentication. |
password | Specifies the password used for simple username/password authentication. |
modelRef | Specifies a model schema as a classpath resource (for example, a URL of the form classpath:/path/to/model.xml ). For details of how to define a JAX-RS model schema, see Section 16.3, “Defining REST Services with the Model Schema”. |
serviceClass | Specifies the name of a service interface or a resource class (that is annotated with @PATH ), re-using it from the JAX-RS server implementation. In this case, the specified class is not invoked directly (it is actually a server class). The specified class is used only for its metadata (through Java reflection and JAX-RS annotations), which is used to construct the client proxy dynamically. |
serviceName | Specifies the service QName (using the format ns:name ) for the JAX-RS endpoint in the special case where a JMS transport is used. For details, see the section called “Using the JMS transport”. |
threadSafe | Specifies whether or not the client proxy is thread-safe. Default is false . |
transportId | For selecting a non-standard transport layer (in place of HTTP). In particular, you can select the JMS transport by setting this property to http://cxf.apache.org/transports/jms . For details, see the section called “Using the JMS transport”. |
abstract | (Spring only) Specifies if the bean is an abstract bean. Abstract beans act as parents for concrete bean definitions and are not instantiated. The default is false . Setting this to true instructs the bean factory not to instantiate the bean. |
depends-on | (Spring only) Specifies a list of beans that the endpoint depends on being instantiated before it can be instantiated. |
16.2.3. jaxrs:client Child Elements
Child elements
jaxrs:client
element.
Element | Description |
---|---|
jaxrs:executor | |
jaxrs:features | Specifies a list of beans that configure advanced features of Apache CXF. You can provide either a list of bean references or a list of embedded beans. |
jaxrs:binding | Not used. |
jaxrs:dataBinding | Specifies the class implementing the data binding used by the endpoint. This is specified using an embedded bean definition. For more details, see the section called “Specifying the data binding”. |
jaxrs:inInterceptors | Specifies a list of interceptors that process inbound responses. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:inFaultInterceptors | Specifies a list of interceptors that process inbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:outInterceptors | Specifies a list of interceptors that process outbound requests. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:outFaultInterceptors | Specifies a list of interceptors that process outbound fault messages. For more information see Part VII, “Developing Apache CXF Interceptors”. |
jaxrs:properties | Specifies a map of properties that are passed to the endpoint. |
jaxrs:providers | Enables you to register one or more custom JAX-RS providers with this endpoint. The children of this element are instances of (bean element) or references to (ref element) JAX-RS providers. |
jaxrs:modelBeans | Consists of a list of references to one or more org.apache.cxf.jaxrs.model.UserResource beans, which are the basic elements of a resource model (corresponding to jaxrs:resource elements). For details, see Section 16.3, “Defining REST Services with the Model Schema”. |
jaxrs:model | Defines a resource model directly in this endpoint (that is, a jaxrs:model element containing one or more jaxrs:resource elements). For details, see Section 16.3, “Defining REST Services with the Model Schema”. |
jaxrs:headers | Used for setting headers on the outgoing message. For details, see the section called “Specifying headers”. |
jaxrs:schemaLocations | Specifies one or more XML schemas used for validating XML message content. This element can contain one or more jaxrs:schemaLocation elements, each specifying the location of an XML schema file (usually as a classpath URL). For details, see the section called “Schema validation”. |
16.3. Defining REST Services with the Model Schema
RESTful services without annotations
@Path
, @PathParam
, @Consumes
, @Produces
, and so on, directly to a Java class (or interface), you can provide all of the relevant REST metadata in a separate XML file, using the model schema. This can be useful, for example, in cases where you are unable to modify the Java source that implements the service.
Example model schema
BookStoreNoAnnotations
root resource class.
Example 16.1. Sample JAX-RS Model Schema
<model xmlns="http://cxf.apache.org/jaxrs"> <resource name="org.apache.cxf.systest.jaxrs.BookStoreNoAnnotations" path="bookstore" produces="application/json" consumes="application/json"> <operation name="getBook" verb="GET" path="/books/{id}" produces="application/xml"> <param name="id" type="PATH"/> </operation> <operation name="getBookChapter" path="/books/{id}/chapter"> <param name="id" type="PATH"/> </operation> <operation name="updateBook" verb="PUT"> <param name="book" type="REQUEST_BODY"/> </operation> </resource> <resource name="org.apache.cxf.systest.jaxrs.ChapterNoAnnotations"> <operation name="getItself" verb="GET"/> <operation name="updateChapter" verb="PUT" consumes="application/xml"> <param name="content" type="REQUEST_BODY"/> </operation> </resource> </model>
Namespaces
XML Language | Namespace |
---|---|
Blueprint | http://cxf.apache.org/blueprint/jaxrs |
Spring | http://cxf.apache.org/jaxrs |
How to attach a model schema to an endpoint
- Define the model schema, using the appropriate XML namespace for your chosen injection platform (Blueprint XML or Spring XML).
- Add the model schema file to your project's resources, so that the schema file is available on the classpath in the final package (JAR, WAR, or OSGi bundle file).NoteAlternatively, it is also possible to embed a model schema directly into a JAX-RS endpoint, using the endpoint's
jaxrs:model
child element. - Configure the endpoint to use the model schema, by setting the endpoint's
modelRef
attribute to the location of the model schema on the classpath (using a classpath URL). - If necessary, instantiate the root resources explicitly, using the
jaxrs:serviceBeans
element. You can skip this step, if the model schema references root resource classes directly (instead of referencing base interfaces).
Configuration of model schema referencing a class
jaxrs:serviceBeans
element, because the model schema automatically instantiates the root resource beans.
customer-resources.xml
is a model schema that associates metadata with customer resource classes, you could instantiate a customerService
service endpoint as follows:
<jaxrs:server id="customerService" address="/customers" modelRef="classpath:/org/example/schemas/customer-resources.xml" />
Configuration of model schema referencing an interface
jaxrs:serviceBeans
element in the endpoint.
customer-interfaces.xml
is a model schema that associates metadata with customer interfaces, you could instantiate a customerService
service endpoint as follows:
<jaxrs:server id="customerService" address="/customers" modelRef="classpath:/org/example/schemas/customer-interfaces.xml"> <jaxrs:serviceBeans> <ref component-id="serviceBean" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="serviceBean" class="service.CustomerService"/>
Model Schema Reference
model
- Root element of the model schema. If you need to reference the model schema (for example, from a JAX-RS endpoint using the
modelRef
attribute), you should set theid
attribute on this element. model/resource
- The
resource
element is used to associate metadata with a specific root resource class (or with a corresponding interface). You can define the following attributes on theresource
element:Attribute Description name
The name of the resource class (or corresponding interface) to which this resource model is applied. path
The component of the REST URL path that maps to this resource. consumes
Specifies the content type (Internet media type) consumed by this resource—for example, application/xml
orapplication/json
.produces
Specifies the content type (Internet media type) produced by this resource—for example, application/xml
orapplication/json
. model/resource/operation
- The
operation
element is used to associate metadata with Java methods. You can define the following attributes on anoperation
element:Attribute Description name
The name of the Java method to which this element is applied. path
The component of the REST URL path that maps to this method. This attribute value can include parameter references, for example: path="/books/{id}/chapter"
, where{id}
extracts the value of theid
parameter from the path.verb
Specifies the HTTP verb that maps to this method. Typically one of: GET
,POST
,PUT
, orDELETE
. If the HTTP verb is not specified, it is assumed that the Java method is a sub-resource locater, which returns a reference to a sub-resource object (where the sub-resource class must also be provided with metadata using aresource
element).consumes
Specifies the content type (Internet media type) consumed by this operation—for example, application/xml
orapplication/json
.produces
Specifies the content type (Internet media type) produced by this operation—for example, application/xml
orapplication/json
.oneway
If true
, configures the operation to be oneway, meaning that no reply message is needed. Defaults tofalse
. model/resource/operation/param
- The
param
element is used extract a value from the REST URL and inject it into one of the method parameters. You can define the following attributes on aparam
element:Attribute Description name
The name of the Java method parameter to which this element is applied. type
Specifies how the parameter value is extracted from the REST URL or message. It can be set to one of the following values: PATH
,QUERY
,MATRIX
,HEADER
,COOKIE
,FORM
,CONTEXT
,REQUEST_BODY
.defaultValue
Default value to inject into the parameter, in case a value could not be extracted from the REST URL or message. encoded
If true
, the parameter value is injected in its URI encoded form (that is, using%nn
encoding). Default isfalse
. For example, when extracting a parameter from the URL path,/name/Joe%20Bloggs
with encoded set totrue
, the parameter is injected asJoe%20Bloggs
; otherwise, the parameter would be injected asJoe Bloggs
.
Chapter 17. Apache CXF Logging
Abstract
17.1. Overview of Apache CXF Logging
Overview
java.util.logging
. Logging is configured in a logging configuration file that is written using the standard java.util.Properties
format. To run logging on an application, you can specify logging programmatically or by defining a property at the command that points to the logging configuration file when you start the application.
Default properties file
logging.properties
file, which is located in your InstallDir/etc
directory. This file configures both the output destination for the log messages and the message level that is published. The default configuration sets the loggers to print message flagged with the WARNING
level to the console. You can either use the default file without changing any of the configuration settings or you can change the configuration settings to suit your specific application.
Logging feature
Example 17.1. Configuration for Enabling Logging
<jaxws:endpoint...> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature"/> </jaxws:features> </jaxws:endpoint>
Where to begin?
More information on java.util.logging
java.util.logging
utility is one of the most widely used Java logging frameworks. There is a lot of information available online that describes how to use and extend this framework. As a starting point, however, the following documents gives a good overview of java.util.logging
:
17.2. Simple Example of Using Logging
Changing the log levels and output destination
- Run the sample server as described in the Running the demo using java section of the
README.txt
file in theInstallDir/samples/wsdl_first
directory. Note that the server start command specifies the defaultlogging.properties
file, as follows:Platform Command Windows start java -Djava.util.logging.config.file=%CXF_HOME%\etc\logging.properties demo.hw.server.Server
UNIX java -Djava.util.logging.config.file=$CXF_HOME/etc/logging.properties demo.hw.server.Server &
The defaultlogging.properties
file is located in theInstallDir/etc
directory. It configures the Apache CXF loggers to printWARNING
level log messages to the console. As a result, you see very little printed to the console. - Stop the server as described in the
README.txt
file. - Make a copy of the default
logging.properties
file, name itmylogging.properties
file, and save it in the same directory as the defaultlogging.properties
file. - Change the global logging level and the console logging levels in your
mylogging.properties
file toINFO
by editing the following lines of configuration:.level= INFO java.util.logging.ConsoleHandler.level = INFO
- Restart the server using the following command:
Platform Command Windows start java -Djava.util.logging.config.file=%CXF_HOME%\etc\mylogging.properties demo.hw.server.Server
UNIX java -Djava.util.logging.config.file=$CXF_HOME/etc/mylogging.properties demo.hw.server.Server &
Because you configured the global logging and the console logger to log messages of levelINFO
, you see a lot more log messages printed to the console.
17.3. Default logging configuration file
17.3.1. Overview of Logging Configuration
logging.properties
, is located in the InstallDir/etc
directory. It configures the Apache CXF loggers to print WARNING
level messages to the console. If this level of logging is suitable for your application, you do not have to make any changes to the file before using it. You can, however, change the level of detail in the log messages. For example, you can change whether log messages are sent to the console, to a file or to both. In addition, you can specify logging at the level of individual packages.
logging.properties
file. There are, however, many other java.util.logging
configuration properties that you can set. For more information on the java.util.logging
API, see the java.util.logging
javadoc at: http://download.oracle.com/javase/1.5/docs/api/java/util/logging/package-summary.html.
17.3.2. Configuring Logging Output
Overview
java.util.logging
, uses handler classes to output log messages. Table 17.1, “Java.util.logging Handler Classes” shows the handlers that are configured in the default logging.properties
file.
Handler Class | Outputs to |
---|---|
ConsoleHandler | Outputs log messages to the console |
FileHandler | Outputs log messages to a file |
Configuring the console handler
Example 17.2. Configuring the Console Handler
handlers= java.util.logging.ConsoleHandler
Example 17.3. Console Handler Properties
- 1
- The console handler supports a separate log level configuration property. This allows you to limit the log messages printed to the console while the global logging setting can be different (see Section 17.3.3, “Configuring Logging Levels”). The default setting is
WARNING
. - 2
- Specifies the
java.util.logging
formatter class that the console handler class uses to format the log messages. The default setting is thejava.util.logging.SimpleFormatter
.
Configuring the file handler
Example 17.4. Configuring the File Handler
handlers= java.util.logging.FileHandler
Example 17.5. File Handler Configuration Properties
- 1
- Specifies the location and pattern of the output file. The default setting is your home directory.
- 2
- Specifies, in bytes, the maximum amount that the logger writes to any one file. The default setting is
50000
. If you set it to zero, there is no limit on the amount that the logger writes to any one file. - 3
- Specifies how many output files to cycle through. The default setting is
1
. - 4
- Specifies the
java.util.logging
formatter class that the file handler class uses to format the log messages. The default setting is thejava.util.logging.XMLFormatter
.
Configuring both the console handler and the file handler
Example 17.6. Configuring Both Console Logging and File Logging
handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler
17.3.3. Configuring Logging Levels
Logging levels
java.util.logging
framework supports the following levels of logging, from the least verbose to the most verbose:
SEVERE
WARNING
INFO
CONFIG
FINE
FINER
FINEST
Configuring the global logging level
Example 17.7. Configuring Global Logging Levels
.level= WARNING
Configuring logging at an individual package level
java.util.logging
framework supports configuring logging at the level of an individual package. For example, the line of code shown in Example 17.8, “Configuring Logging at the Package Level” configures logging at a SEVERE
level on classes in the com.xyz.foo package.
Example 17.8. Configuring Logging at the Package Level
com.xyz.foo.level = SEVERE
17.4. Enabling Logging at the Command Line
Overview
java.util.logging.config.file
property when you start the application. You can either specify the default logging.properties
file or a logging.properties
file that is unique to that application.
Specifying the log configuration file on application start-up
Example 17.9. Flag to Start Logging on the Command Line
-Djava.util.logging.config.file=myfile
17.5. Logging for Subsystems and Services
Overview
com.xyz.foo.level
configuration property described in the section called “Configuring logging at an individual package level” to set fine-grained logging for specified Apache CXF logging subsystems.
Apache CXF logging subsystems
Subsystem | Description |
---|---|
org.apache.cxf.aegis | Aegis binding |
org.apache.cxf.binding.coloc | colocated binding |
org.apache.cxf.binding.http | HTTP binding |
org.apache.cxf.binding.jbi | JBI binding |
org.apache.cxf.binding.object | Java Object binding |
org.apache.cxf.binding.soap | SOAP binding |
org.apache.cxf.binding.xml | XML binding |
org.apache.cxf.bus | Apache CXF bus |
org.apache.cxf.configuration | configuration framework |
org.apache.cxf.endpoint | server and client endpoints |
org.apache.cxf.interceptor | interceptors |
org.apache.cxf.jaxws | Front-end for JAX-WS style message exchange, JAX-WS handler processing, and interceptors relating to JAX-WS and configuration |
org.apache.cxf.jbi | JBI container integration classes |
org.apache.cxf.jca | JCA container integration classes |
org.apache.cxf.js | JavaScript front-end |
org.apache.cxf.transport.http | HTTP transport |
org.apache.cxf.transport.https | secure version of HTTP transport, using HTTPS |
org.apache.cxf.transport.jbi | JBI transport |
org.apache.cxf.transport.jms | JMS transport |
org.apache.cxf.transport.local | transport implementation using local file system |
org.apache.cxf.transport.servlet | HTTP transport and servlet implementation for loading JAX-WS endpoints into a servlet container |
org.apache.cxf.ws.addressing | WS-Addressing implementation |
org.apache.cxf.ws.policy | WS-Policy implementation |
org.apache.cxf.ws.rm | WS-ReliableMessaging (WS-RM) implementation |
org.apache.cxf.ws.security.wss4j | WSS4J security implementation |
Example
InstallDir/samples/ws_addressing
directory. Logging is configured in the logging.properties
file located in that directory. The relevant lines of configuration are shown in Example 17.10, “Configuring Logging for WS-Addressing”.
Example 17.10. Configuring Logging for WS-Addressing
java.util.logging.ConsoleHandler.formatter = demos.ws_addressing.common.ConciseFormatter ... org.apache.cxf.ws.addressing.soap.MAPCodec.level = INFO
README.txt
file located in the InstallDir/samples/ws_addressing
directory.
17.6. Logging Message Content
Overview
Configuring message content logging
Adding the logging feature to an endpoint
Example 17.11. Adding Logging to Endpoint Configuration
<jaxws:endpoint ...> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature"/> </jaxws:features> </jaxws:endpoint>
Adding the logging feature to a consumer
Example 17.12. Adding Logging to Client Configuration
<jaxws:client ...> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature"/> </jaxws:features> </jaxws:client>
Set logging to log INFO level messages
logging.properties
file associated with your service is configured to log INFO
level messages, as shown in Example 17.13, “Setting the Logging Level to INFO”.
Example 17.13. Setting the Logging Level to INFO
.level= INFO java.util.logging.ConsoleHandler.level = INFO
Logging SOAP messages
InstallDir/samples/wsdl_first
directory, as follows:
- Add the
jaxws:features
element shown in Example 17.14, “Endpoint Configuration for Logging SOAP Messages” to thecxf.xml
configuration file located in the wsdl_first sample's directory:Example 17.14. Endpoint Configuration for Logging SOAP Messages
<jaxws:endpoint name="{http://apache.org/hello_world_soap_http}SoapPort" createdFromAPI="true"> <jaxws:properties> <entry key="schema-validation-enabled" value="true" /> </jaxws:properties> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature"/> </jaxws:features> </jaxws:endpoint>
- The sample uses the default
logging.properties
file, which is located in theInstallDir/etc
directory. Make a copy of this file and name itmylogging.properties
. - In the
mylogging.properties
file, change the logging levels toINFO
by editing the.level
and thejava.util.logging.ConsoleHandler.level
configuration properties as follows:.level= INFO java.util.logging.ConsoleHandler.level = INFO
- Start the server using the new configuration settings in both the
cxf.xml
file and themylogging.properties
file as follows:Platform Command Windows start java -Djava.util.logging.config.file=%CXF_HOME%\etc\mylogging.properties demo.hw.server.Server
UNIX java -Djava.util.logging.config.file=$CXF_HOME/etc/mylogging.properties demo.hw.server.Server &
- Start the hello world client using the following command:
Platform Command Windows java -Djava.util.logging.config.file=%CXF_HOME%\etc\mylogging.properties demo.hw.client.Client .\wsdl\hello_world.wsdl
UNIX java -Djava.util.logging.config.file=$CXF_HOME/etc/mylogging.properties demo.hw.client.Client ./wsdl/hello_world.wsdl
Chapter 18. Deploying WS-Addressing
Abstract
18.1. Introduction to WS-Addressing
Overview
- A structure for communicating a reference to a Web service endpoint
- A set of Message Addressing Properties (MAP) that associate addressing information with a particular message
Supported specifications
Further information
18.2. WS-Addressing Interceptors
Overview
WS-Addressing Interceptors
Interceptor | Description |
---|---|
org.apache.cxf.ws.addressing.MAPAggregator | A logical interceptor responsible for aggregating the Message Addressing Properties (MAPs) for outgoing messages. |
org.apache.cxf.ws.addressing.soap.MAPCodec | A protocol-specific interceptor responsible for encoding and decoding the Message Addressing Properties (MAPs) as SOAP headers. |
18.3. Enabling WS-Addressing
Overview
- RMAssertion and WS-Policy Framework
- Using Policy Assertion in a WS-Addressing Feature
Adding WS-Addressing as a Feature
Example 18.1. client.xml and Adding WS-Addressing Feature to Client Configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:wsa="http://cxf.apache.org/ws/addressing" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <jaxws:client ...> <jaxws:features> <wsa:addressing/> </jaxws:features> </jaxws:client> </beans>
Example 18.2. server.xml and Adding WS-Addressing Feature to Server Configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:wsa="http://cxf.apache.org/ws/addressing" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <jaxws:endpoint ...> <jaxws:features> <wsa:addressing/> </jaxws:features> </jaxws:endpoint> </beans>
18.4. Configuring WS-Addressing Attributes
Overview
http://cxf.apache.org/ws/addressing
. It supports the two attributes described in Table 18.2, “WS-Addressing Attributes”.
Attribute Name | Value |
---|---|
allowDuplicates | A boolean that determines if duplicate MessageIDs are tolerated. The default setting is true . |
usingAddressingAdvisory | A boolean that indicates if the presence of the UsingAddressing element in the WSDL is advisory only; that is, its absence does not prevent the encoding of WS-Addressing headers. |
Configuring WS-Addressing attributes
allowDublicates
attribute to false
on the server endpoint:
<beans ... xmlns:wsa="http://cxf.apache.org/ws/addressing" ...> <jaxws:endpoint ...> <jaxws:features> <wsa:addressing allowDuplicates="false"/> </jaxws:features> </jaxws:endpoint> </beans>
Using a WS-Policy assertion embedded in a feature
policies
element.
Example 18.3. Using the Policies to Configure WS-Addressing
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsa="http://cxf.apache.org/ws/addressing" xmlns:wsp="http://www.w3.org/2006/07/ws-policy" xmlns:policy="http://cxf.apache.org/policy-config" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://www.w3.org/2006/07/ws-policy http://www.w3.org/2006/07/ws-policy.xsd http://cxf.apache.org/ws/addressing http://cxf.apache.org/schema/ws/addressing.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <jaxws:endpoint name="{http://cxf.apache.org/greeter_control}GreeterPort" createdFromAPI="true"> <jaxws:features> <policy:policies> <wsp:Policy xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsam:Addressing> <wsp:Policy> <wsam:NonAnonymousResponses/> </wsp:Policy> </wsam:Addressing> </wsp:Policy> <policy:policies> </jaxws:features> </jaxws:endpoint> </beans>
Chapter 19. Enabling Reliable Messaging
Abstract
19.1. Introduction to WS-RM
Overview
How WS-RM works
Figure 19.1. Web Services Reliable Messaging
- The RM source sends a
CreateSequence
protocol message to the RM destination. This contains a reference for the endpoint that receives acknowledgements (thewsrm:AcksTo
endpoint). - The RM destination sends a
CreateSequenceResponse
protocol message back to the RM source. This message contains the sequence ID for the RM sequence session. - The RM source adds an RM
Sequence
header to each message sent by the application source. This header contains the sequence ID and a unique message ID. - The RM source transmits each message to the RM destination.
- The RM destination acknowledges the receipt of the message from the RM source by sending messages that contain the RM
SequenceAcknowledgement
header. - The RM destination delivers the message to the application destination in an exactly-once-in-order fashion.
- The RM source retransmits a message that it has not yet received an acknowledgement.The first retransmission attempt is made after a base retransmission interval. Successive retransmission attempts are made, by default, at exponential back-off intervals or, alternatively, at fixed intervals. For more details, see Section 19.5, “Configuring WS-RM”.
WS-RM delivery assurances
Supported specifications
- WS-ReliableMessaging 1.0
- (Default) Corresponds to the February 2005 submission version, which is now out of date. For reasons of backward compatibility, however, this version is used as the default.Version 1.0 of WS-RM uses the following namespace:
http://schemas.xmlsoap.org/ws/2005/02/rm/
This version of WS-RM can be used with either of the following WS-Addressing versions:http://schemas.xmlsoap.org/ws/2004/08/addressing (default) http://www.w3.org/2005/08/addressing
Strictly speaking, in order to comply with the February 2005 submission version of WS-RM, you ought to use the first of these WS-Addressing versions (which is the default in Apache CXF). But most other Web service implementations have switched to the more recent WS-Addressing specification, so Apache CXF allows you to choose the WS-A version, to facilitate interoperability (see Section 19.4, “Runtime Control”). - WS-ReliableMessaging 1.1/1.2
- Corresponds to the official 1.1/1.2 Web Services Reliable Messaging specification.Versions 1.1 and 1.2 of WS-RM uses the following namespace:
http://docs.oasis-open.org/ws-rx/wsrm/200702
The 1.1 and 1.2 versions of WS-RM use the following WS-Addressing version:http://www.w3.org/2005/08/addressing
Selecting the WS-RM version
- Server side
- On the provider side, Apache CXF adapts to whichever version of WS-ReliableMessaging is used by the client and responds appropriately.
- Client side
- On the client side, the WS-RM version is determined either by the namespace that you use in the client configuration (see Section 19.5, “Configuring WS-RM”) or by overriding the WS-RM version at run time, using the runtime control options (see Section 19.4, “Runtime Control”).
19.2. WS-RM Interceptors
Overview
Apache CXF WS-RM Interceptors
Interceptor | Description |
---|---|
org.apache.cxf.ws.rm.RMOutInterceptor |
Deals with the logical aspects of providing reliability guarantees for outgoing messages.
Responsible for sending the
CreateSequence requests and waiting for their CreateSequenceResponse responses.
Also responsible for aggregating the sequence properties—ID and message number—for an application message.
|
org.apache.cxf.ws.rm.RMInInterceptor | Responsible for intercepting and processing RM protocol messages and SequenceAcknowledgement messages that are piggybacked on application messages. |
org.apache.cxf.ws.rm.RMCaptureInInterceptor
|
Caching incoming messages for persistent storage.
|
org.apache.cxf.ws.rm.RMDeliveryInterceptor
|
Assuring InOrder delivery of messages to the application.
|
org.apache.cxf.ws.rm.soap.RMSoapInterceptor | Responsible for encoding and decoding the reliability properties as SOAP headers. |
org.apache.cxf.ws.rm.RetransmissionInterceptor | Responsible for creating copies of application messages for future resending. |
Enabling WS-RM
RMOutInterceptor
sends a CreateSequence
request and waits to process the original application message until it receives the CreateSequenceResponse
response. In addition, the WS-RM interceptors add the sequence headers to the application messages and, on the destination side, extract them from the messages. It is not necessary to make any changes to your application code to make the exchange of messages reliable.
Configuring WS-RM Attributes
1
).
19.3. Enabling WS-RM
Overview
- Explicitly, by adding them to the dispatch chains using Spring beans
- Implicitly, using WS-Policy assertions, which cause the Apache CXF runtime to transparently add the interceptors on your behalf.
Spring beans: explicitly adding interceptors
InstallDir/samples/ws_rm
directory. The configuration file, ws-rm.cxf
, shows the WS-RM and WS-Addressing interceptors being added one-by-one as Spring beans (see Example 19.1, “Enabling WS-RM Using Spring Beans”).
Example 19.1. Enabling WS-RM Using Spring Beans
<?xml version="1.0" encoding="UTF-8"?> 1<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/ beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 2 <bean id="mapAggregator" class="org.apache.cxf.ws.addressing.MAPAggregator"/> <bean id="mapCodec" class="org.apache.cxf.ws.addressing.soap.MAPCodec"/> 3 <bean id="rmLogicalOut" class="org.apache.cxf.ws.rm.RMOutInterceptor"> <property name="bus" ref="cxf"/> </bean> <bean id="rmLogicalIn" class="org.apache.cxf.ws.rm.RMInInterceptor"> <property name="bus" ref="cxf"/> </bean> <bean id="rmCodec" class="org.apache.cxf.ws.rm.soap.RMSoapInterceptor"/> <bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl"> 4 <property name="inInterceptors"> <list> <ref bean="mapAggregator"/> <ref bean="mapCodec"/> <ref bean="rmLogicalIn"/> <ref bean="rmCodec"/> </list> </property> 5 <property name="inFaultInterceptors"> <list> <ref bean="mapAggregator"/> <ref bean="mapCodec"/> <ref bean="rmLogicalIn"/> <ref bean="rmCodec"/> </list> </property> 6 <property name="outInterceptors"> <list> <ref bean="mapAggregator"/> <ref bean="mapCodec"/> <ref bean="rmLogicalOut"/> <ref bean="rmCodec"/> </list> </property> 7 <property name="outFaultInterceptors"> <list> <ref bean="mapAggregator"> <ref bean="mapCodec"/> <ref bean="rmLogicalOut"/> <ref bean="rmCodec"/> </list> </property> </bean> </beans>
- 1
- A Apache CXF configuration file is a Spring XML file. You must include an opening Spring
beans
element that declares the namespaces and schema files for the child elements that are encapsulated by thebeans
element. - 2
- Configures each of the WS-Addressing interceptors—
MAPAggregator
andMAPCodec
. For more information on WS-Addressing, see Chapter 18, Deploying WS-Addressing. - 3
- Configures each of the WS-RM interceptors—
RMOutInterceptor
,RMInInterceptor
, andRMSoapInterceptor
. - 4
- Adds the WS-Addressing and WS-RM interceptors to the interceptor chain for inbound messages.
- 5
- Adds the WS-Addressing and WS-RM interceptors to the interceptor chain for inbound faults.
- 6
- Adds the WS-Addressing and WS-RM interceptors to the interceptor chain for outbound messages.
- 7
- Adds the WS-Addressing and WS-RM interceptors to the interceptor chain for outbound faults.
WS-Policy framework: implicitly adding interceptors
- Add the policy feature to your client and server endpoint. Example 19.2, “Configuring WS-RM using WS-Policy” shows a reference bean nested within a
jaxws:feature
element. The reference bean specifies theAddressingPolicy
, which is defined as a separate element within the same configuration file.Example 19.2. Configuring WS-RM using WS-Policy
<jaxws:client> <jaxws:features> <ref bean="AddressingPolicy"/> </jaxws:features> </jaxws:client> <wsp:Policy wsu:Id="AddressingPolicy" xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsam:Addressing> <wsp:Policy> <wsam:NonAnonymousResponses/> </wsp:Policy> </wsam:Addressing> </wsp:Policy>
- Add a reliable messaging policy to the
wsdl:service
element—or any other WSDL element that can be used as an attachment point for policy or policy reference elements—to your WSDL file, as shown in Example 19.3, “Adding an RM Policy to Your WSDL File”.Example 19.3. Adding an RM Policy to Your WSDL File
<wsp:Policy wsu:Id="RM" xmlns:wsp="http://www.w3.org/2006/07/ws-policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsam:Addressing xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsp:Policy/> </wsam:Addressing> <wsrmp:RMAssertion xmlns:wsrmp="http://schemas.xmlsoap.org/ws/2005/02/rm/policy"> <wsrmp:BaseRetransmissionInterval Milliseconds="10000"/> </wsrmp:RMAssertion> </wsp:Policy> ... <wsdl:service name="ReliableGreeterService"> <wsdl:port binding="tns:GreeterSOAPBinding" name="GreeterPort"> <soap:address location="http://localhost:9020/SoapContext/GreeterPort"/> <wsp:PolicyReference URI="#RM" xmlns:wsp="http://www.w3.org/2006/07/ws-policy"/> </wsdl:port> </wsdl:service>
19.4. Runtime Control
Overview
org.apache.cxf.ws.rm.RMManager
class.
Runtime control options
org.apache.cxf.ws.rm.RMManager
class.
Key | Description |
---|---|
WSRM_VERSION_PROPERTY
|
String WS-RM version namespace (
http://schemas.xmlsoap.org/ws/2005/02/rm/ or http://docs.oasis-open.org/ws-rx/wsrm/200702 ).
|
WSRM_WSA_VERSION_PROPERTY
| String WS-Addressing version namespace (http://schemas.xmlsoap.org/ws/2004/08/addressing or http://www.w3.org/2005/08/addressing ) - this property is ignored unless you're using the http://schemas.xmlsoap.org/ws/2005/02/rm/ RM namespace). |
WSRM_LAST_MESSAGE_PROPERTY
| Boolean value true to tell the WS-RM code that the last message is being sent, allowing the code to close the WS-RM sequence and release resources (as of the 3.0.0 version of CXF, the WS-RM will close the RM sequence by default, when you close your client). |
WSRM_INACTIVITY_TIMEOUT_PROPERTY
| Long inactivity timeout in milliseconds. |
WSRM_RETRANSMISSION_INTERVAL_PROPERTY
| Long base retransmission interval in milliseconds. |
WSRM_EXPONENTIAL_BACKOFF_PROPERTY
| Boolean exponential back-off flag. |
WSRM_ACKNOWLEDGEMENT_INTERVAL_PROPERTY
| Long acknowledgement interval in milliseconds. |
Controlling WS-RM through JMX
org.apache.cxf.ws.rm.ManagedRMManager
and org.apache.cxf.ws.rm.ManagedRMEndpoint
, but these operations include viewing the current RM state down to the individual message level. You can also use JXM to close or terminate a WS-RM sequence, and to receive notification of when previously-sent messages are acknowledged by the remote RM endpoint.
Example of JMX control
// Java private static class AcknowledgementListener implements NotificationListener { private volatile long lastAcknowledgement; @Override public void handleNotification(Notification notification, Object handback) { if (notification instanceof AcknowledgementNotification) { AcknowledgementNotification ack = (AcknowledgementNotification)notification; lastAcknowledgement = ack.getMessageNumber(); } } // initialize client ... // attach to JMX bean for notifications // NOTE: you must have sent at least one message to initialize RM before executing this code Endpoint ep = ClientProxy.getClient(client).getEndpoint(); InstrumentationManager im = bus.getExtension(InstrumentationManager.class); MBeanServer mbs = im.getMBeanServer(); RMManager clientManager = bus.getExtension(RMManager.class); ObjectName name = RMUtils.getManagedObjectName(clientManager, ep); System.out.println("Looking for endpoint name " + name); AcknowledgementListener listener = new AcknowledgementListener(); mbs.addNotificationListener(name, listener, null, null); // send messages using RM with acknowledgement status reported to listener ...
19.5. Configuring WS-RM
19.5.1. Configuring Apache CXF-Specific WS-RM Attributes
Overview
rmManager
Spring bean. Add the following to your configuration file:
- The
http://cxf.apache.org/ws/rm/manager
namespace to your list of namespaces. - An
rmManager
Spring bean for the specific attribute that your want to configure.
Example 19.4. Configuring Apache CXF-Specific WS-RM Attributes
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/ws/rm/manager http://cxf.apache.org/schemas/configuration/wsrm-manager.xsd"> ... <wsrm-mgr:rmManager> <!-- ...Your configuration goes here --> </wsrm-mgr:rmManager>
Children of the rmManager Spring bean
rmManager
Spring bean, defined in the http://cxf.apache.org/ws/rm/manager
namespace.
Element | Description |
---|---|
RMAssertion | An element of type RMAssertion |
deliveryAssurance | An element of type DeliveryAssuranceType that describes the delivery assurance that should apply |
sourcePolicy | An element of type SourcePolicyType that allows you to configure details of the RM source |
destinationPolicy | An element of type DestinationPolicyType that allows you to configure details of the RM destination |
Example
19.5.2. Configuring Standard WS-RM Policy Attributes
Overview
WS-Policy RMAssertion Children
http://schemas.xmlsoap.org/ws/2005/02/rm/policy
namespace:
Name | Description |
---|---|
InactivityTimeout | Specifies the amount of time that must pass without receiving a message before an endpoint can consider an RM sequence to have been terminated due to inactivity. |
BaseRetransmissionInterval | Sets the interval within which an acknowledgement must be received by the RM Source for a given message. If an acknowledgement is not received within the time set by the BaseRetransmissionInterval , the RM Source will retransmit the message. |
ExponentialBackoff |
Indicates the retransmission interval will be adjusted using the commonly known exponential backoff algorithm (Tanenbaum).
For more information, see Computer Networks, Andrew S. Tanenbaum, Prentice Hall PTR, 2003.
|
AcknowledgementInterval | In WS-RM, acknowledgements are sent on return messages or sent stand-alone. If a return message is not available to send an acknowledgement, an RM Destination can wait for up to the acknowledgement interval before sending a stand-alone acknowledgement. If there are no unacknowledged messages, the RM Destination can choose not to send an acknowledgement. |
More detailed reference information
RMAssertion in rmManager Spring bean
RMAssertion
within a Apache CXF rmManager
Spring bean. This is the best approach if you want to keep all of your WS-RM configuration in the same configuration file; that is, if you want to configure Apache CXF-specific attributes and standard WS-RM policy attributes in the same file.
- A standard WS-RM policy attribute,
BaseRetransmissionInterval
, configured using anRMAssertion
within anrmManager
Spring bean. - An Apache CXF-specific RM attribute,
intraMessageThreshold
, configured in the same configuration file.
Example 19.5. Configuring WS-RM Attributes Using an RMAssertion in an rmManager Spring Bean
<beans xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy" xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager" ...> <wsrm-mgr:rmManager id="org.apache.cxf.ws.rm.RMManager"> <wsrm-policy:RMAssertion> <wsrm-policy:BaseRetransmissionInterval Milliseconds="4000"/> </wsrm-policy:RMAssertion> <wsrm-mgr:destinationPolicy> <wsrm-mgr:acksPolicy intraMessageThreshold="0" /> </wsrm-mgr:destinationPolicy> </wsrm-mgr:rmManager> </beans>
Policy within a feature
Example 19.6. Configuring WS-RM Attributes as a Policy within a Feature
<xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsa="http://cxf.apache.org/ws/addressing" xmlns:wsp="http://www.w3.org/2006/07/ws-policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://www.w3.org/2006/07/ws-policy http://www.w3.org/2006/07/ws-policy.xsd http://cxf.apache.org/ws/addressing http://cxf.apache.org/schema/ws/addressing.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <jaxws:endpoint name="{http://cxf.apache.org/greeter_control}GreeterPort" createdFromAPI="true"> <jaxws:features> <wsp:Policy> <wsrm:RMAssertion xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm/policy"> <wsrm:AcknowledgementInterval Milliseconds="200" /> </wsrm:RMAssertion> <wsam:Addressing xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsp:Policy> <wsam:NonAnonymousResponses/> </wsp:Policy> </wsam:Addressing> </wsp:Policy> </jaxws:features> </jaxws:endpoint> </beans>
WSDL file
External attachment
Example 19.7. Configuring WS-RM in an External Attachment
<attachments xmlns:wsp="http://www.w3.org/2006/07/ws-policy" xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsp:PolicyAttachment> <wsp:AppliesTo> <wsa:EndpointReference> <wsa:Address>http://localhost:9020/SoapContext/GreeterPort</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> <wsp:Policy> <wsam:Addressing xmlns:wsam="http://www.w3.org/2007/02/addressing/metadata"> <wsp:Policy/> </wsam:Addressing> <wsrmp:RMAssertion xmlns:wsrmp="http://schemas.xmlsoap.org/ws/2005/02/rm/policy"> <wsrmp:BaseRetransmissionInterval Milliseconds="30000"/> </wsrmp:RMAssertion> </wsp:Policy> </wsp:PolicyAttachment> </attachments>/
19.5.3. WS-RM Configuration Use Cases
Overview
RMAssertion
within an rmManager
Spring bean is shown. For details of how to set such attributes as a policy within a feature; in a WSDL file, or in an external attachment, see Section 19.5.2, “Configuring Standard WS-RM Policy Attributes”.
Base retransmission interval
BaseRetransmissionInterval
element specifies the interval at which an RM source retransmits a message that has not yet been acknowledged. It is defined in the http://schemas.xmlsoap.org/ws/2005/02/rm/wsrm-policy.xsd schema file. The default value is 3000 milliseconds.
Example 19.8. Setting the WS-RM Base Retransmission Interval
<beans xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy ...> <wsrm-mgr:rmManager id="org.apache.cxf.ws.rm.RMManager"> <wsrm-policy:RMAssertion> <wsrm-policy:BaseRetransmissionInterval Milliseconds="4000"/> </wsrm-policy:RMAssertion> </wsrm-mgr:rmManager> </beans>
Exponential backoff for retransmission
ExponentialBackoff
element determines if successive retransmission attempts for an unacknowledged message are performed at exponential intervals.
ExponentialBackoff
element enables this feature. An exponential backoff ratio of 2
is used by default.
Example 19.9. Setting the WS-RM Exponential Backoff Property
<beans xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy ...> <wsrm-mgr:rmManager id="org.apache.cxf.ws.rm.RMManager"> <wsrm-policy:RMAssertion> <wsrm-policy:ExponentialBackoff="4"/> </wsrm-policy:RMAssertion> </wsrm-mgr:rmManager> </beans>
Acknowledgement interval
AcknowledgementInterval
element specifies the interval at which the WS-RM destination sends asynchronous acknowledgements. These are in addition to the synchronous acknowledgements that it sends on receipt of an incoming message. The default asynchronous acknowledgement interval is 0
milliseconds. This means that if the AcknowledgementInterval
is not configured to a specific value, acknowledgements are sent immediately (that is, at the first available opportunity).
- The RM destination is using a non-anonymous
wsrm:acksTo
endpoint. - The opportunity to piggyback an acknowledgement on a response message does not occur before the expiry of the acknowledgement interval.
Example 19.10. Setting the WS-RM Acknowledgement Interval
<beans xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy ...> <wsrm-mgr:rmManager id="org.apache.cxf.ws.rm.RMManager"> <wsrm-policy:RMAssertion> <wsrm-policy:AcknowledgementInterval Milliseconds="2000"/> </wsrm-policy:RMAssertion> </wsrm-mgr:rmManager> </beans>
Maximum unacknowledged messages threshold
maxUnacknowledged
attribute sets the maximum number of unacknowledged messages that can accrue per sequence before the sequence is terminated.
Example 19.11. Setting the WS-RM Maximum Unacknowledged Message Threshold
<beans xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager ...> <wsrm-mgr:reliableMessaging> <wsrm-mgr:sourcePolicy> <wsrm-mgr:sequenceTerminationPolicy maxUnacknowledged="20" /> </wsrm-mgr:sourcePolicy> </wsrm-mgr:reliableMessaging> </beans>
Maximum length of an RM sequence
maxLength
attribute sets the maximum length of a WS-RM sequence. The default value is 0
, which means that the length of a WS-RM sequence is unbound.
Example 19.12. Setting the Maximum Length of a WS-RM Message Sequence
<beans xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager ...> <wsrm-mgr:reliableMessaging> <wsrm-mgr:sourcePolicy> <wsrm-mgr:sequenceTerminationPolicy maxLength="100" /> </wsrm-mgr:sourcePolicy> </wsrm-mgr:reliableMessaging> </beans>
Message delivery assurance policies
AtMostOnce
— The RM destination delivers the messages to the application destination only once. If a message is delivered more than once an error is raised. It is possible that some messages in a sequence may not be delivered.AtLeastOnce
— The RM destination delivers the messages to the application destination at least once. Every message sent will be delivered or an error will be raised. Some messages might be delivered more than once.InOrder
— The RM destination delivers the messages to the application destination in the order that they are sent. This delivery assurance can be combined with theAtMostOnce
orAtLeastOnce
assurances.
Example 19.13. Setting the WS-RM Message Delivery Assurance Policy
<beans xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager ...> <wsrm-mgr:reliableMessaging> <wsrm-mgr:deliveryAssurance> <wsrm-mgr:AtLeastOnce /> </wsrm-mgr:deliveryAssurance> </wsrm-mgr:reliableMessaging> </beans>
19.6. Configuring WS-RM Persistence
Overview
How it works
- At the RM source endpoint, an outgoing message is persisted before transmission. It is evicted from the persistent store after the acknowledgement is received.
- After a recovery from crash, it recovers the persisted messages and retransmits until all the messages have been acknowledged. At that point, the RM sequence is closed.
- At the RM destination endpoint, an incoming message is persisted, and upon a successful store, the acknowledgement is sent. When a message is successfully dispatched, it is evicted from the persistent store.
- After a recovery from a crash, it recovers the persisted messages and dispatches them. It also brings the RM sequence to a state where new messages are accepted, acknowledged, and delivered.
Enabling WS-persistence
Example 19.14. Configuration for the Default WS-RM Persistence Store
<bean id="RMTxStore" class="org.apache.cxf.ws.rm.persistence.jdbc.RMTxStore"/> <wsrm-mgr:rmManager id="org.apache.cxf.ws.rm.RMManager"> <property name="store" ref="RMTxStore"/> </wsrm-mgr:rmManager>
Configuring WS-persistence
Example 19.15. Configuring the JDBC Store for WS-RM Persistence
<bean id="RMTxStore" class="org.apache.cxf.ws.rm.persistence.jdbc.RMTxStore"> <property name="driverClassName" value="com.acme.jdbc.Driver"/> <property name="url" value="jdbc:acme:rmdb;create=true"/> </bean>
Chapter 20. Enabling High Availability
Abstract
20.1. Introduction to High Availability
Overview
HA with static failover
20.2. Enabling HA with Static Failover
Overview
Encode replica details in your service WSDL file
Example 20.1. Enabling HA with Static Failover: WSDL File
1<wsdl:service name="ClusteredService"> 2 <wsdl:port binding="tns:Greeter_SOAPBinding" name="Replica1"> <soap:address location="http://localhost:9001/SoapContext/Replica1"/> </wsdl:port> 3 <wsdl:port binding="tns:Greeter_SOAPBinding" name="Replica2"> <soap:address location="http://localhost:9002/SoapContext/Replica2"/> </wsdl:port> 4 <wsdl:port binding="tns:Greeter_SOAPBinding" name="Replica3"> <soap:address location="http://localhost:9003/SoapContext/Replica3"/> </wsdl:port> </wsdl:service>
- 1
- Defines a service,
ClusterService
, which is exposed on three ports:Replica1
Replica2
Replica3
- 2
- Defines
Replica1
to expose theClusterService
as a SOAP over HTTP endpoint on port9001
. - 3
- Defines
Replica2
to expose theClusterService
as a SOAP over HTTP endpoint on port9002
. - 4
- Defines
Replica3
to expose theClusterService
as a SOAP over HTTP endpoint on port9003
.
Add the clustering feature to your client configuration
Example 20.2. Enabling HA with Static Failover: Client Configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:clustering="http://cxf.apache.org/clustering" xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <jaxws:client name="{http://apache.org/hello_world_soap_http}Replica1" createdFromAPI="true"> <jaxws:features> <clustering:failover/> </jaxws:features> </jaxws:client> <jaxws:client name="{http://apache.org/hello_world_soap_http}Replica2" createdFromAPI="true"> <jaxws:features> <clustering:failover/> </jaxws:features> </jaxws:client> <jaxws:client name="{http://apache.org/hello_world_soap_http}Replica3" createdFromAPI="true"> <jaxws:features> <clustering:failover/> </jaxws:features> </jaxws:client> </beans>
20.3. Configuring HA with Static Failover
Overview
Configuring a random strategy
Example 20.3. Configuring a Random Strategy for Static Failover
<beans ...> 1 <bean id="Random" class="org.apache.cxf.clustering.RandomStrategy"/> <jaxws:client name="{http://apache.org/hello_world_soap_http}Replica3" createdFromAPI="true"> <jaxws:features> <clustering:failover> 2 <clustering:strategy> <ref bean="Random"/> </clustering:strategy> </clustering:failover> </jaxws:features> </jaxws:client> </beans>
Chapter 21. Enabling High Availability in Fuse Fabric
Abstract
21.1. Load Balancing Cluster
21.1.1. Introduction to Load Balancing
Overview
Fuse Fabric
Load-balancing cluster
Figure 21.1. Fabric Load Balancing for Apache CXF
http://localhost:8185/Foo
and http://localhost:8186/Foo
. For both of these servers, the load balancer feature is configured to store the cluster endpoints under the path, demo/lb
, in the fabric registry.
demo/lb
, in the fabric registry. Because the demo/lb
path is associated with multiple endpoint addresses, fabric implements a random load balancing algorithm to choose one of the available URIs to connect to.
FabricLoadBalancerFeature
io.fabric8.cxf.FabricLoadBalancerFeature
FabricLoadBalancerFeature
class exposes the following bean properties:
-
fabricPath
- This property specifies a node in the fabric registry (specified relative to the base node,
/fabric/cxf/endpoints
) that is used to store the data for a particular endpoint cluster. -
curator
- A proxy reference to the OSGi service exposed by the fabric agent (of type,
org.apache.curator.framework.CuratorFramework
). -
maximumConnectionTimeout
- The maximum length of time to attempt to connect to the fabric agent, specified in milliseconds. The default is 10000 (10 seconds).
-
connectionRetryTime
- How long to wait between connection attempts, specified in milliseconds. The default is 100.
-
loadBalanceStrategy
- By implementing a bean of type
io.fabric8.cxf.LoadBalanceStrategy
and setting this property, you can customise the load balancing algorithm used by the load balancing feature.
Prerequisites
Maven dependency
fabric-cxf
Maven artifact. Add the following dependency to your project's POM file:
<dependency> <groupId>io.fabric8</groupId> <artifactId>fabric-cxf</artifactId> <version>6.2.0.redhat-133</version> </dependency>
OSGi package import
io.fabric8.cxf
to the list of imported packages. For example, using the Maven bundle plug-in, you can specify this package import by adding io.fabric8.cxf
to the comma-separated list in the Import-Package
element, as follows:
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.2.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Import-Package>
...
io.fabric8.cxf,
*
</Import-Package>
...
</instructions>
</configuration>
</plugin>
Fabric deployment
Required feature
fabric-cxf
Apache Karaf feature to be installed in the container. In the context of a fabric, this means you must add the fabric-cxf
feature to the relevant deployment profile. For example, if you are using the cxf-lb-server
profile to deploy a load-balancing WS server, you can add the fabric-cxf
feature by entering the following console command:
JBossFuse:karaf@root> profile-edit -f fabric-cxf cxf-lb-server
21.1.2. Configure the Server
Overview
Prerequisites
Blueprint XML
FabricLoadBalancerFeature
, to an Apache CXF bus. Any Apache CXF endpoints subsequently created on this bus will automatically have the load-balancer feature enabled.
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... xmlns:cxf="http://cxf.apache.org/blueprint/core" ... > ... <reference id="curator" interface="org.apache.curator.framework.CuratorFramework" /> <!-- The FabricFailOverFeature will try to access other service endpoint with round rad --> <bean id="fabricLoadBalancerFeature" class="io.fabric8.cxf.FabricLoadBalancerFeature"> <property name="curator" ref="curator" /> <property name="fabricPath" value="cxf/demo" /> </bean> <!-- setup the feature on the bus to help publish the services to the fabric--> <cxf:bus bus="cxf"> <cxf:features> <ref component-id="fabricLoadBalancerFeature"/> </cxf:features> </cxf:bus> ... </blueprint>
curator
reference- The
curator
reference is a proxy of the local fabric agent, which it accesses through theorg.apache.curator.framework.CuratorFramework
interface. This reference is needed in order to integrate the load balancer feature with the underlying fabric. FabricLoadBalancerFeature
bean- The
FabricLoadBalancerFeature
bean is initialized with the following properties:-
curator
- A reference to the Apache Curator client,
CuratorFramework
. -
fabricPath
- The path of a node in the fabric registry, where the cluster data is stored (for example, the addresses of the endpoints in the load-balancing cluster). The node path is specified relative to the base node,
/fabric/cxf/endpoints
.
-
- Apache CXF bus
- The
cxf:bus
element installs the fabric load balancer feature in the default bus instance.
Example using Blueprint XML
Example 21.1. WS Server with Fabric Load Balancer Feature
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/blueprint/core" xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws" xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0" xsi:schemaLocation=" http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd http://cxf.apache.org/schemas/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd http://cxf.apache.org/blueprint/jaxws http://cxf.apache.org/blueprint/jaxws.xsd "> <reference id="curator" interface="org.apache.curator.framework.CuratorFramework" /> <!-- The FabricFailOverFeature will try to access other service endpoint with round rad --> <bean id="fabicLoadBalancerFeature" class="io.fabric8.cxf.FabricLoadBalancerFeature"> <property name="curator" ref="curator" /> <property name="fabricPath" value="cxf/demo" /> </bean> <!-- setup the feature on the bus to help publish the services to the fabric--> <cxf:bus bus="cxf"> <cxf:features> <ref component-id="fabicLoadBalancerFeature"/> </cxf:features> </cxf:bus> <bean id="hello1" class="io.fabric8.demo.cxf.server.HelloImpl"> <property name="hello" value="Hi"/> </bean> <bean id="hello2" class="io.fabric8.demo.cxf.server.HelloImpl"> <property name="hello" value="Hello"/> </bean> <!-- TODO: We should use address in the form of http://$[bind.address]:$[app1.port]/server/server1, but currently only fuseenterprise has appX.port system properties defined --> <!-- publish the service with the address of fail, cxf client will get the simulated IOException --> <jaxws:server id="service1" serviceClass="io.fabric8.demo.cxf.Hello" address="http://localhost:9000/server/server1"> <jaxws:serviceBean> <ref component-id="hello1" /> </jaxws:serviceBean> </jaxws:server> <jaxws:server id="service2" serviceClass="io.fabric8.demo.cxf.Hello" address="http://localhost:9000/server/server2"> <jaxws:serviceBean> <ref component-id="hello2" /> </jaxws:serviceBean> </jaxws:server> </blueprint>
- Enabling the fabric load balancing feature—the fabric load balancing feature is installed in the default bus instance, as previously described. In this example, the
fabricPath
property is set to the value,cxf/demo
. - Creating the WS endpoints—create the WS endpoints in the usual way, using the
jaxws:server
element (this can be used as an alternative to thejaxws:endpoint
element). By default, this endpoint is automatically associated with the default bus instance, which has load balancing enabled.
21.1.3. Configure the Client
Overview
Prerequisites
Blueprint XML
FabricLoadBalancerFeature
, directly into a WS client proxy instance.
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... xmlns:jaxws="http://cxf.apache.org/blueprint/jaxws" xmlns:cxf="http://cxf.apache.org/blueprint/core" ... > <!-- Create a client proxy, with load balancing enabled --> <jaxws:client id="ClientProxyBeanID" address="http://dummyaddress" serviceClass="SEI"> <jaxws:features> <ref component-id="fabricLoadBalancerFeature" /> </jaxws:features> </jaxws:client> ... <reference id="curator" interface="org.apache.curator.framework.CuratorFramework" /> <!-- The FabricFailOverFeature will try to access other service endpoint with round rad --> <bean id="fabricLoadBalancerFeature" class="io.fabric8.cxf.FabricLoadBalancerFeature"> <property name="curator" ref="curator" /> <property name="fabricPath" value="ZKPath" /> </bean> ... </blueprint>
jaxws:features
element (or, as in this case, by inserting a bean reference to the actual instance). The following beans are used to initialise the fabric load-balancer feature:
curator
reference- The
curator
reference is a proxy of the local fabric agent, which it accesses through theorg.apache.curator.framework.CuratorFramework
interface. This reference is needed in order to integrate the load balancer feature with the underlying fabric. FabricLoadBalancerFeature
bean- The
FabricLoadBalancerFeature
bean is initialized with the following properties:-
curator
- A reference to the Apache Curator client,
curator
. -
fabricPath
- The path of a node in the fabric registry, where the cluster data is stored (for example, the addresses of the endpoints in the load-balancing cluster). The node path is specified relative to the base node,
/fabric/cxf/endpoints
.
-
Java
Hello
Web service.
// Java package io.fabric8.demo.cxf.client; import org.apache.cxf.feature.AbstractFeature; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import io.fabric8.cxf.FabricLoadBalancerFeature; import io.fabric8.demo.cxf.Hello; import java.util.ArrayList; import java.util.List; public class Client { private Hello hello; public void initializeHelloProxy() { // The feature will try to create a zookeeper client itself // by checking the system property of zookeeper.url FabricLoadBalancerFeature feature = new FabricLoadBalancerFeature(); // Feature will use this path to locate the service feature.setFabricPath("demo/lb"); ClientProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean(); clientFactory.setServiceClass(ClientProxyFactoryBean.class); // The address is not the actual address that the client will access clientFactory.setAddress("http://dummyaddress"); List<AbstractFeature> features = new ArrayList<AbstractFeature>(); features.add(feature); // we need to setup the feature on the client factory clientFactory.setFeatures(features); // Create the proxy of Hello hello = clientFactory.create(Hello.class); } public static void main(String args[]) { initializeHelloProxy(); ... } }
fabricPath
property is set to the value, demo/lb
(which matches the example value used by the server in Example 21.1, “WS Server with Fabric Load Balancer Feature”).
http://dummyaddress
, because this value is not used. When the client is initialized, the load balancer feature substitutes the address value retrieved from the demo/lb
node of the fabric registry.
21.2. Failover Cluster
Overview
Failover cluster
Figure 21.2. Fabric Failover for Apache CXF
http://localhost:8185/Foo
and http://localhost:8186/Foo
. In both servers, the failover feature is configured to store the cluster endpoints under the path, demo/fo
, in the fabric registry. The cluster endpoints stored under demo/fo
are ordered. The first endpoint in the cluster is the master and all of the other endpoints are slaves.
- When the WS client starts, it is configured to look up the cluster path,
demo/fo
, in the fabric registry. The failover feature initially returns the first address registered underdemo/fo
(the master). - At some point, the master server could fail. The client determines whether the master has failed by catching the exception that occurs when it tries to make an invocation: if the caught exception matches one of the exceptions in a specified list (by default, just the
java.io.IOException)
, the master is deemed to have failed and the client now ignores the corresponding address entry underdemo/fo
. - The client selects the next address entry under
demo/fo
and attempts to connect to that server. Assuming that this server is healthy, it is effectively the new master. - At some point in the future, if the failed old master is restarted successfully, it creates a new address entry under
demo/fo
after the existing entries, and is then available to clients, in case the other server (or servers) fail.
FabricFailOverFeature
io.fabric8.cxf.FabricFailOverFeature
FabricFailOverFeature
class exposes the following bean properties:
-
fabricPath
- This property specifies a node in the fabric registry (specified relative to the base node,
/fabric/cxf/endpoints
) that is used to store the data for a particular endpoint cluster. -
curator
- A proxy reference to the OSGi service (of type,
org.apache.curator.framework.CuratorFramework
) for the Apache Curator client, which is exposed by the fabric agent. -
maximumConnectionTimeout
- The maximum length of time to attempt to connect to the fabric agent, specified in milliseconds. The default is 10000 (10 seconds).
-
connectionRetryTime
- How long to wait between connection attempts, specified in milliseconds. The default is 100.
-
exceptions
- A semicolon-separated list of exceptions that signal to the client that a server has failed. If not set, this property defaults to
java.io.IOException
.For example, you could set theexceptions
property to a value like the following:java.io.IOException;javax.xml.ws.soap.SOAPFaultException
Blueprint XML
FabricLoadBalancerFeature
bean, you must instantiate and reference a FabricFailOverFeature
bean.
FabricFailOverFeature
bean instance as follows:
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... xmlns:cxf="http://cxf.apache.org/blueprint/core" ... > ... <!-- Reference the fabric agent --> <reference id="curator" interface="org.apache.curator.framework.CuratorFramework" /> <!-- Create the Fabric load balancer feature --> <bean id="failoverFeature" class="io.fabric8.cxf.FabricFailOverFeature"> <property name="curator" ref="curator" /> <property name="fabricPath" value="ZKPath" /> </bean> ... </blueprint>
fabricPath
property and to reference the appropriate bean ID (failoverFeature
in the preceding example).
Chapter 22. Packaging an Application
Abstract
Creating a bundle
Required bundle
org.apache.cxf.cxf-bundle
. This bundle needs to be installed in the JBoss Fuse container before your application's bundle can be started.
Required packages
- javax.jws
- javax.wsdl
- META-INF.cxf
- META-INF.cxf.osgi
- org.apache.cxf.bus
- org.apache.cxf.bus.spring
- org.apache.cxf.bus.resource
- org.apache.cxf.configuration.spring
- org.apache.cxf.resource
- org.apache.servicemix.cxf.transport.http_osgi
- org.springframework.beans.factory.config
Example
Example 22.1. Apache CXF Application Manifest
Manifest-Version: 1.0 Built-By: FinnMcCumial Created-By: Apache Maven Bundle Plugin Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt Import-Package: javax.jws,javax.wsdl,META-INF.cxf,META-INF.cxf.osgi, org.apache.cxf.bus,org.apache.cxf.bus.spring,org.apache.bus.resource, org.apache.cxf.configuration.spring, org.apache.cxf.resource, org.apache.servicemix.cxf.transport.http_cxf, org.springframework.beans.factory.config Bnd-LastModified: 1222079507224 Bundle-Version: 4.0.0.fuse Bundle-Name: Fuse CXF Example Bundle-Description: This is a sample CXF manifest. Build-Jdk: 1.5.0_08 Private-Package: org.apache.servicemix.examples.cxf Required-Bundle: org.apache.cxf.cxf-bundle Bundle-ManifestVersion: 2 Bundle-SymbolicName: cxf-wsdl-first-osgi Tool: Bnd-0.0.255
Chapter 23. Deploying an Application
Abstract
Overview
- Rely on the hot deployment mechanism.
- Use the console.
Hot deployment
/deploy
. Any bundle placed in this folder is installed into the container. If its dependencies can be resolved, the bundle is activated.
Deploying from the console
servicemix>
osgi install -s file:/home/finn/ws/widgetapp.jar
widgetapp.jar
which is located in /home/finn/ws
.
-s
flag. That will install the bundle without attempting to start it. You will then have to manually start the bundle using the osgi start command.
Refreshing an application
Stopping an application
Uninstalling an application
Appendix C. Apache CXF Binding IDs
Table of Binding IDs
Binding | ID |
---|---|
CORBA | http://cxf.apache.org/bindings/corba |
HTTP/REST | http://apache.org/cxf/binding/http |
SOAP 1.1 | http://schemas.xmlsoap.org/wsdl/soap/http |
SOAP 1.1 w/ MTOM | http://schemas.xmlsoap.org/wsdl/soap/http?mtom=true |
SOAP 1.2 | http://www.w3.org/2003/05/soap/bindings/HTTP/ |
SOAP 1.2 w/ MTOM | http://www.w3.org/2003/05/soap/bindings/HTTP/?mtom=true |
XML | http://cxf.apache.org/bindings/xformat |
Appendix D. Using the Maven OSGi Tooling
Abstract
D.1. The Maven Bundle Plug-In
D.2. Setting up a Red Hat JBoss Fuse OSGi project
Overview
Directory structure
src
folder. As in all Maven projects, you place all Java source code in the src/java
folder, and you place any non-Java resources in the src/resources
folder.
beans.xml
file located in the src/resources/META-INF/spring
folder.
Adding a bundle plug-in
Example D.1. Adding an OSGi bundle plug-in to a POM
... <dependencies> <dependency> 1 <groupId>org.apache.felix</groupId> <artifactId>org.osgi.core</artifactId> <version>1.0.0</version> </dependency> ... </dependencies> ... <build> <plugins> <plugin> 2 <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName> 3 <Import-Package>*,org.apache.camel.osgi</Import-Package> 4 <Private-Package>org.apache.servicemix.examples.camel</Private-Package> 5 </instructions> </configuration> </plugin> </plugins> </build> ...
- 1
- Adds the dependency on Apache Felix
- 2
- Adds the bundle plug-in to your project
- 3
- Configures the plug-in to use the project's artifact ID as the bundle's symbolic name
- 4
- Configures the plug-in to include all Java packages imported by the bundled classes; also imports the org.apache.camel.osgi package
- 5
- Configures the plug-in to bundle the listed class, but not to include them in the list of exported packages
Activating a bundle plug-in
packaging
element to bundle
.
Useful Maven archetypes
Spring OSGi archetype
org.springframework.osgi/spring-bundle-osgi-archetype/1.1.2
mvn archetype:create -DarchetypeGroupId=org.springframework.osgi -DarchetypeArtifactId=spring-osgi-bundle-archetype -DarchetypeVersion=1.12 -DgroupId=groupId -DartifactId=artifactId -Dversion=version
Apache CXF code-first archetype
org.apache.servicemix.tooling/servicemix-osgi-cxf-code-first-archetype/2008.01.0.3-fuse
mvn archetype:create -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=spring-osgi-bundle-archetype -DarchetypeVersion=2008.01.0.3-fuse -DgroupId=groupId -DartifactId=artifactId -Dversion=version
Apache CXF wsdl-first archetype
org.apache.servicemix.tooling/servicemix-osgi-cxf-wsdl-first-archetype/2008.01.0.3-fuse
mvn archetype:create -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-osgi-cxf-wsdl-first-archetype -DarchetypeVersion=2008.01.0.3-fuse -DgroupId=groupId -DartifactId=artifactId -Dversion=version
Apache Camel archetype
org.apache.servicemix.tooling/servicemix-osgi-camel-archetype/2008.01.0.3-fuse
mvn archetype:create -DarchetypeGroupId=org.apache.servicemix.tooling -DarchetypeArtifactId=servicemix-osgi-camel-archetype -DarchetypeVersion=2008.01.0.3-fuse -DgroupId=groupId -DartifactId=artifactId -Dversion=version
D.3. Configuring the Bundle Plug-In
Overview
instructions
element.
Configuration properties
Setting a bundle's symbolic name
+ "." +
artifactId, with the following exceptions:
- If groupId has only one section (no dots), the first package name with classes is returned.For example, if the group Id is
commons-logging:commons-logging
, the bundle's symbolic name isorg.apache.commons.logging
. - If artifactId is equal to the last section of groupId, then groupId is used.For example, if the POM specifies the group ID and artifact ID as
org.apache.maven:maven
, the bundle's symbolic name isorg.apache.maven
. - If artifactId starts with the last section of groupId, that portion is removed.For example, if the POM specifies the group ID and artifact ID as
org.apache.maven:maven-core
, the bundle's symbolic name isorg.apache.maven.core
.
Bundle-SymbolicName
child in the plug-in's instructions
element, as shown in Example D.2.
Example D.2. Setting a bundle's symbolic name
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
...
</instructions>
</configuration>
</plugin>
Setting a bundle's name
${project.name}
.
Bundle-Name
child to the plug-in's instructions
element, as shown in Example D.3.
Example D.3. Setting a bundle's name
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-Name>JoeFred</Bundle-Name>
...
</instructions>
</configuration>
</plugin>
Setting a bundle's version
${project.version}
. Any dashes (-
) are replaced with dots (.
) and the number is padded up to four digits. For example, 4.2-SNAPSHOT
becomes 4.2.0.SNAPSHOT
.
Bundle-Version
child to the plug-in's instructions
element, as shown in Example D.4.
Example D.4. Setting a bundle's version
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-Version>1.0.3.1</Bundle-Version>
...
</instructions>
</configuration>
</plugin>
Specifying exported packages
Export-Package
list is populated by all of the packages in your local Java source code (under src/main/java
), except for the deault package, .
, and any packages containing .impl
or .internal
.
Private-Package
element in your plug-in configuration and you do not specify a list of packages to export, the default behavior includes only the packages listed in the Private-Package
element in the bundle. No packages are exported.
Export-Package
child to the plug-in's instructions
element.
Export-Package
element specifies a list of packages that are to be included in the bundle and that are to be exported. The package names can be specified using the *
wildcard symbol. For example, the entry com.fuse.demo.*
includes all packages on the project's classpath that start with com.fuse.demo.
!
. For example, the entry !com.fuse.demo.private
excludes the package com.fuse.demo.private.
!com.fuse.demo.private,com.fuse.demo.*
Specifying private packages
Private-Package
instruction to the bundle plug-in configuration. By default, if you do not specify a Private-Package
instruction, all packages in your local Java source are included in the bundle.
Private-Package
element and the Export-Package
element, the Export-Package
element takes precedence. The package is added to the bundle and exported.
Private-Package
element works similarly to the Export-Package
element in that you specify a list of packages to be included in the bundle. The bundle plug-in uses the list to find all classes on the project's classpath that are to be included in the bundle. These packages are packaged in the bundle, but not exported (unless they are also selected by the Export-Package
instruction).
Example D.5. Including a private package in a bundle
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Private-Package>org.apache.cxf.wsdlFirst.impl</Private-Package>
...
</instructions>
</configuration>
</plugin>
Specifying imported packages
Import-Package
property with a list of all the packages referred to by the contents of the bundle.
Import-Package
child to the plug-in's instructions
element. The syntax for the package list is the same as for the Export-Package
element and the Private-Package
element.
Import-Package
element, the plug-in does not automatically scan the bundle's contents to determine if there are any required imports. To ensure that the contents of the bundle are scanned, you must place an *
as the last entry in the package list.
Example D.6. Specifying the packages imported by a bundle
<plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Import-Package>javax.jws, javax.wsdl, org.apache.cxf.bus, org.apache.cxf.bus.spring, org.apache.cxf.bus.resource, org.apache.cxf.configuration.spring, org.apache.cxf.resource, org.springframework.beans.factory.config, * </Import-Package> ... </instructions> </configuration> </plugin>
More information
Part V. Developing Applications Using JAX-WS
Abstract
Chapter 24. Bottom-Up Service Development
Abstract
24.1. Introduction to JAX-WS Service Development
- Create a Service Endpoint Interface (SEI) that defines the methods you want to expose as a service.NoteYou can work directly from a Java class, but working from an interface is the recommended approach. Interfaces are better suited for sharing with the developers who are responsible for developing the applications consuming your service. The interface is smaller and does not provide any of the service's implementation details.
- Add the required annotations to your code.
- Generate the WSDL contract for your service.NoteIf you intend to use the SEI as the service's contract, it is not necessary to generate a WSDL contract.
- Publish the service as a service provider.
24.2. Creating the SEI
Overview
- Green field development — In this pattern, you are developing a new service without any existing Java code or WSDL. It is best to start by creating the SEI. You can then distribute the SEI to any developers that are responsible for implementing the service providers and consumers that use the SEI.NoteThe recommended way to do green field service development is to start by creating a WSDL contract that defines the service and its interfaces. See Chapter 26, A Starting Point WSDL Contract.
- Service enablement — In this pattern, you typically have an existing set of functionality that is implemented as a Java class, and you want to service enable it. This means that you must do two things:
- Create an SEI that contains only the operations that are going to be exposed as part of the service.
- Modify the existing Java class so that it implements the SEI.
NoteAlthough you can add the JAX-WS annotations to a Java class, it is not recommended.
Writing the interface
wsdl:portType
element. The methods defined by the SEI correspond to wsdl:operation
elements in the wsdl:portType
element.
Example 24.1. Simple SEI
package com.fusesource.demo; public interface quoteReporter { public Quote getQuote(String ticker); }
Implementing the interface
Example 24.2. Simple Implementation Class
package com.fusesource.demo; import java.util.*; public class stockQuoteReporter implements quoteReporter { ... public Quote getQuote(String ticker) { Quote retVal = new Quote(); retVal.setID(ticker); retVal.setVal(Board.check(ticker));[1] Date retDate = new Date(); retVal.setTime(retDate.toString()); return(retVal); } }
24.3. Annotating the Code
24.3.1. Overview of JAX-WS Annotations
- The target namespace for the service.
- The name of the class used to hold the request message
- The name of the class used to hold the response message
- If an operation is a one way operation
- The binding style the service uses
- The name of the class used for any custom exceptions
- The namespaces under which the types used by the service are defined
24.3.2. Required Annotations
Overview
@WebService
annotation on both the SEI and the implementation class.
The @WebService annotation
@WebService
annotation is defined by the javax.jws.WebService
interface and it is placed on an interface or a class that is intended to be used as a service. @WebService
has the properties described in Table 24.1, “@WebService
Properties”
Property | Description |
---|---|
name | Specifies the name of the service interface. This property is mapped to the name attribute of the wsdl:portType element that defines the service's interface in a WSDL contract. The default is to append PortType to the name of the implementation class. [a] |
targetNamespace | Specifies the target namespace where the service is defined. If this property is not specified, the target namespace is derived from the package name. |
serviceName | Specifies the name of the published service. This property is mapped to the name attribute of the wsdl:service element that defines the published service. The default is to use the name of the service's implementation class. [a] |
wsdlLocation | Specifies the URL where the service's WSDL contract is stored. This must be specified using a relative URL. The default is the URL where the service is deployed. |
endpointInterface | Specifies the full name of the SEI that the implementation class implements. This property is only specified when the attribute is used on a service implementation class. |
portName | Specifies the name of the endpoint at which the service is published. This property is mapped to the name attribute of the wsdl:port element that specifies the endpoint details for a published service. The default is the append Port to the name of the service's implementation class.[a] |
[a]
When you generate WSDL from an SEI the interface's name is used in place of the implementation class' name.
|
@WebService
annotation's properties. However, it is recommended that you provide as much information as you can.
Annotating the SEI
@WebService
annotation. Because the SEI is the contract that defines the service, you should specify as much detail as possible about the service in the @WebService
annotation's properties.
@WebService
Annotation” shows the interface defined in Example 24.1, “Simple SEI” with the @WebService
annotation.
Example 24.3. Interface with the @WebService
Annotation
package com.fusesource.demo; import javax.jws.*; @WebService(name="quoteUpdater", 1 targetNamespace="http:\\demos.redhat.com", 2 serviceName="updateQuoteService", 3 wsdlLocation="http:\\demos.redhat.com\quoteExampleService?wsdl", 4 portName="updateQuotePort") 5 public interface quoteReporter { public Quote getQuote(String ticker); }
@WebService
annotation in Example 24.3, “Interface with the @WebService
Annotation” does the following:
- 1
- Specifies that the value of the
name
attribute of thewsdl:portType
element defining the service interface isquoteUpdater
. - 2
- Specifies that the target namespace of the service is http:\\demos.redhat.com.
- 3
- Specifies that the value of the
name
of thewsdl:service
element defining the published service isupdateQuoteService
. - 4
- Specifies that the service will publish its WSDL contract at http:\\demos.redhat.com\quoteExampleService?wsdl.
- 5
- Specifies that the value of the
name
attribute of thewsdl:port
element defining the endpoint exposing the service isupdateQuotePort
.
Annotating the service implementation
@WebService
annotation, you also must annotate the service implementation class with the @WebService
annotation. When adding the annotation to the service implementation class you only need to specify the endpointInterface property. As shown in Example 24.4, “Annotated Service Implementation Class” the property must be set to the full name of the SEI.
Example 24.4. Annotated Service Implementation Class
package org.eric.demo; import javax.jws.*; @WebService(endpointInterface="com.fusesource.demo.quoteReporter") public class stockQuoteReporter implements quoteReporter { public Quote getQuote(String ticker) { ... } }
24.3.3. Optional Annotations
Abstract
@WebService
annotation is sufficient for service enabling a Java interface or a Java class, it does not fully describe how the service will be exposed as a service provider. The JAX-WS programming model uses a number of optional annotations for adding details about your service, such as the binding it uses, to the Java code. You add these annotations to the service's SEI.
24.3.3.1. Defining the Binding Properties with Annotations
Overview
The @SOAPBinding annotation
@SOAPBinding
annotation is defined by the javax.jws.soap.SOAPBinding
interface. It provides details about the SOAP binding used by the service when it is deployed. If the @SOAPBinding
annotation is not specified, a service is published using a wrapped doc/literal SOAP binding.
@SOAPBinding
annotation on the SEI and any of the SEI's methods. When it is used on a method, setting of the method's @SOAPBinding
annotation take precedence.
@SOAPBinding
Properties” shows the properties for the @SOAPBinding
annotation.
Property | Values | Description |
---|---|---|
style | Style.DOCUMENT (default)
Style.RPC
| Specifies the style of the SOAP message. If RPC style is specified, each message part within the SOAP body is a parameter or return value and appears inside a wrapper element within the soap:body element. The message parts within the wrapper element correspond to operation parameters and must appear in the same order as the parameters in the operation. If DOCUMENT style is specified, the contents of the SOAP body must be a valid XML document, but its form is not as tightly constrained. |
use | Use.LITERAL (default)
Use.ENCODED [a]
| Specifies how the data of the SOAP message is streamed. |
parameterStyle [b] | ParameterStyle.BARE
ParameterStyle.WRAPPED (default)
| Specifies how the method parameters, which correspond to message parts in a WSDL contract, are placed into the SOAP message body. If BARE is specified, each parameter is placed into the message body as a child element of the message root. If WRAPPED is specified, all of the input parameters are wrapped into a single element on a request messag |