Users Guide (original) (raw)

1. Overview

1.1. Introduction

This document describes the new features available in this release of the JAX-WS RI. The main focus of this document is to describe the tools used to develop JAX-WS RI 2.3.0-SNAPSHOT web service endpoints and clients. Readers of this document should be familiar with web services XML,XML Schema and WSDL. Familiarity with JAX-RPC 1.1 may also be beneficial but is not necessary.

The documentation/samples discusses how to use JAX-WS in a non-Java EE 5 servlet container using a proprietary deployment descriptor sun-jaxws.xml and servletcom.sun.xml.ws.transport.http.servlet.WSServlet. This means that you can run JAX-WS RI applications in any servlet container that has been enabled with the JAX-WS RI. Applications that use the proprietary DD and servlet will run in a JAX-WS RI enabled Java EE 5 servlet container, but they will be non-portable. If you wish to use JAX-WS in a Java EE container in a Java EE portable manner you need to use the standard Java EE 5 deployment descriptor; please refer to theJava EE 5 or Glassfish documentation/samples. The majority of the documentation included with JAX-WS is valid with Java EE 5 as well.

1.2. Features

1.2.1. JAX-WS 2.3.0 API

JAX-WS 2.3.0 is a Maintainence Release of JAXWS 2.0 API.

JAX-WS 2.3.0 has the following new features from JAX-WS 2.1 specification:

JAX-WS 2.1 has the following new features from JAX-WS 2.0 specification:

JAX-RPC users should note that JAX-WS is a completely different technology than JAX-RPC and thus cannot run JAX-RPC applications on top of JAX-WS. If you have an existing JAX-RPC application it must be converted to work with JAX-WS.

1.2.2. Fully Dynamic Runtime

In JAX-WS, all artifacts generated byannotationProcessing, wsimport andwsgen are portable. JAX-WS uses the annotations within the SEI to aid in marshalling/unmarshalling messages. Because we no longer generated non-portable artifacts, we were able to get rid of tools like JAX-RPC'swsdeploy. The user now can create their own deployable WAR file. To learn more about creating a WAR file and the deployment descriptor, see WAR File Packaging. It should also be noted that JAX-RPC's wscompile tool has been replaced by two new tools: wsimport andwsgen. wsimport is used for importing WSDLs and generating the portable artifacts.wsgen processes a compiled SEI and generates the portable artifacts. Unlike JAX-RPC'swscompile JAX-WS's wsgen does not generate WSDL at tool-time, the WSDL is now generated when the endpoint is deployed. There however is an option onwsgen to generate the WSDL for developement purposes.

1.2.3. MTOM & swaRef

MTOM and swaRef support was added in JAX-WS 2.0 RI FCS release. MTOM and swaref support is required by the JAX-WS 2.0 specification. This means that the MTOM or swaref solution developed with JAX-WS RI will be fully portable with any JAX-WS 2.0 compliant implementation.

MTOM implementation was completely re-written to allow streaming attachment support and just like rest of the JAX-WS RI runtime its written for better performance. This implementation was released as part of JAX-WS 2.0.1 M1 release.

JAX-WS 2.3.0 brings in support for optimized transmission of binary data as specified by MTOM (SOAP Message Transmission Optimization Mechanism)/ XOP (XML Binary Optimized Packaing) and swaRef (SOAP Attachment References specified by WS-I Attachment Profile 1.0).

For details on MTOM and swaRef features refer to MTOM and Swaref.

1.2.4. SOAP 1.2

SOAP 1.2 support is added to JAX-WS 2.3.0. For details refer to SOAP 1.2.

1.2.5. XML/HTTP Binding

Support for XML/HTTP binding is added to JAX-WS 2.0. One can directly send XML over HTTP using Provider andDispatch implementations. This enables support for REST style Web Services in JAX-WS. For details refer to restful sample.

1.2.6. JAXB 2.2

JAX-WS RI 2.3.0-SNAPSHOT uses JAXB 2.2 for data-binding between Java and XML which enables features such as separate compilation, type substitution and other improvements.

1.2.6.1. Type Substitution using@XmlSeeAlso

JAXB 2.1 defines @XmlSeeAlso annotation which can be used to tell JAXB to use the classes mentioned with this annotation. This allows type substitution to takes place. See the samples/type_substitution/src/type_substitution/server/CarDealer.java sample that demonstrates it.

wsimport tool, generates@XmlSeeAlso with all the classes that are not directly referenced by the WSDL operations. To capture all such classes wsimport generates@XmlSeeAlso(ObjectFactory.class) on the generated Service Endpoint Interface.

1.2.6.2. @XmlElement on web service SEI parameters

JAX-WS 2.2 spec allows @XmlElement on web service SEI parameters, which enables better control of XML representation. For this support, JAX-WS relies on JAXB 2.2 API which allows the @XmlElement annotation on parameters.

1.2.7. WS-Addressing

JAX-WS RI 2.3.0-SNAPSHOT supports for W3C Core, SOAP Binding and Addressing 1.0 - Metadata specifications and defines standard API and annotations to enable/disable W3C WS-Addressing on the client and service endpoint. In addition to that, JAX-WS RI also supportsMember Submission version of WS-Addressing. The member submission version is supported in an implementation specific way. For compatility with JAX-WS 2.1 behavior, JAX-WS RI 2.2 also supports wsdls conforming to WSDL Binding specification.

Refer to WS-Addressing for more details. See WS-Addressing samples fromjava-wsaddressing,fromwsdl-wsaddressing-policy andfromwsdl-wsaddressing with the JAX-WS RI 2.3.0-SNAPSHOT for details on the WS-Addressing programming model.

1.2.8. Annotations

JAX-WS 2.3.0 relies heavily on the use of annotations as provided by A Metadata Facility for the Java Programming Language (JSR 175) and and Web Services Metadata for the Java Platform (JSR 181) as well as additional annotations defined by JAX-WS 2.3.0. These annotations are used to customize the mapping from Java to XML schema/WSDL and are used at runtime to alleviate the need for non-portable serializers/deserializers that were generated in JAX-RPC 1.x.(JSR 269) Pluggable Annotation Processing API comes as replacement of apt

The JAX-WS RI utilizes anjavac Pluggable Annotation Processing API functionality that was introduced in Java SE 6. javac allows the SI to process Java source files directly to generate the portable artifacts specified by the JAX-WS 2.0 specification.javac comes as replacement of deprecated apt. More documentation about javac can be found in section Annotation Processing Deprecated apt will be covered in more detail in sectionapt.

For more information on the annotations used by JAX-WS 2.0 please refer to Annotations.

1.2.9. Customizations

JAX-WS RI 2.3.0-SNAPSHOT carries forward customization support introduced in JAX-WS 2.0 RI.

JAX-WS 2.0 specification defines standard XML based customization for a WSDL file to Java mapping and to control certain features. These customizations, or binding declarations, can customize almost all WSDL components that can be mapped to Java, such as the service endpoint interface class, method name, parameter name, exception class, etc. The other important thing you can do with these binding declarations is to control certain features, such as asynchrony, provider, wrapper style, and additional headers. For example, a client application can enable asynchrony for a particular operation in a portType, all operations in a portType, or allportType operations defined in the WSDL file.

These binding declarations can be inlined in a WSDL file or can live outside as an external file. The binding declarations closely align with the JAXB binding declarations. An application importing a WSDL file can inline JAXB bindings inside JAX-WS binding declarations to customize the inlined schema declared in the WSDL file. Schema files that are imported from a WSDL file can be customized using JAXB binding files and can be passed towscompile using the -b option switch.

These are the main customization features:

The following WSDL component's mapped Java names can be modified:

XML Schema Java mapping can be customized using standard JAXB customizations.

For more information on the customizations used by JAX-WS 2.0 please refer to WSDL Customization.

1.2.10. Improved Handler Framework

JAX-WS 2.0 specification defines two types of handlers: logical and protocol handlers. While protocol handlers have access to an entire message such as a SOAP message, logical handlers deal only with the payload of a message and are independent of the protocol being used. Handler chains can now be configured on a per-port, per-protocol, or per-service basis. A new framework of context objects has been added to allow client code to share information easily with handlers.

For more information on the handler framework in JAX-WS RI 2.3.0-SNAPSHOT please refer to Handler.

1.2.11. Provider

Web service endpoints may choose to work at the XML message level by implementing the Provider interface. Here the endpoints access messages or message payloads using this low level, generic API.

For more information on providers in JAX-WS RI 2.3.0-SNAPSHOT please refer to Provider.

1.2.12. Dispatch

The Dispatch API is intended for advanced XML developers who prefer to use XML constructs at thejava.lang.transform.Source orjavax.xml.soap.SOAPMessage level. For added convenience use of the Dispatch API with JAXB data-bound objects is supported. The Dispatch API can be used in both Message andPayload modes.

For more information on the Dispatch please refer to Dispatch.

1.2.13. Asynchronous Client Operations

For more information on asynchronous clients in JAX-WS RI 2.3.0-SNAPSHOT please refer to Asynchronous Client.

1.3. Programming Model

This section of the documentation will focus on the programming model for both developing and publishing a web service endpoint, and writing a web service client. A web service endpoint is the implementation of a web service. A web service client is an application that accesses a web service.

1.3.1. Server

When developing a web service endpoint, a developer may either start from a Java endpoint implementation class or from a WSDL file. A WSDL (Web Services Description Language) document describes the contract between the web service endpoint and the client. A WSDL document may include and/or import XML schema files used to describe the data types used by the web service. When starting from a Java class, the tools generate any portable artifacts as mandated by the spec. When starting from a WSDL file and schemas, the tools generate a service endpoint interface.

There is a trade-off when starting from a Java class or from a WSDL file. If you start from a Java class, you can make sure that the endpoint implementation class has the desirable Java data types, but the developer has less control of the generated XML schema. When starting from a WSDL file and schema, the developer has total control over what XML schema is used, but has less control over what the generated service endpoint and the classes it uses will contain.

1.3.1.1. Starting from Java

The basic process for deploying a web service from a Java class consists of two steps.

  1. Generate portable artifacts.
  2. Create a WAR file to deploy
1.3.1.2. Generate Portable Artifacts

Portable artifacts generated by JAX-WS RI 2.3.0-SNAPSHOT include zero or more JavaBean classes to aide in the marshaling of method invocations and responses, as well as service-specific exceptions.

In document/literal wrapped mode, two JavaBeans are generated for each operation in the web service. One bean is for invoking the other for the response. In all modes (rpc/literal and both document/literal modes), one JavaBean is generated for each service-specific exception.

When starting from Java the developer must provide the JAX-WS tools with a valid endpoint implementation class. This implementation class is the class that implements the desired web service. JAX-WS has a number of restrictions on endpoint implementation classes. A valid endpoint implementation class must meet the following requirements:

Here is an example of a a simple endpoint implementation class `samples/fromjava/src/fromjava/server/AddNumbersImpl.java` from the fromjava sample:

package fromjava.server;

import javax.jws.WebService;

@WebService public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be " +
                "added!", "Numbers: " + number1 + ", " + number2);
    }
    return number1 + number2;
}

}

If you are familiar with JAX-RPC 1.1, you will notice that this implementation class does not implement a service endpoint interface. In JAX-WS RI 2.3.0-SNAPSHOT a service endpoint interface is no longer required.

When starting from a Java endpoint implementation class, it is recommended that the portable artifacts be generated from source using annotationProcessing. This because the JAX-WS tools will then have full access to the source code and will be able to utilize parameter names that are otherwise not available through the Java reflection APIs. If the source for the endpoint implementation class is not available, the portable artifacts can be generated usingwscompile. Here is a sampleannotationProcessing Ant task from the samples:

<classpath refid="jax-ws.classpath"/>

More information about the annotationProcessing Ant task can be found annotationProcessing Ant Task. If this task is run on the fromjava sample, the output would include:

AddNumbers.class AddNumbers.java AddNumbersExceptionBean.class AddNumbersExceptionBean.java AddNumbersResponse.class AddNumbersResponse.java

The AddNumbersImplService.wsdl file describes the web service. Theschema1.xsd file is imported by theAddNumbersImplService.wsdl and contains the datatypes used by the web service. TheAddNumbers.class/AddNumbers.java files contain the a bean used by a JAXB to marshall/unmarshall the addNumbers request. TheAddNumbersExceptionBean.class/AddNumbersExceptionBean.java file is a bean used by JAXB to marshall the contents of theAddNumbersException class. TheAddNumbersResponse.class/AddNumbersResponse.java files represent the response bean used by JAXB to marshall/unmarshall the addNumbers response.

1.3.1.3. Create a WAR file to deploy

Creating a WAR file is nothing more than packaging the service endpoint interface (if there is one), service endpoint implementation, Java classes used by the endpoint implementation and a deployment descriptor in WAR format. For the fromjava sample the AddNumbersImpl andAddNumbersException classes in thefromjava.server package, and the deployment descriptor are bundled together to make a raw WAR file. To learn more about creating a WAR file and the deployment descriptor, see WAR File Packaging. The deployment descriptor used infromjava sample is given below and can be found samples/fromjava/etc/sun-jaxws.xml:

The attributes of the<endpoint> element are described below:

The structure of the raw WAR file is shown below:

META-INF/MANIFEST.MF WEB-INF/sun-jaxws.xml WEB-INF/web.xml WEB-INF/classes/fromjava/server/AddNumbersException.class WEB-INF/classes/fromjava/server/AddNumbersImpl.class WEB-INF/classes/fromjava/server/jaxws/AddNumbers.class WEB-INF/classes/fromjava/server/jaxws/AddNumbersExceptionBean.class WEB-INF/classes/fromjava/server/jaxws/AddNumbersResponse.class

The WAR file created can now be published on a JAX-WS RI enabled servlet container such as the Sun Java System Application Server Platform Edition 8.2

1.3.1.4. Starting from a WSDL File

The basic process for deploying a web service when starting from a WSDL document consists of the following four steps:

  1. Generate a service endpoint interface.
  2. Implement the service endpoint interface.
  3. Create a WAR file to deploy.
1.3.1.5. Generate a Service Endpoint Interface

This step involves compiling or importing the WSDL file to generate a service endpoint interface and value classes mapped from imported XML schemas.

Below is a sample wsimport Ant target:

<binding dir="${basedir}/etc"
        includes="${server.binding}"/>

Its commandline equivalent is:

wsimport.sh etc/AddNumbers.wsdl -b custom-server.xml

Lets look at the excerpt of samples/fromwsdl/etc/AddNumbers.wsdl from the sample fromwsdl:

The generated service endpoint interface looks as follows:

package fromwsdl.server;

@javax.jws.WebService( name = "AddNumbersPortType", serviceName = "AddNumbersService", targetNamespace = "http://duke.example.org") @javax.jws.soap.SOAPBinding( style = javax.jws.soap.SOAPBinding.Style.DOCUMENT, use = javax.jws.soap.SOAPBinding.Use.LITERAL, parameterStyle = javax.jws.soap.SOAPBinding.ParameterStyle.WRAPPED) public interface AddNumbersPortType extends java.rmi.Remote { @javax.jws.WebMethod(operationName = "addNumbers") @javax.jws.WebResult(name = "return") public int addNumbers(@javax.jws.WebParam(name = "arg0") int arg0, @javax.jws.WebParam(name = "arg1") int arg1) throws fromwsdl.server.AddNumbersFault_Exception, java.rmi.RemoteException; }

The generated service endpoint interface has annotations that can be used by the future versions of JAX-WS 2.0 to do dynamic binding and serialization/deserialization at runtime. Alternatively this service endpoint interface can be used to generate a WSDL and schema file. Please note that round-tripping is not guaranteed in this case. So the generated WSDL file and schema may not be the same as the one the service endpoint interface was generated from.

1.3.1.6. Implement the Service Endpoint Interface

The next thing to do will be to provide the implementation of the service endpoint interface generated in the previous step. When you implement the service endpoint interface it is necessary to provide a@WebService annotation on the implementation class with a endpointInteface element specifying the qualified name of the endpoint interface class. Let's look at the implementation class samples/fromwsdl/src/fromwsdl/server/AddNumbersImpl.java from the sample applicationfromwsdl:

package fromwsdl.server;

@WebService(endpointInterface = "fromwsdl.server.AddNumbersPortType") public class AddNumbersImpl implements AddNumbersPortType {

public int addNumbers(int number1, int number2) throws 
        AddNumbersFault_Exception {
    ...
}

}

1.3.1.7. Create a WAR

This step is similar to the one described above in Create a WAR file to deploy .

Here the service endpoint interface implementation class from previous step, together with a deployment descriptor file sun-jaxws.xml, and web.xml should be bundled together with the service endpoint interface, value classes generated in the first step mentioned in Generate a Service Endpoint Interface.

Let's look at samples/fromwsdl/etc/sun-jaxws.xml from the sample applicationfromwsdl:

It defines the deployment-related configuration information for the fromwsdl endpoint. You will notice that this deployment descriptor contains additional attributes than the deployment descriptor described in Create a WAR file to deploy. The interface attribute references the service endpoint interface generated in step 1. The wsdl attribute also points at the WSDL that was imported by wsimport. The service attribute references which service in the WSDL this endpoint is from and the port is the name of the port in that service for this endpoint.

To learn more about creating a WAR file and the deployment descriptor, see WAR File Packaging.

The WAR file created can now be published on a JAX-WS RI enabled servlet container such as the Sun Java System Application Server Platform Edition 8.2

1.3.1.8. J2SE Endpoints

Endpoints can be created and published programmatically using javax.xml.ws.Endpoint API in J2SE. To learn more about these endpoints, see Endpoint API.

1.3.2. Client

A client application can access a remote web service endpoint in one of two ways: port and dispatch.

1.3.2.1. Dynamic Proxy

In this approach client side invokes Web services via a dynamic proxy. The proxies for the Web Service are created from the generated Service and service endpoint interfaces. Once the proxies are created. the client application can invoke methods on those proxies just like a standard implementation of those interfaces. The sections below describe this process more detail.

1.3.2.2. Generate Client Artifacts

The wsimport tool is used to generate the service endpoint interface and the service interface classes. Below is the sample wsimport Ant target:

The command line equivalent of this Ant target is:

wsimport.sh -classpath client_classpath -d dest_dir -s src_dir
-b custom-client.xml http://localhost:8080/jax-ws-fromwsdl/addnumbers?WSDL

For more details see the wsimport documentation.

Here is the excerpt from samples/fromwsdl/src/fromwsdl/client/AddNumbersClient.java in the fromjava sample application:

AddNumbersPortType port = new AddNumbersService().getAddNumbersPort();

int result = port.addNumbers(10, 20);

1.3.2.3. Dispatch

The Dispatch API is intended for advanced XML developers who prefer using XML constructs at thejava.lang.transform.Source orjavax.xml.soap.SOAPMessage level. For added convenience use of Dispatch with JAXB data binding object is supported. With theXML/HTTP binding ajavax.activation.DataSource can also be used. The Dispatch APIs can be used in bothMessage and Payload modes. The Dispatch API client with anXML/HTTP binding can be used with REST Web Services. Please see the restful sample program for more information.

For more information on Dispatch in JAX-WS RI 2.3.0-SNAPSHOT please refer to Dispatch.

2. Provider

Web Service endpoints may choose to work at the XML message level by implementing the Provider interface. This is achieved by implementing either Provider<Source> orProvider<SOAPMessage> orProvider<DataSource>. The endpoint accesses the message or message payload using this low-level, generic API. All the Provider endpoints must have @WebServiceProvider annotation. The @ServiceMode annotation is used to convey whether the endpoint wants to access the message (Service.Mode.MESSAGE) or payload (Service.Mode.PAYLOAD). If there is no@ServiceMode annotation on the endpoint, payload is the default value. The endpoint communicates with handlers usingWebServiceContext resource like any other normal endpoint. Provider endpoints can start from java or WSDL. When the provider endpoints start from a WSDL file,<provider> WSDL customization can be used to mark a port as a provider.

2.1. Provider<Source> andPAYLOAD

An endpoint can access only the payload of a request usingService.Mode.PAYLOAD in the@ServiceMode annotation. This is the default behaviour, if the annotation is missing.

For example:

@WebServiceProvider public class ProviderImpl implements Provider { public Source invoke(Source source) { response = ...; return response; } }

2.2. Provider<SOAPMessage> andMESSAGE

An endpoint can access an entire SOAP request as aSOAPMessage.Service.Mode.MESSAGE in the@ServiceMode annotation is used to convey the intent.

For example:

@WebServiceProvider @ServiceMode(value = Service.Mode.MESSAGE) public class ProviderImpl implements Provider { public SOAPMessage invoke(SOAPMessage msg) { SOAPMessage response =...; return response; } }

2.3. Provider<Source> andMESSAGE

An endpoint can access a request as a Source. If the request is a SOAPMessage, only theSOAPPart (no attachments) of the message is passed as Source to the invoke method. If the returned response is null, it is considered a one way MEP.

For example:

@ServiceMode(value = Service.Mode.MESSAGE) public class ProviderImpl implements Provider { public Source invoke(Source source) { using source } }

2.4. WSDL Customization

If the provider endpoint starts with a WSDL file, a port can be customized to a provider endpoint using the<provider> customization.wsimport won't generate any artifacts for that port.

For example:

<bindings ... wsdlLocaption="AddNumbers.wsdl"xmlns="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/jaxws"> true

2.5. The sun-jaxws.xml file

The attributes of provider endpoint in sun-jaxws.xml: name, implementation, wsdl, service, port override the attributes provided through @WebServiceProvider annotation. For SOAP1.2 binding, one needs to specify binding attribute.

For example:

If the wsdl, service, port are not specified in sun-jaxws.xml, then should be declared in the @WebServiceProvider annotation in implementation class.

2.6. Provider and Binding

Provider endpoint can be configured for different bindings using binding ids. These binding ids are defined in JAX-WS API and endpoint can be configured by specifying @BindingType annotation or using binding attribute in sun-jaxws.xml. sun-jaxws.xml overwrites binding defined by @BindingType annotation. If the binding is not specified using@BindingType or insun-jaxws.xml, the default binding is SOAP1.1/HTTP.

For example: To specify XML/HTTP binding using @BindingType annotation

@ServiceMode(value = Service.Mode.MESSAGE) @BindingType(value = HTTPBinding.HTTP_BINDING) public class ProviderImpl implements Provider { public Source invoke(Source source) {

}

}

For example: To specify XML/HTTP binding insun-jaxws.xml

<endpoint ... binding="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2004/08/wsdl/http"/>

2.7. RESTful Provider endpoints

RESTful Web Services can be built usingXML/HTTP binding based Provider endpoints. In this case, even HTTP GET requests are passed to the endpoint. Endpoint can get necessary HTTP request query string and path information using standardMessageContext.QUERY_STRING andMessageContext.PATH_INFO. For more details on endpoint implementation, see the samples/restful/src/restful/server/AddNumbersImpl.java sample. If the endpoint expects GET requests to contain extra path after the endpoint address, then url-pattern should have "/*" at the end in bothsun-jaxws.xml andweb.xml.

For example: sun-jaxws.xml

<endpoint ... binding="http://www.w3.org/2004/08/wsdl/http" url-pattern="/addnumbers/*"/>

For example: web.xml

...

<servlet-mapping>
    <servlet-name>provider</servlet-name>
    <url-pattern>/addnumbers/*</url-pattern>
</servlet-mapping>

...

2.8. Provider and Handlers

Handlers can be configured with Provider endpoints insun-jaxws.xml descriptor or by putting@HandlerChain on the Provider implementation.

For example:

javaee:handler-chain javaee:handler-chain-namemy handler javaee:handler javaee:handler-nameMyHandler javaee:handler-classprovider.server.MyHandler

3. AsyncProvider

Web Service endpoints may choose to work at the XML message level by implementing the Provider interface. The related information about Provider endpoints is documented inProvider page. However Provider endpoints are synchronous i.e. they receive XML requests and they return XML responses synchronously ininvoke() method. If the endpoint wants to spawn a thread to process the request, it would block the jax-ws runtime thread and has to manage all the low details synchronizing the threads when the response is available. Also blocking a thread doesn't really scale well especially when the underlying transport is capable of handling asynchronous request and responses. RI provides an implemention specific solution to this problem by introducing AsyncProvider. This is similar to Provider endpoints but the difference is that the endpoint implementations have to implementAsyncProvider interface.

3.1. AsyncProvider Example

The following example shows an AsyncProvider example that accesses the payload of the request.

@WebServiceProvider public class AsyncProviderImpl implements AsyncProvider {

public void invoke(Source source, AsyncProviderCallback cbak, 
                   WebServiceContext ctxt) {
    
    
}

}

3.2. AsyncProvider sample

See a samples/asyncprovider/Readme.txt that illustrates AsyncProvider endpoints.

3.3. AsyncService sample

See another samples/asyncservice/Readme.txt" sample that illustrates AsyncProvider endpoint that uses asynchronous servlet as the transport to bring true asynchronity on the server-side.

4. Dispatch

Web service client applications may choose to work at the XML message level by using the Dispatch<T> APIs. Thejavax.xml.ws.Dispatch<T> interface provides support for the dynamic invocation of service endpoint operations.

Four Message Exchange Protocols(MEP) are supported: request-response, one way, asynchronous polling, and callback. Each of these invocation MEPs are required with JAXB data boundjava.lang.Object,javax.xml.transform.Source,javax.xml.soap.SOAPMessage andjavax.activation.DataSource object requests.

The javax.xml.ws.Service acts as a factory for the creation of Dispatch<T> instances. In addition, a Dispatch<T> instance is created in either Service.Mode.PAYLOAD orService.Mode.MESSAGE modes. Ajavax.xml.soap.SOAPMessage request can only be used with a Dispatch<T> instance ofService.Mode.MESSAGE and using the SOAP Binding. Ajavax.activation.DataSource request can only be used with a Dispatch<T> instance ofService.Mode.MESSAGE and using the XML/HTTP Binding.

Note that the Dispatch<T> instance simply acts as a conduit for the request. No validation of the message is required to be performed by the implementation, though some may catch errors during request processing. It is up to the client program to supply well-formed XML requests.

4.1. Programming Model

4.1.1. Create a dynamic Service.

The javax.xml.ws.Service acts as a factory for the creation of a dynamic Service. When created for use with Dispatch<T> APIs the Service created can be either aService that has knowledge of the binding information of a known Service or no knowledge of any specific Service.

That is, when the Service is created with a WSDL file the port(s) binding ID, QName, and endpoint address are known to the Service.

The methods to create a dynamic Service are shown here:

Service service = Service.create(QName serviceQName); Service service = Service.create(URL wsdlLocation, QName serviceQName);

A Dispatch<T> instance must be bound to a specific port and endpoint before use. The service has an addPort(QName portName, URI bindingID, String endpointAddress) method that the client program can invoke for Dispatch<T> objects. Ports created using this method can only be used withDispatch<T> instances.

If the Service has been created with WSDL binding information the the port need not be added as theDispatch<T> instance will be created specific for the binding information provided in the supplied WSDL file.

Developers who have used web service applications in the past are familiar with the port QName and endpoint address parameters of this method. JAX-WS RI 2.3.0-SNAPSHOT supports three Binding URI's, that of the SOAP 1.1, the SOAP 1.2 and XML/HTTP Binding. For more information on SOAP 1.2 support please refer to the SOAP 1.2 documents. For the XML/HTTP binding please see chapter 11 of the JAX-WS 2.0 PFD Specification.

The addition of the SOAP 1.1 port using theService API is shown here:

service.addPort(QName portName, String SOAPBinding.SOAP11HTTP_BINDING, String endpointAddress);

SOAP 1.2 support has been implemented forDispatch. This requires only one change in the programming model. The addition of the SOAP 1.2 port using theService API is shown here:

service.addPort(QName portName, String SOAPBinding.SOAP12HTTP_BINDING, String endpointAddress);

XML/HTTP binding support has been implemented forDispatch. The creation of the XML/HTTP port using the Service API is shown here:

service.addPort(QName portName, String HTTPBinding.HTTP_BINDING, String endpointAddress);

4.1.2. Create a Dispatch<T> instance.

The Dispatch<T> object can be created using either of these two Service methods:

Dispatch dispatch = service.createDispatch(QName portName, Class clazz, Service.Mode mode); Dispatch dispatch = service.createDispatch(QName portName, JAXBContext jaxbcontext, Service.Mode mode);

For a javax.xml.transform.Source and JAXB data binding java.lang.Object Dispatch<T> can be created in bothService.Mode.PAYLOAD andService.Mode.MESSAGE modes. Ajavax.xml.soap.SOAPMessage can only be created in Service.Mode.MESSAGE mode. The first form of the createDispatch method is used to create ajavax.xml.transform.Source orjavax.xml.soap.SOAPMessage specific to theDispatch<T> instance.

A JAXB object-specific instance can only be created using the second method listed above.

It is important to note that once theDispatch<T> instance is created it is static. That is, its Service.Mode or request type can not be changed. The instance can be reused given the caveat that if it is a JAXB-specificDispatch<T> it must be reused with objects known to the same JAXBContext.

4.1.3. Set the context Map<String, Object> for the request.

The Dispatch<T> interface extends the javax.xml.ws.BindingProvider interface. TheBindingProvider interface defines accessor methods for the request and response context maps. StandardBindingProvider properties are defined by the JAX-WS 2.0 specification and the client program may set and get these properties. The application may also define application-specific properties, but the specification discourages this for portability reasons.

4.1.4. Prepare the message request.

This is the client developer's responsibility. For examples of how to prepare specific request types refer to theDispatch<T> sample applications.

4.1.5. Invoke the web service request.

Four types of invocation MEPs are supported using the methods below. In methods that produce a response, the type ofObject returned will be of the same type as the request. For example, a SOAPMessage request will return a SOAPMessage response.

Object response = dispatch.invoke(T); dispatch.invokeOneway(T); Response response = dispatch.invokeAsync(T); Future<?> response = dispatch.invokeAsync(T, AsyncHandler);

4.2. Dispatch and Asynchronous Invocations

Asynchronous invocations require special consideration. The first form of the invokeAsync method is a polling method. The response, Response<T>,returns to the user immediately and may be polled for completion. In the meantime, the client program can do other work.

The javax.xml.ws.Response<T> implements the java.util.concurrent.Future<T> interface that is included in J2SE 5.0. The Response<T> object returns the actual response via its get method, which blocks if the response is not ready to be returned.

The Future<T> interface also has acancel method that will attempt to cancel the request invocation if the request is being invoked.

Faults returned from the service or exceptions thrown during the invocation are returned when the Response<T> get method is called. Because the execution doesn't occur in the main thread, the exception or fault returned is wrapped in an java.util.concurrent.ExecutionException. To obtain the actual cause use the getCause method ofExecutionException.

For more information on thejava.util.concurrent.Future<?> interface see the J2SE 5.0 documentation.

public interface Response extends java.util.concurrent.Future {

Map<String, Object> getContext();

}

The second form of the invokeAsync method has a second parameter of typejavax.xml.ws.AsyncHandler. The purpose of theAsyncHandler is to get and handle the the response or any fault thrown in an application-specific way. TheAsyncHandler has a methodhandleResponse(Response<T>) that takes ajavax.xml.ws.Response<T> parameter. This method gets the response or any faults and processes them according to behavior defined in the application. Note that it is the responsibility of the client program to implement the asynchronous handler.

class ResponseHandler implements javax.xml.ws.AsyncHandler {

public handleResponse(Response<T>);

}

This form of the asynchronous invocation method returns aFuture<?> object with wildcard type. As in the asynchronous poll invocation, theFuture<T> object can be polled to see if the response is ready. However, calling the get method will not return the response of the invocation, but an object of indeterminate type.

Examples of synchronous and asynchronous invocations are shown in the Dispatch<T> samples. For convenience an example of Response<T> usage is display here:

Response response = dispatch.invokeAsync(Source); while (!response.isDone()) {

}

try {

Source result = (javax.xml.transform.Source) response.get();

} catch (ExecutionException ex) {

Throwable cause = ex.getCause();

} catch (InterupptedException ie) {

System.out.println("Operation invocation interrupted");

}

5. Asynchronous Client

This document describes how a client application can invoke a remote web service asynchronously. It can do so either by generating a static stub or using the Dispatch API.

5.1. Asynchronous Invocation Using Static Stub

Client application should applyjaxws:enableAsyncMapping binding declaration to the WSDL file to generate asynchronous method in the service endpoint interface. Please refer to Asynchrony for details on how this can be applied to the WSDL file.

Lets look at the following WSDL excerpt:

...

<portType name="AddNumbersImpl">
    <operation name="addNumbers">
        <input message="tns:addNumbers"/>
        <output message="tns:addNumbersResponse"/>
    </operation>
</portType>
<binding name="AddNumbersImplBinding" type="tns:AddNumbersImpl">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
            style="document"/>
    <operation name="addNumbers">
        <soap:operation soapAction=""/>
        <input>
            <soap:body use="literal"/>
        </input>
        <output>
            <soap:body use="literal"/>
        </output>
    </operation>
</binding>

...

In order to generate a service endpoint interface with asynchronous methods the following binding declaration file will be passed to wsimport:

true

It produces the following service endpoint interface (annotations are removed from the synchronous method for better readability):

//synchronous method public int addNumbers(int number1, int number2) throws java.rmi.RemoteException;

//async polling Method public Response addNumbers(int number1, int number2);

//async callback Method public Future<?> addNumbers(int number1, int number2, AsyncHandler);

5.1.1. Async Polling

//async polling Method public Response addNumbers(int number1, int number2);

Typically a client application will invoke the async polling operation on the stub and check for a response on the returnedResponse object. The response is available whenResponse.isDone returns true.

javax.xml.ws.Response resp = port .addNumbersAsync(10, 20); while (!resp.isDone()) {

} System.out.println("The sum is: " + resp.get().getReturn());

...

5.1.2. Async Callback

//async callback Method public Future<?> addNumbers(int number1, int number2, AsyncHandler);

Here the client application provides anAsyncHandler by implementing thejavax.xml.ws.AsyncHandler<T> interface.

class AddNumbersCallbackHandler implements AsyncHandler { private AddNumbersResponse output;

public void handleResponse(Response<AddNumbersResponse> response) {
    try {
        output = response.get();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

AddNumbersResponse getResponse() {
    return output;
}

}

The async handler is then passed as the last parameter of the async callback method:

AddNumbersCallbackHandler callbackHandler = new AddNumbersCallbackHandler();

Future<?> resp = port.addNumbersAsync(number1, number2, callbackHandler); while (!resp.isDone()) {

} System.out.println("The sum is: " + callbackHandler.getResponse().getReturn());

5.2. Asynchronous Invocation Using Dispatch

For information on the Dispatch API and asynchronous invocations see Dispatch

6. Handler

6.1. Handler Types

JAX-WS 2.0 defines a Handler interface, with subinterfaces LogicalHandler andSOAPHandler. The Handler interface contains handleMessage(C context) andhandleFault(C context) methods, whereC extends MessageContext. A property in the MessageContext object is used to determine if the message is inbound or outbound.SOAPHandler objects have access to the full soap message including headers. Logical handlers are independent of protocol and have access to the payload of the message.

The new handler types can now be written without casting the message context object that is passed to them. For instance:

public class MyLogicalHandler implements LogicalHandler {

public boolean handleMessage(LogicalMessageContext messageContext) {
    LogicalMessage msg = messageContext.getMessage();
    return true;
}

}

public class MySOAPHandler implements SOAPHandler {

public boolean handleMessage(SOAPMessageContext messageContext) {
    SOAPMessage msg = messageContext.getMessage();
    return true;
}

}

A close(C context) method has been added that is called on the handlers at the conclusion of a message exchange pattern. This allows handlers to clean up any resources that were used for the processing of a request-only or request/response exchange.

The init() and destroy() methods of the handler lifecycle no longer exist. Instead, a method may be annotated with the @PostConstruct annotation to be called after the handler is created or the@PreDestroy annotation to be called before the handler is destroyed. Note that the annotated methods must returnvoid and take no arguments:

import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;

public class MyLogicalHandler implements LogicalHandler {

@PostConstruct
public void methodA() {
}

@PreDestroy
public void methodB() {
}

}

6.2. MessageContext

In the examples above, the LogicalMessage object allows a handler to get and set the message payload either as a JAXB object or as a javax.xml.transform.Source. TheSOAPMessage object allows access to headers and the SOAP body of the message.

Both context objects extend MessageContext, which holds properties that the handlers can use to communicate with each other. A standard propertyMessageContext.MESSAGE_OUTBOUND_PROPERTY holds aBoolean that is used to determine the direction of a message. For example, during a request, the property would beBoolean.TRUE when seen by a client handler andBoolean.FALSE when seen by a server handler.

The message context object can also hold properties set by the client or provider. For instance, port proxy and dispatch objects both extend BindingProvider. A message context object can be obtained from both to represent the request or response context. Properties set in the request context can be read by the handlers, and the handlers may set properties on the message context objects passed to them. If these properties are set with the scopeMessageContext.Scope.APPLICATION then they will be available in the response context to the client. On the server end, a context object is passed into the invoke method of a Provider.

6.3. Handler Chain Configuration

6.3.1. Handler Files

Starting from a WSDL file, handler chain configuration is through WSDL customizations as defined by JSR 109. A<handler-chains> element is added to the customization file. The following is a simple handler chain with one handler (customization may be on server or client side):

<-- excerpt from customization file --> fromwsdl.handler_simple.common.TestHandler

Multiple handler-chain elements may exist within the handler-chains element. These may optionally use a service name, port name, or protocol pattern in their description to apply some chains to certain ports and protocols and not to others. For instance (note the wildcard character used in the service name):

<-- excerpt --> ns1:My*Service ...

<handler-chain>
    <port-name-pattern xmlns:ns1="urn:namespace">ns1:HelloPort
    </port-name-pattern>
    <handler>...</handler>
</handler-chain>

<handler-chain>
    <protocol-bindings>##SOAP11_HTTP</protocol-bindings>
    <handler>...</handler>
</handler-chain>

Handlers will appear in the final handler chain in the order that they are included in the customization file. However, logical handlers will be sorted out and called before protocol handlers during execution.

Starting from a Java class, annotations are used to describe the handler chain as defined by JSR 181. The following example uses the @HandlerChain annotation to refer to a file describing the chain.

import javax.jws.HandlerChain; import javax.jws.WebService;

@WebService @HandlerChain(file = "handlers.xml") public class MyServiceImpl {

}

An example handlers.xml file is shown below. The schema is the same that is used for the customization.

<jws:handler-chains xmlns:jws="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/javaee"> jws:handler-chain jws:handler jws:handler-classfromjava.handler_simple.common.TestHandler

When packaging the service, thehandlers.xml file must be in the classpath within the WAR file, either directly underWEB-INF/classes or further down in the same package as the service class file.

On the server side, the handlers may be configured in thesun-jaxws.xmldeployment descriptor as well. A handler chain specified here will override handlers in WSDL customizations or annotated classes. The schema for the handler section is the same as in the previous examples:

<endpoints ...> <endpoint...> ...

6.3.2. Programmatic Case

Handler chains may be configured on the client side at runtime by setting a chain directly on aBindingProvider (e.g., aDispatch object or a port proxy) or by using aHandlerResolver. This example shows how to add a handler chain to a port proxy:

HelloPortType myProxy =

Binding binding = ((BindingProvider) myProxy).getBinding();

List handlerList = binding.getHandlerChain();

handlerList.add(new MyHandler()); binding.setHandlerChain(handlerList);

To configure the handlers that are added to newly createdBinding objects, add a handler resolver to the service with setHandlerResolver(). The new resolver will be used whenever aBindingProvider is created from the service. An example resolver is as follows:

public class MyResolver implements HandlerResolver {

public List<Handler> getHandlerChain(PortInfo info) {
    List<Handler> handlers = new ArrayList<Handler>();
    
    return handlers;
}

}

A resolver that modifies the initially configured handler chains could be written by callingservice.getHandlerResolver() and passing the original resolver to a new one:

public List getHandlerChain(PortInfo info) { List handlers = originalResolver.getHandlerChain(info);

return handlers;

}

6.4. Handler Samples

The fromjavahandler andfromwsdlhandler samples set aSOAPHandler on the client and server. This handler simply outputs the contents of the SOAP message and can be used to see the requests and responses being passed back and forth. See the sample documentation for information on running the samples.

7. MTOM and Swaref

7.1. MTOM and XOP

MTOM (Message Transmission and Optimization Mechanism) together with XOP (XML Binary Optimized Packaging) defines how an XML binary data such asxs:base64Binary or xs:hexBinary can be optimally transmitted over the wire. XML type, such asxs:base64Binary is sent in lined inside the SOAP envelope. This gets quite in-efficient when the data size is more, for example a SOAP endpoint that exchanges images/songs etc. MTOM specifies how XOP packaging can be used to send the binary data optimally.

7.2. MTOM in JAX-WS 2.0

MTOM feature is disabled in JAX-WS by default. It can be enabled on the client and server. Once enabled all the XML binary data, XML elements of type xs:base64Binary andxs:hexBinary is optimally transmitted. Currently MTOM works only with proxy port.

Note: MTOM optimization is applied right at the time when JAX-WS writes the message on to the wire. This is done to avoid any bufferring. Having a handler means that JAX-WS transforms the Message in to DOM or SOAPMessage. It results in inlined base64 encoded data and it remains so when the data is written over the wire as attachment. This is done in order to avoid unnecessary conversion to and from when handlers are being used. In short: when handlers are used, MTOM optimization does not happen.

7.2.1. xmime:expectedContentType to Java type mapping

An schema element of type xs:bas64Binary or xs:hexBinary can be annotated by using attribute reference using xmime:expectedContentType JAXB 2.0 specification definesxmime:expectedContentType to Java type mapping in Table 2, “xmime:expectedContentType to Java type mapping”. Here is this table:

Table 2. xmime:expectedContentType to Java type mapping

MIME Type Java Type
image/gif java.awt.Image
image/jpeg java.awt.Image
text/plain java.lang.String
text/xml orapplication/xml javax.xml.transform.Source
*/* javax.activation.DataHandler

is mapped to byte[]

<element name="image" type="base64Binary" **xmime:expectedContentTypes="image/jpeg"** xmlns:xmime="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2005/05/xmlmime"/>

is mapped to java.awt.Image

7.2.2. xmime:contentType schema annotation

xmime:contentType schema annotation indicates the content-type of an XML element content whose type is xs:base64Binary orxs:hexBinary. The value of the attribute is a valid content-type string (e.g., "text/xml; charset=utf-16"). This attribute specifies the content-type of the element content on which it occurs. This annotation can be primarily used to indicate the Content-Type of binary data.

For example the schema type

Here xmime:base64Binary is defined byDescribing Media Content of Binary Data in XML.

Gets mapped to PicutreType bean bywsimport:

PictureType req = new PictureType(); req.setValue(name.getBytes()); req.setContentType("application/xml");

On the wire this is how it looks:

<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv=" http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd=" http://www.w3.org/2001/XMLSchema" xmlns:ns1=" http://example.org/mtom/data" xmlns:ns2="http://www.w3.org/2005/05/xmlmime"> <soapenv:Body> <ns1:TestMtomXmimeContentTypeResponse ns2:contentType="application/xml"> <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="c id:193ed174-d313-4325-8eed-16cc25595e4e@example.org"/> </ns1:TestMtomXmimeContentTypeResponse> </soapenv:Body> </soapenv:Envelope>

7.2.3. How to enable MTOM in JAX-WS 2.0

Enabling MTOM on Server:

}

Enabling MTOM on Client:

7.2.4. Attach vs In-line

As defined by JAXB 2.0 specificationxs:base64Binary andxs:hexBinary mapping to java isbyte[]. JAX-WS implementation has set a threshold of 1KB of byte[] size. This threshold can be modified using implementation specific propertycom.sun.xml.ws.developer.JAXWSProperties.MTOM_THRESHOLD_VALUE in the RequestContext on the client side and in the MessageContext on the server side. If thebyte[] that is being sent is less than this threshold (default is 1KB) then the binary data is base64 encoded by JAXB and in lined inside the SOAP Body otherwise the binary data is sent as attachment mime part in Multipart/Related package and XML infoset for the binary data is XOP encoded by JAXB

<xop:Include href=...>

is used to reference the attachment. The XOP encoding and packaging is done as per described by the XOP packaging rules. The href is the theContent-ID of the attachment and is encoded as per CID URI scheme defined in RFC 2111. xmime:contentType attribute may appear on the element that includes binary data to indicate preferred media type as annotated on the corresponding schema.

7.2.4.1. How to specify MTOM data Threshold

Default threshold value for MTOM feature is 0 bytes. You can set a threshold value for MTOM by using@MTOM annotation on server-side or using MTOMFeature on client-side. Let's say you set MTOM threshold as 3000, this serves as hint to JAX-WS when to send binary dat as attachments. In this case, JAX-WS will send any byte array in the message thats equal to or larger than 3KB as attachment and the corresponding XML infoset will be XOP encoded (will contain reference to this attachment)

7.2.5. MTOM Samples

Example 1. MTOM Sample - mtom

This is SOAP 1.1 MTOM SampleThis is how the JAX-WS generated XOP packaged SOAP message looks on the wire:

Content-Type: Multipart/Related; start-info="text/xml"; type="application/xop+xml"; boundary="----=_Part_0_1744155.1118953559416" Content-Length: 3453 SOAPAction: ""

------=_Part_1_4558657.1118953559446

Content-Type: application/xop+xml; type="text/xml"; charset=utf-8

<soapenv:Envelope xmlns:soapenv="" title="undefined" rel="noopener noreferrer">http://schemas.xmlsoap.org/soap/envelope/"> soapenv:Body RHVrZQ== <xop:Include** **xmlns:xop="http://www.w3.org/2004/08/xop/include"** **href="cid:5aeaa450-17f0-4484-b845-a8480c363444@example.org"/>

------=_Part_1_4558657.1118953559446 Content-Type: image/jpeg Content-ID: 5aeaa450-17f0-4484-b845-a8480c363444@example.org

╪ α ►JFIF ☺☻ ☺ ☺ █ ♠♠ ♀¶ ♀♂♂♀↓↕‼☼¶↔→▼▲↔→∟∟ $.' ",#∟∟(7),01444▼'9=82<.342 █ C☺ ♀♂♀↑↑2!∟!22222222222222222222222222222222222222222222

222222 └ ) ¬♥☺" ☻◄☺♥◄☺ ─ ▼ ☺♣☺☺☺☺☺☺ ☺☻♥♦ ♂ ─ ╡► ☻☺♥♥☻♦♥♣♣♦♦ ☺}☺☻♥ ♦◄♣↕!1A♠‼Qa"q¶2?#B▒┴§R╤≡$3bré

▬↨↑↓→%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzâäàåçêëèÆôöòûùÿÖÜóúñѪº¿⌐¬▓│┤╡╢╖╕╣║┬├─┼╞╟╚╔╩╥╙╘╒╓╫╪┘┌ßΓπΣσµτΦΘΩ±≥≤⌠⌡÷≈°∙· ─

Above Photo is inlined binary data because its less than 1KB and image which is more than 1KB is sent as attachment. Here is the associated schema:

    <element name="Photo" type="base64Binary"/>
    
    <element name="image" type="base64Binary"
            **xmime:expectedContentTypes="image/jpeg"**/>
</sequence>

Example 2. MTOM Sample - mtom-soap12

This is SOAP 1.2 MTOM Sample. Here is how the JAX-WS generated soap message looks on the wire:

<element name="image" type="base64Binary" **xmime:expectedContentTypes="image/jpeg"**/>

Content-Type: Multipart/Related; start-info="application/soap+xml"; type="application/xop+xml"; boundary="----=_Part_0_1744155.1118960238280" Content-Length: 1946 SOAPAction: ""

------=_Part_1_4558657.1118960238320 Content-Type: application/xop+xml; type="application/soap+xml"; charset=utf-8

<soapenv:Envelope xmlns:soapenv="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2003/05/soap-envelope"> soapenv:Body RHVrZQ== <xop:Include** **xmlns:xop="http://www.w3.org/2004/08/xop/include"** **href="cid:42a7ee0a-20ee-426b-a135-094d72bc138f@example.org"/>

------=_Part_1_4558657.1118960238320 Content-Type: application/octet-stream Content-ID: 42a7ee0a-20ee-426b-a135-094d72bc138f@example.org

╪ α ►JFIF ☺☻ ☺ ☺ █ ♠♠ ♀¶

♀♂♂♀↓↕‼☼¶↔→▼▲↔→∟∟
$.' ",#∟∟(7),01444▼'9=82<.342 █ C☺ ♀♂♀↑↑2!∟!22222222222222222222222222222222222222222222

222222 └ ' )♥☺" ☻◄☺♥◄☺ ─ ▼ ☺♣☺☺☺☺☺☺ ☺☻♥♦ ♂ ─ ╡► ☻☺♥♥☻♦♥♣♣♦♦ ☺}☺☻♥ ♦◄♣↕!1A♠‼Qa"q¶2?#B▒┴§R╤≡$3bré

▬↨↑↓→%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzâäàåçêëèÆôöòûùÿÖÜóúñѪº¿⌐¬▓│┤╡╢╖╕╣║┬├─┼╞╟╚╔╩╥╙╘╒╓╫╪┘┌ßΓπΣσµτΦΘΩ±≥≤⌠⌡÷≈°∙· ─ ▼☺ ♥☺☺☺☺☺☺☺☺☺ ☺☻♥♦

7.3. swaRef

WS-I Attachment Profile 1.0 defines mechanism to reference MIME attachment parts using swaRef. In this mechanism the content of XML element of type wsi:swaRef is sent as MIME attachment and the element inside SOAP Body holds the reference to this attachment in the CID URI scheme as defined by RFC 2111.

7.3.1. swaRef in JAX-WS 2.0

JAXB 2.0 defines mapping of wsi:swaRef schema type to javax.activation.DataHandler. An application will construct the DataHandler with the data and the appropriate MIME type and JAX-WS will coordinate with JAXB and SAAJ to send it as attachment MIME part.

7.3.2. How to use swaRef

An XML element of type wsi:swaRef is mapped to a DataHandler and is sent as attachment over the wire. For example,

will be sent over the wire as :

Content-Type: Multipart/Related; start-info="text/xml"; type="application/xop+xml"; boundary="----=_Part_4_32542424.1118953563492" Content-Length: 1193 SOAPAction: ""

------=_Part_5_32550604.1118953563502 Content-Type: application/xop+xml; type="text/xml"; charset=utf-8

<soapenv:Envelope xmlns:soapenv="" title="undefined" rel="noopener noreferrer">http://schemas.xmlsoap.org/soap/envelope/"> soapenv:Body cid:b0a597fd-5ef7-4f0c-9d85-6666239f1d25@example.jaxws.sun.com

------=_Part_5_32550604.1118953563502 Content-Type: application/xml Content-ID: <**b0a597fd-5ef7-4f0c-9d85-6666239f1d25@example.jaxws.sun.com**>

Simple example of application Simple example ejb1.jar ejb2.jar web.war web

7.3.3. swaRef Sample

Refer to swaRef sampletestSwaRef() method in samples/mime/src/mime/client/MimeApp.java

8. SOAP 1.2

8.1. Introduction

The default binding supported by JAX-WS 2.0 is SOAP 1.1 over HTTP. With this release we have added SOAP 1.2 binding over HTTP support into JAX-WS 2.0. This document describes how SOAP 1.2 binding can be applied to an endpoint and how it can be used on the client side in the case of proxy port. To enable SOAP 1.2 support in the Dispatch client please refer to the Dispatch documents.

8.2. SOAP 1.2 Endpoint

To enable SOAP 1.2 binding on an endpoint. You would need to set binding attribute value in sun-jaxws.xml to SOAP 1.2 HTTP binding value as specified byjavax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING which is: "http://www.w3.org/2003/05/soap/bindings/HTTP/" or "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/"

Here is the sun-jaxws.xml fromfromjava-soap1.2 sample:

<endpoint name="fromjava-soap12" implementation="fromjava_soap12.server.AddNumbersImpl" binding="http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/ url-pattern="/addnumbers"/>

JAX-WS 2.0 generates WSDL on the fly when requested by a client. If this binding attribute is present and is equal to SOAP 1.2 HTTP binding WSDL with SOAP 1.2 binding is generated. Based on this binding descriptor JAX-WS runtime configures itself to handle SOAP 1.2 messages.

Notice that the binding id "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/" is not a standard binding id. If you use SOAP 1.2 binding id "http://www.w3.org/2003/05/soap/bindings/HTTP/" defined by JAX-WS, still the endpoint is configured to use SOAP 1.2 binding, except that a wsdl will not be generated on the fly.

Alternatively, you can specify the binding through@BindingType annotation in the implementation class to use SOAP 1.2 binding. Here is an example from thefromjava_soap12 sample.

@WebService @BindingType(value = "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/") public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be added " +
                "!", "Numbers: " + number1 + ", " + number2);
    }
    return number1 + number2;
}

}

The commandline wsgen and the equivalent ant task can be used to generate SOAP 1.1 (default) or SOAP 1.2 WSDL. The binding information should be passed using -wsdl:protocol switch.

8.3. Client

On the client there is nothing special that has to be done. JAX-WS runtime looks into the WSDL to determine the binding being used and configures itself accordingly. wsimport command line tool orwsimport ant task can be used to import the WSDL and to generated the client side artifacts.

8.4. Samples

There are 2 samples bundled with this release

A SOAP 1.2 message generated by JAX-WS:

Content-Type: application/soap+xml; charset=utf-8 Content-Length: 178 SOAPAction: ""

<soapenv:Envelope xmlns:soapenv="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2003/05/soap-envelope"> soapenv:Body -10 20

A SOAP 1.2 Fault message generated by JAX-WS:

Content-Type:application/soap+xml; charset=utf-8 Content-Length: 476 SOAPAction: ""

<soapenv:Envelope xmlns:soapenv="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2003/05/soap-envelope"> soapenv:Body soapenv:Fault soapenv:Code soapenv:Value soapenv:Sender soapenv:Reason <soapenv:Text xml:lang="en"> Negative number cant be added! soapenv:Detail Numbers: -10, 20 Negative number cant be added!

9. WSDL Customization

The JAX-WS 2.0 specification defines standard XML-based customization for WSDL to Java mapping and to control certain features. These customizations, or binding declarations, can customize almost all WSDL components that can be mapped to Java, such as the service endpoint interface class, method name, parameter name, exception class, etc. The other important thing you can do with these binding declarations is control certain features, such as asynchrony, provider, wrapper style, and additional headers. For example, a client application can enable asynchrony for a particular operation in aportType or all operations in aportType or all portType operations defined in the WSDL file.

The JAX-RPC 1.1 specification did not define a standard customization architecture. However JAX-RPC 1.x SI had limited WSDL to Java customization support. It allowed a JAX-RPC 1.x application to:

But these customizations were not portable and could not be used across other JAX-RPC implementations. JAX-WS RI 2.3.0-SNAPSHOT provides complete support for all the binding declarations defined by the specification.

9.1. Declaring Customizations

All the binding declaration elements live inhttp://java.sun.com/xml/ns/jaxws namespace. There are two ways to specify binding declarations. In the first approach, all binding declarations pertaining to a given WSDL document are grouped together in a standalone document, called an_external binding file_. The second approach consists of embedding binding declarations directly inside a WSDL document. In either case, the jaxws:bindings element is used as a container for JAX-WS binding declarations. Thejaxws prefix maps to thehttp://java.sun.com/xml/ns/jaxws namespace.

9.1.1. External Binding Declaration

External binding files are semantically equivalent to embedded binding declarations. When wsimport processes the WSDL document for which there is an external binding file, it internalizes the binding declarations defined in the external binding file on the nodes in the WSDL document they target using the wsdlLocation attribute. The embedded binding declarations can exist in a WSDL file and an external binding file targeting that WSDL, butwsimport may give an error if, upon embedding the binding declarations defined in the external binding files, the resulting WSDL document contains conflicting binding declarations.

9.1.1.1. Root Binding Element

The jaxws:bindings declaration appears as the root of all other binding declarations. This top-level jaxws:bindings element must specify the location of the WSDL file as a URI in the value ofwsdlLocation attribute.

Its important that the wsdlLocation attribute on the root jaxws:bindings declaration is same as the WSDL location URI given towsimport.

<jaxws:bindings wsdlLocation="http://localhost:8080/jaxws-external-customize/addnumbers?WSDL" jaxws:xmlns="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/jaxws">

...

9.1.1.2. Child Binding Elements

The root jaxws:bindings element may contain child jaxws:bindings elements. In this case the child jaxws:bindings element must carry an XPath expression in the node attribute to refer to the WSDL node it customizes.

Here is an excerpt from an external binding file samples/external-customize/etc/custom-client.xml in the external-customize sample:

<jaxws:bindings wsdlLocation="http://localhost:8080/jaxws-external-customize/addnumbers?WSDL" jaxws:xmlns="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/jaxws"> <jaxws:bindings node="wsdl:definitions" xmlns:wsdl="" title="undefined" rel="noopener noreferrer">http://schemas.xmlsoap.org/wsdl/"> <jaxws:package name="external_customize.client"/>

    ...
    
</jaxws:bindings>

In this example the childjaxws:bindings applies package customization. An XPath expression in the node attribute refers to the root node of the WSDL document, which iswsdl:definitions and declares the packageexternal_customize.client for all the generated Java classes mapped from the WSDL file.

9.1.2. Embedded Binding Declarations

Embedded binding declarations directly inside the WSDL follow different rules compared to the binding declarations declared in the external binding file. Here are some important facts and rules as defined in the JAX-WS 2.0 specification:

Here's an example of embedded binding declarations in the WSDL AddNumbers.wsdl from theinline-customize sample:

<wsdl:portType name="AddNumbersImpl">

<jaxws:bindings xmlns:jaxws="http://java.sun.com/xml/ns/jaxws">
    
    <jaxws:class name="MathUtil"/>
    ...
</jaxws:bindings>
<wsdl:operation name="addNumber">
    ...
</wsdl:operation>

The above WSDL file excerpt shows thewsdl:portType customization.jaxws:bindings appears as extension element ofportType. It customizes the class name of the generated service endpoint interface. Without this customization, or by default, the service endpoint interface class is named after the wsdl:portType name. The binding declarationjaxws:class customizes the generated class to be named MathUtil instead ofAddNumberImpl.

In the following section, all the possible standard customizations and their scope is described. Global customizations can be specified under wsdl:definitions element and other customizations can be specified under the node of its scope.

9.2. Standard Customizations

This section provides the details of all the possible WSDL binding declarations.

9.2.1. Global bindings

The global customizations are the customizations that applies to the entire scope of wsdl:definition in the wsdl referenced by the rootjaxws:bindings@wsdlLocation.Following customizations have the global scopes:

<jaxws:package name="..."/>

jaxws:enableWrapperStyle/

jaxws:enableAsyncMapping/

These can appear as direct child of the Root Binding Element declarations in the external customization file. For example:

<package name="external_customize.client"/>
<enableWrapperStyle>true</enableWrapperStyle>
<enableAsyncMapping>false</enableAsyncMapping>

In embedded usage, the global customization can be specified under <wsdl:definitions> node of the wsdl.

9.2.2. Package Customization

By default wscompile generates WSDL artifacts in a package computed from the WSDLtargetNamespace. For example, a WSDL file with the targetNamespace http://duke.example.org without any package customization will be mapped to the org.duke package. To customize the default package mapping you would use ajaxws:package customization on thewsdl:definitions node or it can directly appear inside the top level bindings element.

An important thing to note is that -p option on commandline wsimport.sh tool (package attribute on wsimport ant task), overrides thejaxws:package customization,it also overrides the schema package customization specified using jaxb schema customization.

For example:

Mathutil package

...

or

Mathutil package

    ...
    
</bindings>

...

9.2.3. Wrapper Style

wsimport by default applies wrapper style rules to the abstract operation defined in thewsdl:portType, and if an operation qualifies the Java method signature is generated accordingly. Wrapper style Java method generation can be disabled by usingjaxws:enableWrapperStyle.

jaxws:enableWrapperStyle can appear on the toplevel bindings element (with@wsdlLocation attribute), it can also appear on the following target nodes:

For example:

<enableWrapperStyle>true</enableWrapperStyle>

<bindings
        node="wsdl:definitions/wsdl:portType[@name='AddNumbersImpl']/wsdl:operation[@name='addNumbers']">
    
    <enableWrapperStyle>false</enableWrapperStyle>
    
    ...
    
</bindings>

...

In the example above the wrapper style is disabled for theaddNumbers operation inAddNumbersImpl portType .This is because wsimport processes this binding in the following order: firstwsdl:operation, then its parentwsdl:portType, and finallywsdl:definitions. Herewsdl:operation addNumbers has this customization disabled so this is what is applied bywsimport to generate a bare Java method signature.

9.2.4. Asynchrony

A client application can use thejaxws:enableAsyncMapping binding declaration so that wsimport will generate async polling and callback operations along with the normal synchronous method when it compiles a WSDL file.

It has the same target nodes as the wrapper style binding declaration described above in section 2.2.

Example :

<enableAsyncMapping>false</enableAsyncMapping>

<bindings
        node="wsdl:definitions/wsdl:portType[@name='AddNumbersImpl']/wsdl:operation[@name='addNumbers']">
    
    <enableAsyncMapping>true</enableAsyncMapping>

    ...

</bindings>

...

In the above example wsimport will generate async polling and callback methods for theaddNumbers operation. In thewsdl:definition node, the async customization is disabled or false but the wsdl:operation node has it enabled or true, and so wsimport generates the async methods of thewsdl:operation addNumbers.

This is how the generated signatures look (annotations are removed from synchronous method for reading simplicity):

public int addNumbers(int number1, int number2) throws org.duke.AddNumbersFault_Exception, java.rmi.RemoteException;

public Response addNumbers(int number1, int number2);

public Future<?> addNumbers(int number1, int number2, AsyncHandler);

...

9.2.5. The Provider Interface

By default the value of jaxws:provider binding is false. That is, provider interface generation is disabled. In order to mark a port as provider interface this binding declaration should refer to thewsdl:port node using an XPath expression. Please note that provider binding declaration applies only when developing a server starting from a WSDL file.

9.2.6. Class Customization

The generated class for wsdl:portType,wsdl:fault,soap:headerfault, andwsdl:server can be customized using thejaxws:class binding declaration. Refer to the external binding declaration filecustom-client.xml in theexternal-customize sample.

9.2.6.1. The Service Endpoint Interface Class

wscompile will generate the service endpoint interface class MathUtil instead of the default AddNumbersImpl in this example:

<class name="MathUtil">
    <javadoc>Perform mathematical computations</javadoc>
</class>
9.2.6.2. The Exception Class

wsimport will generate theMathUtilException class instead of the default AddNumbersExeption in this example:

Exception generated during computation

9.2.6.3. The Service Class

wsimport will generateMathUtilService instead of the defaultAddNumbersService in this example:

<class name="MathUtilService">
    <javadoc>Service to perform mathematical computations</javadoc>
</class>

9.2.7. Java Method Customization

The jaxws:method binding declaration is used to customize the generated Java method name of a service endpoint interface and to customize the port accessor method in the generated Service class. Refer to the external binding declaration filecustom-client.xml in theexternal-customize sample.

9.2.7.1. Service Endpoint Interface Methods

wsimport will generate a method namedadd instead of the defaultaddNumbers in this example:

<method name="add">
    <javadoc>Adds the numbers</javadoc>
</method>
9.2.7.2. Port Accessor Methods in the Service Class

wsimport will generate thegetMathUtil port accessor method in the generated Service class instead of the default getAddNumbersImplPort method in this example:

Returns MathUtil port

9.2.8. Java Parameter Customization

The jaxws:parameter binding declaration is used to change the parameter name of generated Java methods. It can be used to change the method parameter of awsdl:operation in awsdl:portType. Refer to the external binding declaration file custom-client.xml of theexternal-customize sample.

<parameter
        part="definitions/message[@name='addNumbers']/part[@name='parameters']"
        element="tns:number1" name="num1"/>

...

The above sample renames the default parameter name of the Java method addNumbers fromnumber1 to num1.

9.2.9. Javadoc customization

jaxws:javadoc customization can be used to specify javadoc text for java package, class(SEI, Service or Exception class) and on the methods in SEI and service class. Inorder to do it,it should appear on the corresponding wsdl nodes.

For package level javadoc:

<jaxws:package name="xs:string"> jaxws:javadocxs:string

For class level javadoc:

<jaxws:class name="xs:string"> jaxws:javadocxs:string

For method level javadoc:

<jaxws:method name="xs:string"> jaxws:javadocxs:string

For specific samples on javadoc customization for class, refer The Service Endpoint Interface Class, The Exception Class and The Service Class customization. For javadoc customization on method refer Service Endpoint Interface Methods and Port Accessor Methods in the Service Class customization and for package level customization refer Package Customization.

9.2.10. XML Schema Customization

An XML schema inlined inside a compiled WSDL file can be customized by using standard JAXB bindings. These JAXB bindings can live inside the schema or as the child of ajaxws:bindings element in an external binding declaration file:

<jaxws:bindings node="wsdl:definitions/wsdl:types/xsd:schema[@targetNamespace='" title="undefined" rel="noopener noreferrer">http://duke.example.org']"> jaxb:schemaBindings <jaxb:package name="fromwsdl.server"/>

External XML schema files imported by the WSDL file can be customized using a JAXB external binding declaration file:

<jxb:bindings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="1.0"> <jxb:bindings schemaLocation="http://localhost:8080/jaxws-external-customize/schema1.xsd" node="/xsd:schema"> jxb:schemaBindings <jxb:package name="fromjava.client"/>

...

The external JAXB binding declaration file can be passed towsimport using the -b switch. See the JAX-WS wsimport documentation for details.

9.2.11. Handler Chain Customization

jaxws:bindings customization can be used to customize or add handlers. All that is needed is to inline a handler chain configuration conforming to JSR 181 Handler Chain configuration schema inside jaxws:bindings element.

Below is a sample JAX-WS binding declaration file with JSR 181 handler chain configuration:

<jaxws:bindings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" wsdlLocation="http://localhost:8080/jaxws-fromwsdlhandler/addnumbers?WSDL" xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:javaee="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/javaee"> <jaxws:bindings node="wsdl:definitions"> javaee:handler-chain javaee:handler-chain-nameLoggingHandlers

        <javaee:handler>
            <javaee:handler-name>Logger</javaee:handler-name>
            <javaee:handler-class>fromwsdlhandler.common.LoggingHandler
            </javaee:handler-class>
        </javaee:handler>
    </javaee:handler-chain>
</jaxws:bindings>

When this customization file is passed on towsimport tool using -b switch together with the WSDL, wsimport generates all the artifacts togather with a handler configuration file which has everything inside jaxws:bindings element enclosing thejws:handler-chain element. It also add@javax.jws.HandlerChain annotation in the generated SEI class. JAXWS runtime uses the@HandlerChain annotation from the SEI to find the handlers that has to be added into the handle chain.

10. Annotations

10.2. JSR 181 (Web Services Metadata) Annotations

Because JSR 181 has been written to work with JAX-RPC 1.1, we have made slight changes in the use and interpretation of these annotations to work better with JAX-WS 2.0. We are working with the JSR 181 expert group to align the next release with JAX-WS 2.0 and we hope that all of the changes we have made will be folded in.

10.2.1. @javax.jws.WebService

The purpose of this annotation is to mark an endpoint implementation as implementing a web service or to mark that a service endpoint interface as defining a web service interface. All endpoint implementation classes MUST have aWebService annotation and must meet the requirements of section 3.3 of the JAX-WS 2.0 specification.

Table 3. @javax.jws.WebService - Description of Properties

Property Description Default
name The name of thewsdl:portType The unqualified name of the Java class or interface
targetNamespace The XML namespace of the the WSDL and some of the XML elements generated from this web service. Most of the XML elements will be in the namespace according to the JAXB mapping rules. The namespace mapped from the package name containing the web service according to section 3.2 of the JAX-WS 2.0 specification.
serviceName The Service name of the web service:wsdl:service The unqualified name of the Java class or interface + "Service"
endpointInterface The qualified name of the service endpoint interface. If the implementation bean references a service endpoint interface, that service endpoint interface is used to determine the abstract WSDL contract (portType and bindings). In this case, the service implementation bean MUST NOT include any JSR 181 annotations other than@WebService and@HandlerChain In addition, the@WebService annotation MUST NOT include the name annotation element. The endpoint implementation class is not required to implement the endpointInterface. None – If not specified, the endpoint implementation class is used to generate the web service contract. In this case, a service endpoint interface is not required.
portName Thewsdl:portName The WebService.name + "Port"
wsdlLocation Not currently used by JAX-WS RI 2.3.0-SNAPSHOT
10.2.1.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface WebService { String name() default "";

String targetNamespace() default "";

String serviceName() default "";

String wsdlLocation() default "";

String endpointInterface() default "";

String portName() default "";

}

10.2.1.2. Examples

Example 3. @javax.jws.WebService - Example 1

@WebService(name = "AddNumbers", targetNamespace = "http://duke.example.org") public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be added " +
                "!", "Numbers: " + number1 + ", " + number2);
    }
    return number1 + number2;
}

}

If you are familiar with JAX-RPC 1.1, you will notice that the AddNumbersImpl implementation class does not implement a service endpoint interface. In JAX-WS 2.3.0 a service endpoint interface is no longer required. If a service endpoint interfaces is desired, then the @WebService annotation on the endpoint implementation is modified to specify the endpoint interface and the actual service endpoint interface must also have a @WebService annotation. The following is the aboveAddNumbersImpl modified to use a service endpoint interface.

Example 4. @javax.jws.WebService - Example 2 - Implementation class using Service Endpoint Interface

@WebService(endpointInterface = "annotations.server.AddNumbersIF") public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be " +
                "added!", "Numbers: " + number1 + ", " + number2);
    } return number1 + number2;
}

}

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") public interface AddNumbersIF extends Remote {

public int addNumbers(int number1, int number2) throws 
        RemoteException, AddNumbersException;

}

10.2.2. @javax.jws.WebMethod

The purpose of this annotation is to expose a method as a web service operation. The method must meet all the requirements of section 3.4 of the JAX-WS 2.0 specification.

Table 4. @javax.jws.WebMethod - Description of Properties

Property Description Default
operationName The name of thewsdl:operation matching this method. For operations using the mode defined bySOAPBinding.Style.DOCUMENT,SOAPBinding.Use.LITERAL, andSOAPBinding.ParameterStyle.BARE, this name is also used for the global XML element representing the operations body element. The namespace of this name is taken from the value@WebService.targetNamespace or its default value. The name of the Java method
action The XML namespace of the the WSDL and some of the XML elements generated from this web service. Most of the XML elements will be in the namespace according to the JAXB mapping rules. ""
exclude Used to exclude a method from the WebService. false
10.2.2.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface WebMethod { String operationName() default "";

String action() default "";

boolean exclude() default false;

}

10.2.2.2. Examples

Example 5. @javax.jws.WebMethod - Example

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") public interface AddNumbersIF extends Remote {

@WebMethod(operationName = "add", action = "urn:addNumbers")
public int addNumbers(int number1, int number2) throws 
        RemoteException, AddNumbersException;

}

10.2.3. @javax.jws.OneWay

The purpose of this annotation is to mark a method as a web service one-way operation. The method must meet all the requirements of section 3.4.1 of the JSR 224 spec.

There are no properties on the OneWay annotation.

10.2.3.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Oneway { }

10.2.3.2. Examples

Example 6. @javax.jws.OneWay - Example

@WebService(name = "CheckIn") public class CheckInIF {

@WebMethod
@OneWay
public void checkIn(String name);

}

10.2.4. @javax.jws.WebParam

This annotation is used to customize the mapping of a single parameter to a message part or element.

Table 5. @javax.jws.WebParam - Description of Properties

Property Description Default
name Name of the parameter.If the operation is RPC style and@WebParam.partName has not been specified, this is name of thewsdl:part representing the parameter.@WebMethod.operation Name, if the operation is document style and the parameter style isBARE.Otherwise, the default is argN if the operation is document style or the parameter maps to a header, this is the local name of the XML element representing the parameter.A name MUST be specified if the operation is document style, the parameter style is BARE, and the mode is OUT orINOUT. @WebMethod.operation Name, if the operation is document style and the parameter style is BARE. Otherwise, the default is argN, where N represents the index of the parameter in the method signature (starting atarg0).
targetNamespace The XML namespace for the parameter. Only used if the operation is document style or the paramater maps to a header. If the target namespace is set to "", this represents the empty namespace. The empty namespace, if the operation is document style, the parameter style isWRAPPED, and the parameter does not map to a header. Otherwise, the default is thetargetNamespace for the Web Service.
mode Represents the direction the parameter flows for this method. Possible values areIN, INOUT andOUT. INOUT andOUT modes can only be used with parameters that meet the requirements for a holder as classified by section 3.5 of the JAX-WS 2.0 specification. OUT andINOUT parameters can be used by all RPC andDOCUMENT bindings. IN for non-holder parameters INOUT for holder parameters.
header Specifies whether the parameter should be carried in a header. FALSE
partName Used to specify thepartName for the parameter withRPC orDOCUMENT/BARE operations. @WebParam.name
10.2.4.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface WebParam {

public enum Mode {
    IN,
    OUT,
    INOUT
}

String name() default "";

String targetNamespace() default "";

Mode mode() default Mode.IN;

boolean header() default false;

String partName() default "";

}

10.2.4.2. Examples

Example 7. @javax.jws.WebParam - Example 1

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") public interface AddNumbersIF extends Remote {

@WebMethod(operationName = "add", action = "urn:addNumbers")
@WebResult(name = "return")
public int addNumbers(@WebParam(name = "num1") int number1, 
                      @WebParam(name = "num2") int number2) throws 
        RemoteException, AddNumbersException;

}

Example 8. @javax.jws.WebParam - Example 2

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") public interface AddNumbersIF extends Remote {

@WebMethod(operationName = "add", action = "urn:addNumbers")
@WebResult(name = "return")
public void addNumbers(@WebParam(name = "num1") int number1, 
                       @WebParam(name = "num2") int number2, 
                       @WebParam(name = "result",
        mode = WebParam.Mode.OUT) Holder<Integer> result) throws RemoteException, AddNumbersException;

}

10.2.5. @javax.jws.WebResult

This annotation is used to customize the mapping of the method return value to a WSDL part or XML element.

Table 6. @javax.jws.WebResult - Description of Properties

Property Description Default
name The name of the return value in the WSDL and on the wire. For RPC bindings this is the part name of the return value in the response message. ForDOCUMENT bindings this is the local name of the XML element representing the return value. "return" for RPC andDOCUMENT/WRAPPED bindings. Method name + "Response" forDOCUMENT/BARE bindings.
targetNamespace The XML namespace for the return value. Only used if the operation is document style or the return value maps to a header. If the target namespace is set to "", this represents the empty namespace. The empty namespace, if the operation is document style, the parameter style isWRAPPED, and the return value does not map to a header, Otherwise, the default is the targetNamespace for the Web Service.
header Specifies whether the result should be carried in a header. FALSE
partName Used to specify thepartName for the result withRPC orDOCUMENT/BARE operations. @WebResult.name
10.2.5.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface WebResult {

String name() default "return";

String targetNamespace() default "";

boolean header() default false;

String partName() default "";

}

10.2.5.2. Examples

Example 9. @javax.jws.WebResult - Example

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") public interface AddNumbersIF extends Remote {

@WebMethod(operationName = "add", action = "urn:addNumbers")
@WebResult(name = "return")
public int addNumbers(@WebParam(name = "num1") int number1, 
                      @WebParam(name = "num2") int number2) throws 
        RemoteException, AddNumbersException;

}

10.2.6. @javax.jws.HandlerChain

This annotation is used to specified an externally defined handler chain.

Table 7. @javax.jws.HandlerChain - Description of Properties

Property Description Default
file Location of the file containing the handler chain definition. The location can be relative or absolute with in a classpath system. If the location is relative, it is relative to the package of the web service. If it is absolute, it is absolute from some path on the classpath. None
name DEPRECATED The handler chain name from within the handler chain file. ""
10.2.6.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface HandlerChain {

String file();

@Deprecated String name() default "";

}

10.2.6.2. Examples

Example 10. @javax.jws.HandlerChain - Example

@WebService @HandlerChain(file = "handlers.xml") public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be added " +
                "!", "Numbers: " + number1 + ", " + number2);
    }
    return number1 + number2;
}

}

Example 11. @javax.jws.HandlerChain - Example - handlers.xml

<jws:handler-config xmlns:jws="" title="undefined" rel="noopener noreferrer">http://java.sun.com/xml/ns/javaee"> jws:handler-chains jws:handler-chain jws:handler jws:handler-classfromjavahandler.common.LoggingHandler

Important

When using a handler chain file, it is important that the file is store in the appropriate place in the classpath so that the file can be found. This means that when a raw WAR file is created that the file must be place in the proper directory. Please refer to thefromjavahandlers sample application and the Handler for more information.

10.2.7. @javax.jws.soap.SOAPBinding

JSR 181 also allows you to specify aSOAPBinding annotation on an endpoint implementation or service endpoint interface. This annotation lets the developer choose between DOCUMENT\LITERAL WRAPPED, DOCUMENT\LITERAL BARE,RPC\LITERAL and RPC\ENCODED endpoints with the default being DOCUMENT\LITERAL WRAPPED. JAX-WS 2.3.0 does not support RPC\ENCODED. The main difference between DOCUMENT\LITERAL BARE andDOCUMENT\LITERAL WRAPPED is that methods on aDOCUMENT\LITERAL WRAPPED endpoint can have multiple parameters bound to the body of a SOAP message, while aDOCUMENT\LITERAL BARE can only have one such parameter. The main difference between DOCUMENT\LITERAL WRAPPED and RPC\LITERAL is that aDOCUMENT\LITERAL invocation can be fully validated by a standard validating XML parser, while anRPC\LITERAL invocation cannot because of the implied wrapper element around the invocation body.

Table 8. @javax.jws.soap.SOAPBinding - Description of Properties

Property Description Default
style Defines the style for messages used in a web service. The value can be eitherDOCUMENT orRPC. DOCUMENT
use Defines the encoding used for messages used in web service. Can only beLITERAL for JAX-WS 2.3.0. LITERAL
parameterStyle Determines if the method's parameters represent the entire message body or whether the parameters are wrapped in a body element named after the operation. Choice of WRAPPED or BARE. BARE can only be used with DOCUMENT style bindings. WRAPPED
10.2.7.1. Annotation Type Definition

@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface SOAPBinding {

public enum Style {
    DOCUMENT,
    RPC,
}

public enum Use {
    LITERAL,
    ENCODED,
}

public enum ParameterStyle {
    BARE,
    WRAPPED,
}

Style style() default Style.DOCUMENT;

Use use() default Use.LITERAL;

ParameterStyle parameterStyle() default ParameterStyle.WRAPPED;

}

10.2.7.2. Examples

Example 12. @javax.jws.soap.SOAPBinding - Example

@WebService(targetNamespace = "http://duke.example.org", name = "AddNumbers") @SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL) public interface AddNumbersIF extends Remote {

@WebMethod(operationName = "add", action = "urn:addNumbers")
@WebResult(name = "return")
public int addNumbers(@WebParam(name = "num1") int number1, 
                      @WebParam(name = "num2") int number2) throws 
        RemoteException, AddNumbersException;

}

10.3. JSR 224 (JAX-WS) Annotations

The following are standard annotations needed by JAX-WS that are not defined in JSR 181. The developer may not ever use these annotations directly as some of them are generated by JAX-WS tools but they will be presented here to avoid confusion.

10.3.1. @javax.xml.ws.BindingType

The BindingType annotation is used to specify the binding to use for a web service endpoint implementation class. As well as specify additional features that may be enabled.

This annotation may be overriden programmatically or via deployment descriptors, depending on the platform in use.

Table 9. @javax.xml.ws.BindingType - Description of Properties

Property Description Default
value A binding identifier (a URI).See theSOAPBinding andHTTPBinding for the definition of the standard binding identifiers.@see javax.xml.ws.Binding@see javax.xml.ws.soap.SOAPBinding#SOAP11HTTP_BINDING@see javax.xml.ws.soap.SOAPBinding#SOAP12HTTP_BINDING@see javax.xml.ws.http.HTTPBinding#HTTP_BINDING "SOAP 1.1 Protocol"/HTTP
10.3.1.1. Annotation Type Definition

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface BindingType {

String value() default "";


Feature[] features() default {};

}

10.3.1.2. Examples

Example 13. @javax.xml.ws.BindingType - Example

Given the web service defined by

@WebService @BindingType(value = "http://www.w3.org/2003/05/soap/bindings/HTTP/") public class AddNumbersImpl {

public int addNumbers(int number1, int number2) throws 
        AddNumbersException {
    if (number1 < 0 || number2 < 0) {
        throw new AddNumbersException("Negative number cant be " + 
                "added!", "Numbers: " + number1 +
                ", " + number2);
    }
    return number1 + number2;
}

}

The deployed endpoint would use the SOAP 1.2 over HTTP binding.

10.3.2. @javax.xml.ws.RequestWrapper

This annotation annotates methods in the Service Endpoint Interface with the request wrapper bean to be used at runtime.

When starting from Java this annotation is used to resolve overloading conflicts in DOCUMENT\LITERAL mode. Only the className is required in this case.

Table 10. @javax.xml.ws.RequestWrapper - Description of Properties

Property Description Default
localName Specifies thelocalName of the XML Schema element representing this request wrapper. operationName as defined by@javax.jws.WebMethod
targetNamespace namespace of the request wrapper element. the targetNamespace of the SEI
className The name of the Class representing the request wrapper.
10.3.2.1. Annotation Type Definition

@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface RequestWrapper {

public String localName() default "";


public String targetNamespace() default "";


public String className() default "";

}

10.3.2.2. Examples

Example 14. @javax.xml.ws.RequestWrapper - Example

public interface AddNumbersImpl {

@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addNumbers", 
        targetNamespace = "http://server.fromjava/", 
        className = "fromjava.client.AddNumbers")
@ResponseWrapper(localName = "addNumbersResponse",
        targetNamespace = "http://server.fromjava/", 
        className = "fromjava.client.AddNumbersResponse")
public int addNumbers(@WebParam(name = "arg0", targetNamespace = "") 
                          int arg0, @WebParam(name = "arg1", targetNamespace = "") int arg1) throws AddNumbersException_Exception;

}

10.3.3. @javax.xml.ws.ResponseWrapper

This annotation annotates methods in the Service Endpoint Interface with the response wrapper bean to be used at runtime.

When starting from Java this annotation is used to resolve overloading conflicts in DOCUMENT\LITERAL mode. Only the className is required in this case.

Table 11. @javax.xml.ws.ResponseWrapper - Description of Properties

Property Description Default
localName Specifies thelocalName of the XML Schema element representing this request wrapper. operationName as defined by@javax.jws.WebMethod
targetNamespace namespace of the request wrapper element. the targetNamespace of the SEI
className The name of the Class representing the request wrapper.
10.3.3.1. Annotation Type Definition

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ResponseWrapper {

public String localName() default "";


public String targetNamespace() default "";


public String className() default "";

}

10.3.3.2. Examples

Example 15. @javax.xml.ws.ResponseWrapper - Example

public interface AddNumbersImpl {

@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addNumbers", 
        targetNamespace = "http://server.fromjava/", 
        className = "fromjava.client.AddNumbers")
@ResponseWrapper(localName = "addNumbersResponse",
        targetNamespace = "http://server.fromjava/", 
        className = "fromjava.client.AddNumbersResponse")
public int addNumbers(@WebParam(name = "arg0", targetNamespace = "") 
                          int arg0, @WebParam(name = "arg1", targetNamespace = "") int arg1) throws AddNumbersException_Exception;

}

10.3.4. @javax.xml.ws.ServiceMode

This annotation allows the Provider developer to indicate whether a Provider implementation wishes to work with entire protocol messages or just with protocol message payloads.

Table 12. @javax.xml.ws.ServiceMode - Description of Properties

Property Description Default
value Convey whether theProvider endpoint wants to access then entire message (MESSAGE) or just the payload (PAYLOAD). PAYLOAD
10.3.4.1. Annotation Type Definition

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface ServiceMode {

public Service.Mode value() default Service.Mode.PAYLOAD;

}

10.3.4.2. Examples

Example 16. @javax.xml.ws.ServiceMode - Example

@ServiceMode(value = Service.Mode.PAYLOAD) public class AddNumbersImpl implements Provider { public Source invoke(Source source) throws RemoteException { try { DOMResult dom = new DOMResult(); Transformer trans = TransformerFactory.newInstance() .newTransformer(); trans.transform(source, dom); Node node = dom.getNode(); Node root = node.getFirstChild(); Node first = root.getFirstChild(); int number1 = Integer.decode(first.getFirstChild() .getNodeValue()); Node second = first.getNextSibling(); int number2 = Integer.decode(second.getFirstChild() .getNodeValue()); return sendSource(number1, number2); } catch (Exception e) { e.printStackTrace(); throw new RemoteException("Error in provider endpoint"); } }

private Source sendSource(int number1, int number2) {
    int sum = number1 + number2;
    String body = "<ns:addNumbersResponse xmlns:ns =\"http://duke" +
            ".example.org\"><return>" + sum +
            "</return></ns:addNumbersResponse>";
    Source source = new StreamSource(new ByteArrayInputStream(body.getBytes()));
    return source;
}

}

10.3.5. @javax.xml.ws.WebEndpoint

Used to annotate the getPortName() methods of a generated service interface.

The information specified in this annotation is sufficient to uniquely identify a wsdl:port element inside a wsdl:service. The latter is determined based on the value of the WebServiceClient annotation on the generated service interface itself.

Table 13. @javax.xml.ws.WebEndpoint - Description of Properties

Property Description Default
name Defines the local name of the XML element representing the corresponding port in the WSDL. ""
10.3.5.1. Annotation Type Definition

@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebEndpoint {

String name() default "";

}

10.3.5.2. Examples

Example 17. @javax.xml.ws.WebEndpoint - Example

@WebServiceClient(name = "AddNumbersImplService", targetNamespace = "http://server.fromjava/", wsdlLocation = "http://localhost:8080/jaxws-fromjava/addnumbers" + "?wsdl") public class AddNumbersImplService extends Service { private final static URL WSDL_LOCATION; private final static QName ADDNUMBERSIMPLSERVICE = new QName ("http://server.fromjava/", "AddNumbersImplService"); private final static QName ADDNUMBERSIMPLPORT = new QName ("http://server.fromjava/", "AddNumbersImplPort");

static {
    URL url = null;
    try {
        url = new URL("http://localhost:8080/jaxws-fromjava" +
                "/addnumbers?wsdl");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    WSDL_LOCATION = url;
}

public AddNumbersImplService(URL wsdlLocation, QName serviceName) {
    super(wsdlLocation, serviceName);
}

public AddNumbersImplService() {
    super(WSDL_LOCATION, ADDNUMBERSIMPLSERVICE);
}


@WebEndpoint(name = "AddNumbersImplPort")
public AddNumbersImpl getAddNumbersImplPort() {
    return (AddNumbersImpl) super.getPort(ADDNUMBERSIMPLPORT, AddNumbersImpl.class);
}

}

10.3.6. @javax.xml.ws.WebFault

This annotation is generated by the JAX-WS tools into service specific exception classes generated from a WSDL to customize the local and namespace name of the fault element and the name of the fault bean and to mark the service specific exception as one generated from WSDL. The reason that the JAX-WS needs to know if a service specific exception is generated from a WSDL or not is because these exceptions will already have a fault bean generated for them. The name of this fault bean is not the same name as the one generated from a Java service specific exception class. For more information on this topic, please refer to section 3.6 of the JAX-WS 2.0 specification.

Table 14. @javax.xml.ws.WebFault - Description of Properties

Property Description Default
name Defines the local name of the XML element representing the corresponding fault in the WSDL. ""
targetNamespace Defines the namespace of the XML element representing the corresponding fault in the WSDL. ""
faultBean The qualified name of the Java class that represents the detail of the fault message. ""
10.3.6.1. Annotation Type Definition

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebFault {

public String name() default "";


public String targetNamespace() default "";


public String faultBean() default "";


public String messageName() default "";

}

10.3.6.2. Examples

Example 18. @javax.xml.ws.WebFault - Example

@javax.xml.ws.WebFault(name = "AddNumbersException", targetNamespace = "http://server.fromjava/jaxws") public class AddNumbersException_Exception extends Exception { private fromjava.client.AddNumbersException faultInfo;

public AddNumbersException_Exception(String message, 
                                     fromjava.client.AddNumbersException faultInfo) {
    super(message);
    this.faultInfo = faultInfo;
}

public AddNumbersException_Exception(String message, 
                                     fromjava.client
                                             .AddNumbersException faultInfo, Throwable cause) {
    super(message, cause);
    this.faultInfo = faultInfo;
}

public fromjava.client.AddNumbersException getFaultInfo() {
    return faultInfo;
}

}

10.3.7. @javax.xml.ws.WebServiceClient

The information specified in this annotation is sufficient to uniquely identify a wsdl:service element inside a WSDL document. This wsdl:service element represents the Web service for which the generated service interface provides a client view.

Table 15. @javax.xml.ws.WebServiceClient - Description of Properties

Property Description Default
name Defines the local name of thewsdl:serviceName in the WSDL. ""
targetNamespace Defines the namespace for thewsdl:serviceName in the WSDL. ""
wsdlLocation Specifies the location of the WSDL that defines this service. ""
10.3.7.1. Annotation Type Definition

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebServiceClient {

String name() default "";


String targetNamespace() default "";


String wsdlLocation() default "";

}

10.3.7.2. Examples

Example 19. @javax.xml.ws.WebServiceClient - Example

@WebServiceClient(name = "AddNumbersImplService", targetNamespace = "http://server.fromjava/", wsdlLocation = "http://localhost:8080/jaxws-fromjava/addnumbers" + "?wsdl") public class AddNumbersImplService extends Service { private final static URL WSDL_LOCATION; private final static QName ADDNUMBERSIMPLSERVICE = new QName ("http://server.fromjava/", "AddNumbersImplService"); private final static QName ADDNUMBERSIMPLPORT = new QName ("http://server.fromjava/", "AddNumbersImplPort");

static {
    URL url = null;
    try {
        url = new URL("http://localhost:8080/jaxws-fromjava" +
                "/addnumbers?wsdl");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    WSDL_LOCATION = url;
}

public AddNumbersImplService(URL wsdlLocation, QName serviceName) {
    super(wsdlLocation, serviceName);
}

public AddNumbersImplService() {
    super(WSDL_LOCATION, ADDNUMBERSIMPLSERVICE);
}


@WebEndpoint(name = "AddNumbersImplPort")
public AddNumbersImpl getAddNumbersImplPort() {
    return (AddNumbersImpl) super.getPort(ADDNUMBERSIMPLPORT, AddNumbersImpl.class);
}

}

10.3.8. @javax.xml.ws.WebServiceProvider

Annotation used to annotate a Provider implementation class.

Table 16. @javax.xml.ws.WebServiceProvider - Description of Properties

Property Description Default
targetNamespace The XML namespace of the the WSDL and some of the XML elements generated from this web service. Most of the XML elements will be in the namespace according to the JAXB mapping rules. The namespace mapped from the package name containing the web service according to section 3.2 of the JAX-WS 2.0 specification.
serviceName The Service name of the web service:wsdl:service The unqualified name of the Java class or interface + "Service"
portName Thewsdl:portName
wsdlLocation Location of the WSDL description for the service
10.3.8.1. Annotation Type Definition

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebServiceProvider {

String wsdlLocation() default "";    


String serviceName() default "";


String targetNamespace() default "";


String portName() default "";

}

10.3.8.2. Examples

Example 20. @javax.xml.ws.WebServiceProvider - Example

@ServiceMode(value = Service.Mode.PAYLOAD) @WebServiceProvider(wsdlLocation = "WEB-INF/wsdl/AddNumbers.wsdl") public class AddNumbersImpl implements Provider { public Source invoke(Source source) { try { DOMResult dom = new DOMResult(); Transformer trans = TransformerFactory.newInstance() .newTransformer(); trans.transform(source, dom); Node node = dom.getNode(); Node root = node.getFirstChild(); Node first = root.getFirstChild(); int number1 = Integer.decode(first.getFirstChild() .getNodeValue()); Node second = first.getNextSibling(); int number2 = Integer.decode(second.getFirstChild() .getNodeValue()); return sendSource(number1, number2); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Error in provider endpoint", e); } }

private Source sendSource(int number1, int number2) {
    int sum = number1 + number2;
    String body = "" + sum + "";
    Source source = new StreamSource(new ByteArrayInputStream(body.getBytes()));
    return source;
}

}

10.3.9. @javax.xml.ws.WebServiceRef

The WebServiceRef annotation is used to define a reference to a web service and (optionally) an injection target for it. Web service references are resources in the Java EE 5 sense.

Table 17. @javax.xml.ws.WebServiceRef - Description of Properties

Property Description Default
name The JNDI name of the resource. For field annotations, the default is the field name. For method annotations, the default is the JavaBeans property name corresponding to the method. For class annotations, there is no default and this must be specified.
type The Java type of the resource. For field annotations, the default is the type of the field. For method annotations, the default is the type of the JavaBeans property. For class annotations, there is no default and this must be specified.
mappedName A product specific name that this resource should be mapped to.
value The service class, always a type extending javax.xml.ws.Service. This element must be specified whenever the type of the reference is a service endpoint interface.
wsdlLocation Location of the WSDL description for the service
10.3.9.1. Annotation Type Definition

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface WebServiceRef {

String name() default "";


Class<?> type() default Object.class;


String mappedName() default "";


Class<? extends Service> value() default Service.class;


String wsdlLocation() default "";


String lookup() default "";

}

10.3.10. @javax.xml.ws.Action

The Action annotation allows explicit association of Action message addressing property with input, output, and fault messages of the mapped WSDL operation.

This annotation can be specified on each method of a service endpoint interface or implementation. For such a method, the mapped operation in the generated WSDL contains explicitwsaw:Action attribute on the WSDLinput, output andfault messages of the WSDLoperation based upon which attributes of theAction annotation have been specified.

Table 18. @javax.xml.ws.Action - Description of Properties

Property Description Default
input Explicit value ofAction message addressing property for the input message of the operation. If the value is "", then nowsaw:Action is generated. ""
ouput Explicit value ofAction message addressing property for the output message of the operation. If the value is "", then nowsaw:Action is generated. ""
fault Explicit value ofAction message addressing property for the fault message(s) of the operation. Each exception that is mapped to a fault and requires explicitAction message addressing property, need to be specified as a value in this property using FaultAction annotation. {}
10.3.10.1. Annotation Type Definition

@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Action {

String input() default "";


String output() default "";


FaultAction[] fault() default {};

}

10.3.10.2. Examples

Example 21. @javax.xml.ws.Action - Example 1 - Specify explicit values for Action message addressing property for input and output messages.

@javax.jws.WebService public class AddNumbersImpl { @javax.xml.ws.Action( input = "http://example.com/inputAction", output = "http://example.com/outputAction") public int addNumbers(int number1, int number2) { return number1 + number2; } }

The generated WSDL looks like:

<definitions targetNamespace="http://example.com/numbers" ...>

...

<portType name="AddNumbersPortType">
    <operation name="AddNumbers">
        <input message="tns:AddNumbersInput" name="Parameters"
                wsaw:Action="http://example.com/inputAction"/>
        <output message="tns:AddNumbersOutput" name="Result"
                wsaw:Action="http://example.com/outputAction"/>
    </operation>
</portType>

...

Example 22. @javax.xml.ws.Action - Example 2 - Specify explicit value for Action message addressing property for only theinput message.

The default values are used for theoutput message.

@javax.jws.WebService public class AddNumbersImpl { @javax.xml.ws.Action(input = "http://example.com/inputAction") public int addNumbers(int number1, int number2) { return number1 + number2; } }

The generated WSDL looks like:

<definitions targetNamespace="http://example.com/numbers" ...>

...

<portType name="AddNumbersPortType">
    <operation name="AddNumbers">
        <input message="tns:AddNumbersInput" name="Parameters"
                wsaw:Action="http://example.com/inputAction"/>
        <output message="tns:AddNumbersOutput" name="Result"/>
    </operation>
</portType>

...

It is legitimate to specify an explicit value forAction message addressing property foroutput message only. In this case, a default value of wsaw:Action is used for the input message.

Example 23. @javax.xml.ws.Action - Example 3 - @FaultAction

See [@javax.xml.ws.FaultAction](ch03.html#javax-xml-ws-faultaction-outline "10.3.11. @javax.xml.ws.FaultAction") for an example of how to specify an explicit value forAction message addressing property for the fault message.

10.3.11. @javax.xml.ws.FaultAction

The FaultAction annotation is used inside an Action annotation to allow an explicit association of Action message addressing property with the fault messages of the WSDL operation mapped from the exception class.

The fault message in the generated WSDL operation mapped for className class contains explicit wsaw:Action attribute.

Table 19. @javax.xml.ws.FaultAction - Description of Properties

Property Description Default
className Name of the exception class there is no default and is required.
value Value of Action message addressing property for the exception ""
10.3.11.1. Annotation Type Definition

@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface FaultAction {

Class<? extends Exception> className();


String value() default "";

}

10.3.11.2. Examples

Example 24. @javax.xml.ws.FaultAction - Example 1 - Specify explicit values forAction message addressing property for the input, output and fault message if the Java method throws only one service specific exception.

@javax.jws.WebService public class AddNumbersImpl { @javax.xml.ws.Action( input = "http://example.com/inputAction", output = "http://example.com/outputAction", fault = { @javax.xml.ws.FaultAction(className = AddNumbersException.class, value = "http://example.com/faultAction")}) public int addNumbers(int number1, int number2) throws AddNumbersException { return number1 + number2; } }

The generated WSDL looks like:

<definitions targetNamespace="http://example.com/numbers" ...>

...

<portType name="AddNumbersPortType">
    <operation name="AddNumbers">
        <input message="tns:AddNumbersInput" name="Parameters"
                wsaw:Action="http://example.com/inputAction"/>
        <output message="tns:AddNumbersOutput" name="Result"
                wsaw:Action="http://example.com/outputAction"/>
        <fault message="tns:AddNumbersException"
                name="AddNumbersException"
                wsaw:Action="http://example.com/faultAction"/>
    </operation>
</portType>

...

Example 25. @javax.xml.ws.FaultAction - Example 1 - Specify explicit values forAction message addressing property if the Java method throws only one service specific exception, without specifying the values forinput and output messages.

@javax.jws.WebService public class AddNumbersImpl { @javax.xml.ws.Action( fault = {@javax.xml.ws.FaultAction(className = AddNumbersException.class, value = "http://example.com/faultAction")}) public int addNumbers(int number1, int number2) throws AddNumbersException { return number1 + number2; } }

The generated WSDL looks like:

<definitions targetNamespace="http://example.com/numbers" ...>

...

<portType name="AddNumbersPortType">
    <operation name="AddNumbers">
        <input message="tns:AddNumbersInput" name="Parameters"/>
        <output message="tns:AddNumbersOutput" name="Result"/>
        <fault message="tns:addNumbersFault" name="InvalidNumbers"
                wsa:Action="http://example.com/addnumbers/fault"/>
    </operation>
</portType>

...

Example 26. @javax.xml.ws.FaultAction - Example 1 - Specify explicit values forAction message addressing property if the Java method throws more than one service specific exception.

@javax.jws.WebService public class AddNumbersImpl { @javax.xml.ws.Action( fault = {@javax.xml.ws.FaultAction(className = AddNumbersException.class, value = "http://example.com/addFaultAction"),

                @javax.xml.ws.FaultAction(className = 
                        TooBigNumbersException.class,
                        value = "http://example" +
                                ".com/toobigFaultAction")})
public int addNumbers(int number1, int number2) throws AddNumbersException, TooBigNumbersException {
    return number1 + number2;
}

}

The generated WSDL looks like:

<definitions targetNamespace="http://example.com/numbers" ...>

...

<portType name="AddNumbersPortType">
    <operation name="AddNumbers">
        <input message="tns:AddNumbersInput" name="Parameters"/>
        <output message="tns:AddNumbersOutput" name="Result"/>
        <fault message="tns:addNumbersFault" name="AddNumbersException"
                wsa:Action="http://example.com/addnumbers/fault"/>
        <fault message="tns:tooBigNumbersFault"
                name="TooBigNumbersException"
                wsa:Action="http://example.com/toobigFaultAction"/>
    </operation>
</portType>

...

10.4. JSR 222 (JAXB) Annotations

The following JAXB annotations are being documented because JAX-WS generates them when generating wrapper beans and exception beans according to the JAX-WS 2.0 spec. Please refer to sections 3.5.2.1 and 3.6 of the JAX-WS 2.0 specification for more information on these beans. For more information on these and other JAXB annotations please refer to theJAXB 2.0 specification.

10.4.1. @javax.xml.bind.annotation.XmlRootElement

This annotation is used to map a top level class to a global element in the XML schema used by the WSDL of the web service.

Table 20. @javax.xml.bind.annotation.XmlRootElement - Description of Properties

Property Description Default
name Defines the local name of the XML element representing the annotated class ##default – the name is derived from the class
namespace Defines the namespace of the XML element representing the annotated class ##default – the namespace is derived from the package of the class
10.4.1.1. Annotation Type Definition

@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface XmlRootElement {

String namespace() default "##default";


String name() default "##default";

}

10.4.1.2. Examples

Example 27. @javax.xml.bind.annotation.XmlRootElement - Example

@XmlRootElement(name = "addNumbers", namespace = "http://server.fromjava/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "addNumbers", namespace = "http://server.fromjava/", propOrder = {"arg0", "arg1"}) public class AddNumbers {

@XmlElement(name = "arg0", namespace = "")
private int arg0;
@XmlElement(name = "arg1", namespace = "")
private int arg1;

public int getArg0() {
    return this.arg0;
}

public void setArg0(int arg0) {
    this.arg0 = arg0;
}

public int getArg1() {
    return this.arg1;
}

public void setArg1(int arg1) {
    this.arg1 = arg1;
}

}

10.4.2. @javax.xml.bind.annotation.XmlAccessorType

This annotation is used to specify whether fields or properties are serialized by default.

Table 21. @javax.xml.bind.annotation.XmlAccessorType - Description of Properties

Property Description Default
value Specifies whether fields or properties are serialized by default. The value can beXmlAccessType.FIELD orXmlAccessType.PROPERTY orXmlAccessType.PUBLIC_MEMBER orXmlAccessType.NONE XmlAccessType.PROPERTY
10.4.2.1. Annotation Type Definition

@Inherited @Retention(RUNTIME) @Target({PACKAGE, TYPE}) public @interface XmlAccessorType {

XmlAccessType value() default XmlAccessType.PUBLIC_MEMBER;

}

public enum XmlAccessType {

PROPERTY,

FIELD,

PUBLIC_MEMBER,

NONE

}

10.4.2.2. Examples

Example 28. @javax.xml.bind.annotation.XmlAccessorType - Example

@XmlRootElement(name = "addNumbers", namespace = "http://server.fromjava/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "addNumbers", namespace = "http://server.fromjava/", propOrder = {"arg0", "arg1"}) public class AddNumbers {

@XmlElement(name = "arg0", namespace = "")
private int arg0;
@XmlElement(name = "arg1", namespace = "")
private int arg1;

public int getArg0() {
    return this.arg0;
}

public void setArg0(int arg0) {
    this.arg0 = arg0;
}

public int getArg1() {
    return this.arg1;
}

public void setArg1(int arg1) {
    this.arg1 = arg1;
}

}

10.4.3. @javax.xml.bind.annotation.XmlType

This annotation is used to map a value class to an XML Schema type. A value class is a data container for values represented by properties and fields. A schema type is a data container for values represented by schema components within a schema type's content model (e.g. Model groups, attributes etc).

Table 22. @javax.xml.bind.annotation.XmlType - Description of Properties

Property Description Default
name Defines the local name of the XML type representing this class in the XML schema used by the WSDL of the web service "##default"
namespace Defines the namespace of the XML type representing this class in the XML schema used by the WSDL of the web service "##default"
propOrder Defines a list of names of JavaBean properties in the class. Each name in the list is the name of a Java identifier of the JavaBean property. The order in which JavaBean properties are listed is the order of XML Schema elements to which the JavaBean properties are mapped.All of the JavaBean properties being mapped must be listed (i.e. if a JavaBean property mapping is prevented by @XmlTransient then it does not have to be listed). Otherwise, it is an error. By default, the JavaBean properties are ordered using a default order specified in the JAXB 2.0 specification. {""}
10.4.3.1. Annotation Type Definition

@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface XmlType {

String name() default "##default";


String[] propOrder() default {""};


String namespace() default "##default";


Class factoryClass() default DEFAULT.class;


static final class DEFAULT {
}


String factoryMethod() default "";

}

10.4.3.2. Examples

Example 29. @javax.xml.bind.annotation.XmlType - Example

@XmlRootElement(name = "addNumbers", namespace = "http://server.fromjava/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "addNumbers", namespace = "http://server.fromjava/", propOrder = {"arg0", "arg1"}) public class AddNumbers {

@XmlElement(name = "arg0", namespace = "")
private int arg0;
@XmlElement(name = "arg1", namespace = "")
private int arg1;

public int getArg0() {
    return this.arg0;
}

public void setArg0(int arg0) {
    this.arg0 = arg0;
}

public int getArg1() {
    return this.arg1;
}

public void setArg1(int arg1) {
    this.arg1 = arg1;
}

}

10.4.4. @javax.xml.bind.annotation.XmlElement

This annotation is used to map a property contained in a class to a local element in the XML Schema complex type to which the containing class is mapped.

Table 23. @javax.xml.bind.annotation.XmlElement - Description of Properties

Property Description Default
name Defines the local name of the XML element representing the property of a JavaBean "##default" - the element name is derived from the JavaBean property name.
namespace Defines the namespace of the XML element representing the property of a JavaBean "##default" - the namespace of the containing class
nillable Not generated by JAX-WS
type Not generated by JAX-WS
10.4.4.1. Annotation Type Definition

@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) public @interface XmlElement {

String name() default "##default";


boolean nillable() default false;


boolean required() default false;


String namespace() default "##default";


String defaultValue() default "\u0000";


Class type() default DEFAULT.class;


static final class DEFAULT {
}

}

10.4.4.2. Examples

Example 30. @javax.xml.bind.annotation.XmlElement - Example

@XmlRootElement(name = "addNumbers", namespace = "http://server.fromjava/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "addNumbers", namespace = "http://server.fromjava/", propOrder = {"arg0", "arg1"}) public class AddNumbers {

@XmlElement(name = "arg0", namespace = "")
private int arg0;
@XmlElement(name = "arg1", namespace = "")
private int arg1;

public int getArg0() {
    return this.arg0;
}

public void setArg0(int arg0) {
    this.arg0 = arg0;
}

public int getArg1() {
    return this.arg1;
}

public void setArg1(int arg1) {
    this.arg1 = arg1;
}

}

10.4.5. @javax.xml.bind.annotation.XmlSeeAlso

Instructs JAXB to also bind other classes when binding this class.

Table 24. @javax.xml.bind.annotation.XmlSeeAlso - Description of Properties

Property Description Default
value Other classes that JAXB can use when binding this class {}
10.4.5.1. Annotation Type Definition

@Target({ElementType.TYPE}) @Retention(RUNTIME) public @interface XmlSeeAlso { Class[] value(); }

10.5. JSR 250 (Common Annotations) Annotations

The following annotations are being documented because JAX-WS endpoints use them for resource injection, and as lifecycle methods. Please refer to sections 5.2.1 and 5.3 of the JAX-WS 2.0 specification for resource injection, and lifecycle management. For more information on these and other common annotations please refer to the JSR 250: Common Annotations for the Java TM Platform .

10.5.1. @javax.annotation.Resource

This annotation is used to mark a WebServiceContext resource that is needed by a web service. It is applied to a field or a method for JAX-WS endpoints. The container will inject an instance of the WebServiceContext resource into the endpoint implementation when it is initialized.

Table 25. @javax.annotation.Resource - Description of Properties

Property Description Default
type Java type of the resource For field annotations, the default is the type of the field. For method annotations, the default is the type of the JavaBeans property.
10.5.1.1. Annotation Type Definition

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface Resource {

Class type() default java.lang.Object.class;

}

10.5.1.2. Examples

Example 31. @javax.annotation.Resource - Example

@WebService public class HelloImpl { @Resource private WebServiceContext context;

public String echoHello(String name) {
    
}

}

10.5.2. @javax.annotation.PostConstruct

This annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service.

10.5.2.1. Annotation Type Definition

@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PostConstruct { }

10.5.2.2. Examples

Example 32. @javax.annotation.PostConstruct - Example

@WebService public class HelloImpl { @PostConstruct private void init() {

}

public String echoHello(String name) {
    
}

}

10.5.3. @javax.annotation.PreDestroy

The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding.

10.5.3.1. Annotation Type Definition

@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PreDestroy { }

10.5.3.2. Examples

Example 33. @javax.annotation.PreDestroy - Example

@WebService public class HelloImpl { public String echoHello(String name) {

}

@PreDestroy
private void release() {
    
}

}

11. WS-Addressing

11.1. WS-Addressing in JAX-WS RI

Web Services Addressing provides transport-neutral mechanisms to address Web services and messages. JAX-WS 2.2 specification requires support for W3C Core,SOAP Binding and Addressing 1.0 - Metadata specifications and defines standard API to enable/disable W3C WS-Addressing on the client and service endpoint. In addition to that, JAX-WS RI also supports Member Submission version of WS-Addressing. The member submission version is supported in an implementation specific way. For compatility with JAX-WS 2.1 behavior, JAX-WS RI 2.3.0-SNAPSHOT also supports wsdls conforming to WSDL Binding specification. The subsequent sections describe how the two WS-Addressing versions can be enabled/disabled on client and server side .

11.2. Why WS-Addressing?

The subsequent sections explain the different use cases served by WS-Addressing.

11.2.1. Transport Neutrality

This section describes how a message can be sent to a Web service endpoint in transport neutral manner.

Example 34. SOAP 1.2 message, without WS-Addressing, sent over HTTP

POST /fabrikam/Purchasing HTTP 1.1/POST (1) Host: example.com SOAPAction: http://example.com/fabrikam/SubmitPO

<S:Envelope (2) xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wombat="" title="undefined" rel="noopener noreferrer">http://wombat.org/"> <S:Header> wombat:MessageID uuid:e197db59-0982-4c9c-9702-4234d204f7f4 <S:Body> ...

1 HTTP transport headers.
2 SOAP message in HTTP body.

The host (example.com), the dispatch method (POST) and the URL to dispatch to (/fabrikam/Purchasing) are in the HTTP transport headers. The actual message and implied meaning (for example payload's QName orSOAPAction) is defined by the messaging system (SOAP) or transport protocol (HTTP). If the message is to be sent over an alternate transport, such as SMTP, then the information conveyed in HTTP transport headers need to be mapped to SMTP specific headers. On the server side, to dispatch successfully, a Web service stack has to gather the information from the SMTP (as opposed to HTTP) headers and the SOAP message.

Also in the above message, there is no standard header to establish the identity of a message. In this case,MessageID header defined in the namespace URI bound to wombat prefix is used but is application specific and is thus not re-usable.

WS-Addressing introduce Message Addressing Properties that collectively augment a message to normalize this information.

Example 35. SOAP 1.2 message, with WS-Addressing, sent over HTTP

POST /fabrikam/Purchasing HTTP 1.1/POST (1) Host: example.com SOAPAction: http://example.com/fabrikam/SubmitPO

<S:Envelope (2) xmlns:S="http://www.w3.org/2003/05/soap-envelope" **xmlns:wsa="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2005/08/addressing/"**> <S:Header> wsa:MessageID (3) uuid:e197db59-0982-4c9c-9702-4234d204f7f4 wsa:To http://example.com/fabrikam/Purchasing wsa:Action http://example.com/fabrikam/SubmitPO <S:Body> ...

1 HTTP transport headers.
2 SOAP message in HTTP body.
3 Binding of Message Addressing Properties to SOAP 1.2 message.

For example, wsa:MessageID is a binding of an abstract property that defines an absolute URI that uniquely identifies the message,wsa:To is binding of an abstract absolute URI representing the address of the intended receiver of this message and wsa:Action is binding of an abstract absolute IRI that uniquely identifies the semantics implied by this message. All the information earlier shared between transport protocols and messaging systems is now normalized into a uniform format that can be processed independent of transport or application.

If the exactly same message is to be sent/received using a different transport, for example asynchronously over SMTP, then the value of wsa:To header could be changed to mailto:purchasing@example.com. The updated wsa:To header looks like:

wsa:To mailto:purchasing@example.com

On the server side, Web services stack can gather all the information from the SOAP message and then dispatch it correctly.

11.2.2. Stateful Web service

Web services are usually stateless, i.e. the service endpoint receives a request and responds back without saving any processing state in between different requests. However making Web services stateful enables to share multiple instances of service endpoints. For example, consider a stateful Bank Web service. The client (say bank customer) can obtain a bank EPR, with relevant state information stored as reference parameters, and invoke a method on that EPR to do a series of banking operations. On the service endpoint, whenever a request is received, the reference parameters from the EPR are available as first-class SOAP headers allowing the endpoint to restore the state.

JAX-WS RI 2.3.0-SNAPSHOT enables stateful Web services to be annotated withcom.sun.xml.ws.developer.Stateful annotation.

11.2.3. Simple and Complex MEPs

WS-Addressing defines standard Message Addressing Properties (MAPs) to support simple and complex message patterns. The SOAP Binding defines a mapping of these MAPs to SOAP headers and convey end-to-end message characteristics including addressing for source and destination endpoints as well as message identity. For example destination MAP represents an absolute IRI representing the address of the intended receiver of the message and is mapped to a SOAP header with wsa:To element name. reply endpoint represents an endpoint reference for the intended receiver for replies to this message and is mapped to a SOAP header with wsa:ReplyTo element name. In addition, WSDL Binding, also defines requirement on the presence of these MAPs for standard Message Exchange Patterns (MEPs) such as request/response and one-way.

Using these MAPs, complex MEPs can be created. For example:

  1. Asynchronous MEP: Using reply endpoint MAP, an asynchronous transport may be specified for a synchronous request. For example, a client application might send a request over HTTP and ask to receive the response through SMTP.
  2. Conversation MEP: Using relationship MAP, that defines the relationship between two messages, a conversational MEP can be defined by correlating multiple request/response MEPs. For example a client sending a request to service endpoint receives a response withwsa:RelatesTo MAP. The service endpoint may optionally include wsa:MessageID in the response. This MAP can then be included by the client in wsa:RelatesTo MAP in next request to the service endpoint there by starting a conversation.
  3. Distributed MEP: Using reply endpoint and fault endpoint MAP, a different transport/address can be specified for receiving normal and fault responses respectively.

11.2.4. Composability with other WS-* specifications

There are several Web services specification (commonly known as WS-* specs) that make use of the abstract properties defined by WS-Addressing. For example WS-Metadata Exchange define a bootstrap mechanism for retrieving metadata before the business message exchange can take place. This mechanism involve sending a WS-Transfer request for the retrieval of a resource's representation. A typical request message looks like:

<s11:Envelope (1) xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/" **xmlns:wsa="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2005/08/addressing"**> (2) s11:Header wsa:Action (3) http://schemas.xmlsoap.org/ws/2004/09/transfer/Get wsa:Tohttp://example.org/metadata wsa:ReplyTo wsa:Addresshttp://www.w3.org/2005/08/addressing/anonymous wsa:MessageID uuid: 68da6b24-7fa1-4da2-8a06-e615bfa3d2d0 s11:Body/

1 SOAP request message to retrieve metadata about a Web service endpoint.
2 WS-Addressing namespace URI bound to "wsa" prefix.
3 The standard WS-Addressing MAPs used to convey the semantics (wsa:Action), receiver (wsa:To) of the message, intended receiver of reply (wsa:ReplyTo) message and identity (wsa:MessageID) information of the message

This message has an empty SOAP Body and relies completely upon standard MAPs to convey all the information. Similarly, a WS-Metadata Exchange response message with metadata looks like:

<s11:Envelope xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/" **xmlns:wsa="" title="undefined" rel="noopener noreferrer">http://www.w3.org/2005/08/addressing"**> s11:Header wsa:Action (1) http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse wsa:RelatesTo uuid: 68da6b24-7fa1-4da2-8a06-e615bfa3d2d0 s11:Body/ (2) ... s11:Body/

1 The standard WS-Addressing MAPs used to convey the semantics (wsa:Action) of the response message and relationship (wsa:RelatesTo) to the request message.
2 Abbreviated SOAP Body for simplicity which otherwise would contain the MEX response.

WS-Reliable Messaging describes a protocol that allows messages to be delivered reliably between distributed applications in the presence of software component, system or network failures. This specification defines protocol messages that must be exchanged between client and service endpoint, before the business message exchange, in order to deliver the messages reliably. For example, RM Source sends <CreateSequence> request message to RM Destination to create an outbound sequence. The message looks like:

<s11:Envelope xmlns:s11="http://schemas.xmlsoap.org/soap/envelope/" **xmlns:wsa=" http://www.w3.org/2005/08/addressing"** xmlns:wsrm=" " title="undefined" rel="noopener noreferrer">http://schemas.xmlsoap.org/ws/2005/02/rm"> s11:Body (1) wsrm:CreateSequence wsrm:AcksTo wsa:Address http://www.w3.org/2005/08/addressing/anonymous

1 SOAP Body of the request message.

The Body contains an element, wsrm:AcksTo (of the type Endpoint Reference), that specifies the endpoint reference to which<SequenceAcknowledgement> messages and faults related to sequence creation are sent.

WS-Secure Conversation, WS-Trust, WS-Policy and other similar specifications use the constructs defined by WS-Addressing as building blocks.

11.3. WS-Addressing Versions

There are two prominent versions of WS-Addressing that are commonly used:

Sun, IBM, BEA, Microsoft and SAP co-authored and submitted a WS-Addressing specification to W3C in August 2004. W3C chartered a new Working Group with a mission to produce a W3C Recommendation for WS-Addressing by refining the submitted specification. The original specification submitted to W3C is referred as "Member Submission WS-Addressing" or "Submission WS-Addressing". The term Member Submission is defined by W3C.

The WG was chartered to deliver a W3C Recommendation for WS-Addressing Core, SOAP Binding (mapping abstract properties defined in Core to SOAP 1.1 and 1.2) andWSDL Binding (mechanisms to define property values in WSDL 1.1 and WSDL 2.0 service descriptions) specification. This separate between Core/Bindings is common methodology where Core is relevant to application developers and Binding (both SOAP and WSDL) is relevant for Web service stack implementers. This collective set of specifications is referred as "W3C WS-Addressing".

JAX-WS RI supports both versions out-of-the-box. Check below on how to enable either of the versions on a service endpoint starting from Java or starting from WSDL.

11.4. Describing WS-Addressing in WSDL

WS Addressing 1.0- Metadata defines standard ways to describe message addressing properties like Action, Destination in wsdl and also indicate the use of Addressing in wsdl. WS-Addressing Metadata specification replaces the previous Web Services Addressing 1.0 - WSDL Binding specification in candidate recommendation earlier. If you are still using wsdls conforming to WS Addressing 1.0 - WSDL Binding specification, skip to the next section. Still you may want to update your wsdls to use in standard ways defined by the W3C recommended Addressing 1.0 - Metadata specification for better interoperability. Also, There is no standard mechanism to describe Member Submission version support in the WSDL and some implementaions have used WS-Policy to indicate the support of member submission version and JAX-WS RI understands such assertion.

11.4.1. WS-Addressing 1.0 - Metadata

Addressing 1.0 - Metadata specification uses Web Services Policy Framework (WS Policy 1.5) and Web Services Policy - Attachment [ WS Policy 1.5 - Attachment] specifications to express the support of Web Services Addressing 1.0. A new policy assertion<wsam:Addressing> is defined to express the support of Addressing. The wsam:Addressing policy assertion applies to the endpoint policy subject and may be attached to wsdl11:port orwsdl11:binding.

Indicating the requirement of WS-Addressing: When

is present in a Policy alternative, one is required to use WS-Addressing to communicate with the subject.

Indicating the support of WS-Addressing:

<wsam:Addressing wsp:Optional="true">

can be used to indicate support for WS-Addressing but does not require the use of it. In these cases, there are no restrictions about the use of WS-Adressing.

In certain cases, the endpoint can lay some restrictions to indicate the messages it can accept with WS-Addressing. Nested asertions can be used to restrict the use of response endpoint inside the <wsam:Addressing> assertion.

Requiring the use of Non-Anonymous response endpoints:

wsam:Addressing wsp:Policy wsam:NonAnonymousResponses/

can be used to indicate that the subject requires WS-Addressing and requires the use of non-anonymous response EPRs. In this case, the response endpoint in the request messages will have to use something other than the anonymous URI as the value of address. This is typically used when the response needs to be sent to a third entity other than the client and service and the response is sent to the non-anonyous URI through a new connection Requiring the use of Anonymous response endpoints:

wsam:Addressing wsp:Policy wsam:AnonymousResponses/

can be used to indicate that the subject requires WS-Addressing and requires the use of anonymous responses. In this case, the endpoint requires request messages to use response endpoint EPRs that contain the anonymous URI ("http://www.w3.org/2005/08/addressing/anonymous") or None URI ("http://www.w3.org/2005/08/addressing/none") as the value of address.

11.4.2. WS-Addressing WSDL Binding

W3C WS-Addressing WSDL Binding defines an extensibility element, wsaw:UsingAddressing, that can be used to indicate that an endpoint conforms to the WS-Addressing specification. JAX-WS RI generates this extension element in the WSDL if W3C WS-Addressing is enabled on the server-side. On the client side, the RI recognizes this extension element and enforce the rules defined by the W3C specification. This extensibility element may be augmented withwsdl:required attribute to indicate whether WS-Addressing is required (true) or not (false).

W3C WS-Addressing WSDL Binding defineswsaw:Anonymous element which when used in conjunction with wsaw:UsingAddressing define assertions regarding a requirement or a constraint in the use of anonymous URI in EPRs sent to the endpoint. The WSDL Binding defines three distinct values: optional,required and prohibited to express the assertion. The default value ofwsaw:Anonymous (equivalent to not present) isoptional. An operation withrequired wsaw:Anonymous value is shown below:

<wsaw:UsingAddressing wsdl:required="true"/> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <soap:operation soapAction=""/>

...

<wsaw:Anonymous>required</wsaw:Anonymous>

In this case, a message received at the endpoint, for this operation, with a non-anonymous ReplyTo or FaultTo EPR will result in a fault message returned back to the client withwsa:OnlyAnonymousAddressSupported fault code. There is no such equivalent feature in Member Submission WS-Addressing.

11.5. Configuring Addressing on Endpoint

This section describes how W3C and Member Submission WS-Addressing can be enabled/disabled on the server-side.

11.5.1. Starting from WSDL

Starting from WSDL, If the wsdl contains the above described metadata to indicate use addressing at endpoint scope, Addressing is enabled on the server-side. See Describing WS-Addressing in WSDL section for more details.

11.5.2. Starting from Java

This section describes how WS-Addressing can be enabled/disabled if you develop an endpoint starting from a Java SEI.

By default, WS-Addressing is disabled on an endpoint starting from Java. If that is the expected behavior, then nothing else needs to be done. In that case any WS-Addressing headers received at the endpoint are treated like SOAP headers targeted for the appliaction and are ignored.

11.5.2.1. Addressing annotations

If WS-Addressing support needs to be enabled on an endpoint, then along withjavax.jws.WebService annotation,javax.xml.ws.soap.Addressing annotation need to be specified for enabling W3C WS-Addressing. If Member Submission WS-Addressing needs to be enabled then com.sun.xml.ws.developer.MemberSubmissionAddressing annotation needs to be specified on the service endpoint. For example, the service endpoint in fromjava-wsaddressing sample looks like:

@javax.xml.ws.soap.Addressing @javax.jws.WebService public class AddNumbersImpl {

}

To enable, Member Submission WS-Addressing, the SEI definition needs to be changed to:

@com.sun.xml.ws.developer.MemberSubmissionAddressing @javax.jws.WebService public class AddNumbersImpl {

}

Once WS-Addressing support is enabled on a service endpoint, then:

11.5.2.2. Is Addressing Optional or Required ?

Both javax.xml.ws.soap.Addressing andcom.sun.xml.ws.developer.MemberSubmissionAddressing annotations take two optional Boolean parameters,enabled (default true) andrequired (default false). Ifrequired is specified true, then WS-Addressing rules are enforced. Otherwise the inbound message is inspected to find out if WS-A is engaged and then the rules are enforced. See When is WS-Addressing engaged? section for more details on enforcement during runtime.

For example, to enforce Member Submission WS-Addressing rules on the server side, the above code sample will change to:

@com.sun.xml.ws.developer.MemberSubmissionAddressing(enabled = true, required = true) @javax.jws.WebServicepublic class AddNumbersImpl {

}

11.6. On the client side

This section describes how WS-Addressing can be enabled/disabled on the client-side. JAX-WS RI follows the standard extensibility elements in WSDL to enable WS-Addressing support on the client side. In addition, it also allows the client to instruct JAX-WS RI to disable WS-Addressing processing. The assumption is that in this case the client has it's own WS-Addressing processing module. For example, a Dispatch-based client in MESSAGE mode may be used to perform non-anonymous ReplyTo/FaultTo processing.

11.6.1. Implicit behavior

As defined in Describing WS-Addressing in WSDL, If the WSDL contains metadata about the support or requirement of WS-Addressing, JAX-WS RI runtime enables Addressing feature on the client-side.

There is no standard extensibility element for Member Submission WS-Addressing and so there is no implicit behavior defined. It can only be explicitly enabled as described in the next section.

11.6.2. Explicit enabling

If a WSDL does not contain WS-Addressing standard extensibility element, then either W3C WS-Addressing or Member Submission WS-Addressing can be explicitly enabled usingcreateDispatch and getPort methods on javax.xml.ws.Service. The following new APIs are added in JAX-WS 2.1:

Each method is a variation of an already existing method in JAX-WS 2.0. The only addition is an extra var-argjavax.xml.ws.WebServiceFeature parameter. AWebServiceFeature is a new class introduced in JAX-WS 2.1 specification used to represent a feature that can be enabled or disabled for a Web service.

The JAX-WS 2.1 specification definesjavax.xml.ws.soap.AddressingFeature to enable W3C WS-Addressing on the client side. In addition, the JAX-WS RI also definescom.sun.xml.ws.developer.MemberSubmissionAddressingFeature to enable Member Submission WS-Addressing on the client side.

For example in fromjava-wsaddressing example, in order to enable W3C WS-Addressing on a proxy,wsimport is used to generate theAddNumbersImplService class. Then a port can be obtained using the getAddNumbersImplPort method and passing an instance ofjavax.xml.ws.AddressingFeature. The code looks like:

new AddNumbersImplService().getAddNumbersImplPort(new javax.xml.ws.AddressingFeature());

Similarly, a Dispatch instance with Member Submission WS-Addressing can be created as:

new AddNumbersImplService().createDispatch( new QName("http://server.fromjava_wsaddressing/", "AddNumbersImplPort"), SOAPMessage.class, Service.Mode.MESSAGE, new com.sun.xml.ws.developer.MemberSubmissionAddressingFeature());

Feature Parameters

Both javax.xml.ws.soap.AddressingFeature andcom.sun.xml.ws.developer.MemberSubmissionAddressingFeature take two optional Boolean parameters, enabled (default true) and required (default false). If enabled, all WS-Addressing headers are generated for an outbound message. If required is specified true, then WS-Addressing rules are enforced for inbound message. Otherwise the inbound message is inspected to find out if WS-A is engaged and then the rules are enforced.

For example, to enforce Member Submission WS-Addressing rules on the client side, the above code sample will change to:

new AddNumbersImplService().getAddNumbersImplPort(new com.sun.xml .ws.developer.MemberSubmissionAddressingFeature(true, true));

11.6.3. Explicit disabling

A client may like to instruct JAX-WS RI to disable WS-Addressing processing. The assumption is that in this case the client has it's own WS-Addressing processing module. For example, a Dispatch-based client in MESSAGE mode may be used to perform non-anonymous ReplyTo/FaultTo processing.

WS-Addressing processing can be explicitly disabled using one of new methods added to JAX-WS 2.1 specification as defined in Section 3.2. For example, W3C WS-Addressing processing can be disabled using the following code:

new AddNumbersImplService().getAddNumbersImplPort(new javax.xml.ws.AddressingFeature(false));

11.7. When is WS-Addressing engaged?

W3C WS-Addressing SOAP Binding defines that if a receiver processes a message containing awsa:Action header, then SOAP Binding is engaged, and the rules of the specification are enforced. In JAX-WS RI, if WS-Addressing is explicitly disabled then the RI does not follow the rules of engagement. However if WS-Addressing is either implicitly or explicitly enabled then JAX-WS RI engages WS-Addressing based upon the presence of wsa:Action header. JAX-WS RI follows same rule for Member Submission version as well.

In effect, if an endpoint advertises WS-Addressing is required in the WSDL and a client does not send any WS-Addressing header then no WS-Addressing fault is returned back to the client. However if the client send wsa:Action header then the endpoint will enforce all the rules of the specification. For example, if thewsa:MessageID header is missing for a request/response MEP then a fault with appropriate code and sub-code is thrown back to the client.

11.8. Associating Action with an operation

11.8.1. Implicit Action

In most common cases, an implicit Action association, as defined by W3C WS-Addressing 1.0 - Metadata and Member Submission, will be sufficient. For such cases, only using the correct annotation to enable Addressing is required. The client looking at such a WSDL will send the implicitwsa:Action header. If only Addressing is enabled by using the appropriate annotation at the SEI,

11.8.2. Explicit Action

This section describes how an explicit Action Message Addressing Property can be associated with an operation in the SEI.

W3C WS-Addressing W3C WS-Addressing 1.0 - Metadata and Member Submission WS-Addressing define mechanisms to associate Action Message Addressing Property with an operation. JAX-WS 2.1 defines javax.xml.ws.Action andjavax.xml.ws.FaultAction annotations to explicitly associate an Action with input,output, and fault messages of the mapped WSDL operation. For example, one of the methods in the fromjava-wsaddressing sample looks like:

@Action(input = "http://example.com/input3", output = "http://example.com/output3", fault = {@FaultAction(className = AddNumbersException.class, value = "http://example.com/fault3")}) public int addNumbers3(int number1, int number2) throws AddNumbersException {

}

The generated WSDL fragment looks like:

where wsam is bound to W3C WS-Addressing 1.0 - Metadata namespace or Member Submission namespace depending upon the annotation used to enable Addressing.

12. Stateful Webservice

12.1. Introduction

JAX-WS RI has a vendor extension that allows developers to bring back object state to the web service world. Normally, JAX-WS RI only creates one instance of a service class, and have it serve all incoming requests concurrently. This makes it essentially impossible to use instance fields of the service class for any meaningful purpose.

Because of this, people end up coding like C, in anti-OO fashion. Either that or you end up with writing boiler-plate code to dispatch a request to the right instance of your real domain object.

The stateful web service support in JAX-WS RI resolves this problem by having JAX-WS RI maintain multiple instances of a service. By using WS-Addressing behind the scene, it provides a standard-based on-the-wire protocol and easy-to-use programming model.

12.2. Usage

Application service implementation classes (or providers) who'd like to use the stateful web service support must declare@Stateful annotation on a class. It should also have apublic static method/field that takesStatefulWebServiceManager.

@Stateful @WebService @Addressing class BankAccount {

protected final int id;
private int balance;

BankAccount(int id) {
    this.id = id;
}

@WebMethod
public synchronized void deposit(int amount) {
    balance += amount;
}


public static StatefulWebServiceManager<BankAccount> manager;


public static void setManager(StatefulWebServiceManager<BankAccount> 
                                      manager) {
    
}

}

After your service is deployed but before you receive a first request, the resource injection occurs on the field or the method.

A stateful web service class does not need to have a default constructor. In fact, most of the time you want to define a constructor that takes some arguments, so that each instance carries certain state (as illustrated in the above example).

Each instance of a stateful web service class is identified by an unique EndpointReference. Your application creates an instance of a class, then you'll have JAX-WS RI assign this unique EPR for the instance as follows:

@WebService class Bank {

@WebMethod
public synchronized W3CEndpointReference login(int accountId, 
                                               int pin) {
    if (!checkPin(pin))
        throw new AuthenticationFailedException("invalid pin");
    BankAccount acc = new BankAccount(accountId);
    return BankAccount.manager.export(acc);
}

}

Typically you then pass this EPR to remote systems. When they send messages to this EPR, JAX-WS RI makes sure that the particular exported instance associated with that EPR will receive a service invocation.

12.3. Things To Consider

When you no longer need to tie an instance to the EPR, useunexport(Object) so that the object can be GC-ed (or else you'll leak memory). You may choose to do so explicitly, or you can rely on the time out by using setTimeout(long, Callback).

StatefulWebServiceManager is thread-safe. It can be safely invoked from multiple threads concurrently.

13. Catalog

13.1. Catalog Support

Often times, such as for performance reason or your application specific needs, you have a need where you want to resolve the WSDL/Schema documents resolved from the copy of it you have either bundled with your client or server or just to resolve it not from where a WSDL/schema imports points to but rather from where you want it to be picked up.

13.1.1. A Sample catalog file

Example 36. jax-ws-catalog.xml

...

< system systemId=" http://foo.org/hello?wsdl" uri="HelloService.wsdl"/>
13.1.1.1. Location of the catalog file

For details on XML catalog see here.

14. WAR File Packaging

14.1. The WAR Contents

Typically, one creates the WAR file with a GUI development tool or with the ant war task from the generated artifacts from wsimport,wsgen, or annotationProcessing tools.

For example, a sample WAR file starting from a WSDL file:

Table 26. Files contained in WAR when starting from WSDL

File Description
WEB-INF/classes/hello/HelloIF.class SEI
WEB-INF/classes/hello/HelloImpl.class Endpoint
WEB-INF/sun-jaxws.xml JAX-WS RI deployment descriptor
WEB-INF/web.xml Web deployment descriptor
WEB-INF/wsdl/HelloService.wsdl WSDL
WEB-INF/wsdl/schema.xsd WSDL imports this Schema

14.2. The sun-jaxws.xml File

The <endpoints> element contain one or more <endpoint> elements. Each endpoint represents a port in the WSDL and it contains all information aboutimplementation class, servleturl-pattern, binding,WSDL, service,port QNames. The following shows asun-jaxws.xml file for a simpleHelloWorld service.sun-jaxws.xml is the schema instance of <sun-jaxws.xsd>.

Endpoint can have the following attributes:

Table 27. sun-jaxws.xml - Endpoint element attributes.

Attribute Optional Use
name N Name of the endpoint
wsdl Y Primary wsdl file location in the WAR file. For e.g.WEB-INF/wsdl/HelloService.wsdl. If this isn't specified, JAX-WS will create and publish a new WSDL. When the service is developed from Java, it is recommended to omit this attribute.
service Y QName of WSDL service. For e.g.{http://example.org/}HelloService. When the service is developed from Java, it is recommended to omit this attribute.
port Y QName of WSDL port. For e.g.{http://example.org/}HelloPort. When the service is developed from Java, it is recommended to omit this attribute.
implementation N Endpoint implementation class name. For e.g: hello.HelloImpl. The class should have a @WebService annotation. Provider based implementation class should have a @WebServiceProvider annotation.
url-pattern N Should match inweb.xml
binding Y Binding id defined in the JAX-WS API. The possible values are:"http://schemas.xmlsoap.org/wsdl/soap/http""http://www.w3.org/2003/05/soap/bindings/HTTP/"If omitted, it is consideredSOAP1.1 binding.
enable-mtom Y Enables MTOM optimization.true or false. Default is false.

Endpoint can have a optional handler-chain element:

<endpoints ...> <endpoint ...> somename MyHandler hello.MyHandler

14.3. The web.xml File

The following shows a web.xml file for a simple HelloWorld service. It specifies JAX-WS RI specific listener, servlet classes. These classes arecom.sun.ws.transport.http.servlet.WSServletContextListener, and com.sun.xml.ws.transport.http.servlet.WSServlet is servlet

com.sun.xml.ws.transport.http.servlet.WSServletContextListener hello com.sun.xml.ws.transport.http.servlet.WSServlet 1 hello /hello 60

Remember these requirements when building a WAR:

16. Endpoint API

Web Service endpoints can be created and published programmatically using javax.xml.ws.Endpoint API. An endpoint consists of a Web Service Implementation object and some configuration information. The implementation hosts the web service endpoint using a light weight http server and clients can access the web service as if the endpoint is deployed in a J2EE container. This means that there is no need to have any J2EE servlet or EJB container to host the endpoint. TheEndpoint API provides a way to configure the endpoint with the necessary binding, metadata (WSDL and schema documents), handlers etc.

16.1. Endpoint

An endpoint can be created using any of the following constructors:

Endpoint.create(implementor)

Endpoint.create(bindingId,implementor)

Endpoint.publish(address, implementor)

Once the Endpoint object is created using the first two constructors, it can be published usingEndpoint.publish(). Any publishedEndpoint can be stopped usingEndpoint.stop(). samples/supplychain/src/supplychain/server/WarehouseLightWeight.java supplychain sample shows creating and publishing anEndpoint.

16.2. Endpoint andProperties

An endpoint can be configured to match service name and port name of WSDL using properties. This overwrites implementor object's serviceName, portName from @WebService annotation. The port address for an endpoint is patched only if the corresponding port's service name, and port name in WSDL are matched.

Example 37. Endpoint andProperties Example

Endpoint endpoint = ...

Map<String, Object> map = new HashMap<String, Object>(); map.put(Endpoint.WSDL_SERVICE, new QName(...)); map.put(Endpoint.WSDL_PORT, new QName(...));

endpoint.setProperties(map);

16.3. Endpoint andBinding

An endpoint can be configured for different bindings using binding ids. These binding ids are defined in JAX-WS API and endpoint can be configured by specifying @BindingType annotation or using binding id in the Endpoint() constructors. The parameter in constructor overwrites binding defined by @BindingType annotation. If the binding is not specified using @BindingType or using a parameter in Endpoint() constructor, the default binding isSOAP1.1/HTTP. Binding object is used to configure MTOM, handler chain etc. SOAP binding object is used to configure SOAP binding specifics like roles.

For example:

Example 38. Endpoint and Binding Example

The following configures the endpoint forXML/HTTP binding.

Endpoint endpoint = Endpoint.create(HTTPBinding.HTTP_BINDING, implementor);

Working with a Binding object:

SOAPBinding binding = (SOAPBinding) endpoint.getBinding(); binding.setMTOMEnabled(true);

binding.setRoles(...);

binding.setHandlerChain(...);

16.4. Endpoint andmetadata

When the service endpoint is created using existing java classes, the implementation dynamically generates and publishes WSDL and schema documents. But when the service endpoint is created using existing WSDL documents, the same WSDL documents can be used for publishing using metadata facility. When a Source object is created, set systemId always and make sure the imports are resolvable w.r.tsystemIds.

Example 39. Endpoint and metadata Example

List metadataFile =... List metadata = new ArrayList(); for (File file : metadataFile) { Source source = new StreamSource(new FileInputStream(file)); source.setSystemId(file.toURL().toExternalForm()); metadata.add(source); } endpoint.setMetadata(metadata);

17. Modular Databinding

17.1. Introduction

The JAX-WS reference implementation (RI) used to be dependent on the JAXB RI for databinding. JAXB and JAX-WS implementations have been decoupled, and databinding is now modular. The Eclipselink JAXB implementation, plus EclipseLink extensions, is called MOXy. The org.eclipse.persistence.moxy.jar file is bundled with GlassFish Server, which supports the JAXB RI and MOXy as databinding providers. For standalone distributions, databinding plugins can be found inlib/plugins folder in the distribution. The MOXy implementation (library) is not bundled with JAX-WS. It's expected from user to provide MOXy jars to classpath whenever MOXy databinding is required. EclipseLink JAXB compiler is not included as well, but can be used with GlassFish Server. Download the EclipseLink zip file athttp://www.eclipse.org/eclipselink/downloads/ and unzip it.

17.2. Configure databinding for JVM

To specify the databinding provider for the JVM, set the com.sun.xml.ws.spi.db.BindingContextFactory JVM property to one of the following values:

For example:

asadmin create-jvm-options -Dcom.sun.xml.ws.spi.db.BindingContextFactory=com.sun.xml.ws.db.toplink.JAXBContextFactory

17.3. Configure databinding for an endpoint

To specify the databinding provider for a web service endpoint:

It's one of goals of JAX-WS RI to make development of web services as simple as possible, so using of java annotations perfectly makes sense. However there are usecases where it is impossible to use them. For example if we need to expose existing component as a web service, but we have no source code, just binaries. In such scenarios we need not to rely on annotations and JAX-WS RI framework needs a different way how to obtain necessary metadata. The solution is to provide metadata in xml files and to configure JAX-WS RI framework in a way it's aware of them.

18.1. Configuration files

To specify classes' metadata externally, each java class requires separate file. The way how JAX-WS RI framework handles this metadata depends on attributes of xml root element java-wsdl-mapping:

Example 40. webservices.war/WEB-INF/classes/external-metadata.xml

<web-service name="" target-namespace="mynamespace"/>

18.2. XSD Schema

As you probably noticed in an example above, there is a new schema for configuration files:http://xmlns.oracle.com/webservices/jaxws-databinding. The schema is designed to reflect Web Service Metadata (JSR-181) and JAX-WS Annotations (JSR-224) so structure should be really intuitive to developers - see following table:

Table 28. Mapping java @Annotation-s to xml elements examples

@Annotation corresponding xml element
javax.jws.WebService(name="AddNumbers", portName="AddNumbersPort")
javax.xml.ws.WebServiceProvider( targetNamespace="urn:test", serviceName="Endpoint", portName="EndpointPort")
javax.xml.ws.ServiceMode(Service.Mode.MESSAGE)

18.3. Passing Configuration Files to JAX-WS RI

There are different stages where we need to pass the collection of files to JAX-WS RI framework:

For more complete example see samples.