@WebService public class QuoteBean implements StockQuote { public float getQuote(String sym) { ... } }
@WebService
annotation tells the server
runtime to expose all public methods on that bean as a Web service.
Additional levels of granularity can be controlled by adding
additional annotations on individual methods or parameters. Using
annotations makes it much easier to expose Java artifacts as Web
services. In addition, as artifacts are created from using some of
the top-down mapping tools starting from a WSDL file, annotations
are included within the source and Java classes as a way of
capturing the metadata along with the source files.@WebService public interface CreditRatingService { // sync operation Score getCreditScore(Customer customer); // async operation with polling Response<Score> getCreditScoreAsync(Customer customer); // async operation with callback Future<?> getCreditScoreAsync(Customer customer, AsyncHandler<Score> handler); }
CreditRatingService svc = ...; Future<?> invocation = svc.getCreditScoreAsync(customerFred, new AsyncHandler<Score>() { public void handleResponse ( Response<Score> response) { Score score = response.get(); // do work here... } } );
CreditRatingService svc = ...; Response<Score> response = svc.getCreditScoreAsync(customerFred); while (!response.isDone()) { // do something while we wait } // no cast needed, thanks to generics Score score = response.get();
@Resource
annotation for resource injection. The @Resource
annotation is defined by the JSR-250, Common Annotations
specification that is included in Java Platform, Enterprise
Edition 5 (Java EE 5). By placing the @Resource
annotation on a service endpoint implementation, you can
request a resource injection and collect the
javax.xml.ws.WebServiceContext
interface related
to that particular endpoint invocation. When the endpoint
sees the @Resource
annotation, the endpoint adds
the annotated variable with an appropriate value before the
servlet is placed into service. From the
WebServiceContext
interface, you can collect the
MessageContext
for the request associated with
the particular method call using the
getMessageContext()
method.@Resource
annotation for resource injection:
@WebService public class MyService { @Resource private WebServiceContext ctx; public String echo (String input) { … } }
javax.xml.ws.Dispatch
). The dispatch client is an
XML messaging oriented client. The data is sent in either
PAYLOAD
or MESSAGE
mode. When using
the PAYLOAD
mode, the dispatch client is only
responsible for providing the contents of the <soap:Body>
and JAX-WS adds the <soap:Envelope> and
<soap:Header> elements. When using the
MESSAGE
mode, the dispatch client is responsible
for providing the entire SOAP envelope including the
<soap:Envelope>, <soap:Header>, and
<soap:Body> elements and JAX-WS does not add anything
additional to the message. The dispatch client supports
asynchronous invocations using a callback or polling
mechanism.SOAPMessage
object across the interface. JAX-WS
leverages the JAXB 2.0 support as the data binding technology
of choice between Java and XML.@WebService
annotation to the bean defines the application as a Web
service and how a client can access the Web service.
JavaBeans can have a service endpoint interface, but it is
not required. Enabling JavaBeans for Web services includes
annotating the bean and the optional service endpoint
interface, assembling all artifacts required for the Web
service, and deploying the application into Axis2. You are
not required to develop a WSDL file because the use of
annotations can provide all of the WSDL information necessary
to configure the service endpoint or the client. It is,
however, a best practice to develop a WSDL file.Provider
interface to enable services to
work at the XML message level. By using annotations on
the service endpoint or client, you can define the
service endpoint as a Web service.javax.jws.WebService
annotation for JavaBeans endpoints or the
javax.jws.WebServiceProvider
annotation for
a Provider endpoint. These annotations define the Java
class as a Web service endpoint. For a JavaBeans
endpoint, the service endpoint interface or service
endpoint implementation is a Java interface or class,
respectively, that declares the business methods provided
by a particular Web service. The only methods on a
JavaBeans endpoint that can be invoked by a Web services
client are the business methods that are defined in the
explicit or implicit service endpoint interface.@WebService (javax.jws.WebService)
annotation included on the bean class. If the service
implementation bean also uses an SEI, then that endpoint
interface must be referenced by the endpointInterface
attribute on that annotation. If the service
implementation bean does not use an SEI, then the service
is described by the implicit SEI defined in the
bean.javax.xml.ws.Provider
, as an
alternative to service endpoint interfaces. The
Provider
interface supports a more messaging
oriented approach to Web services. With the
Provider
interface, you can create a Java
class that implements a simple interface to produce a
generic service implementation class. The
Provider
interface has one method, the
invoke method, which uses generics to control both the
input and output types when working with various messages
or message payloads. All Provider endpoints must be
annotated with the @WebServiceProvider
(javax.xml.ws.WebServiceProvider)
annotation. A
service implementation cannot specify the
@WebService
annotation if it implements the
javax.xml.ws.Provider
interface.javax.jws.WebService
or javax.xml.ws.WebServiceProvider
annotation. Both annotations must not be present on a
Java class. The
javax.xml.ws.WebServiceProvider
annotation is only supported on classes that
implement the javax.xml.ws.Provider
interface.
javax.jws.WebService
annotation. You
can add the @WebMethod
annotation to
methods of a service endpoint interface to
customize the Java-to-WSDL mappings. All public
methods are considered as exposed methods
regardless of whether the @WebMethod
annotation is specified or not. It is incorrect to
have an @WebMethod
annotation on an
service endpoint interface that contains the
exclude
attribute.javax.jws.WebService
annotation will
use the default values for the
serviceName
, portName
,
and targetNamespace
parameters. To
override these default values, specify values for
these parameters in the @WebService
annotation. If the @WebMethod
annotation is not specified, all public methods are
exposed including the inherited methods with the
exception of methods inherited from
java.lang.Object
. The
exclude
parameter of the
@WebMethod
annotation can be used to
control which methods are exposed.Provider
interface, use the
javax.xml.ws.WebServiceProvider
annotation on the Provider endpoint.@ResponseWrapper
annotation for a wrapped
method.-wsdl
argument is specified. The wsgen command does not
automatically generate the WSDL file. The WSDL file is
automatically generated when you deploy the service
endpoint.LITERAL
are supported while the
value, ENCODED
, is not supported. For WSDL
documents that implement a Document/Literal wrapped
pattern, a root element is declared in the XML schema and
is used as an operation wrapper for a message flow.
Separate wrapper element definitions exist for both the
request and the response.@WebService
annotation
to the desired superclass or you can override the
inherited method in the implementation class with a call
to the superclass method. Implementation classes only
expose methods from superclasses that are annotated with
the @WebService
annotation.XMLType
annotations that have the same @XMLType
name
defined within different Java packages. When this
scenario occurs, the following error is produced:
Error: Two classes have the same XML type name .... Use @XmlType.name and @XmlType.namespace to assign different names to them...
@XMLType.name
values that have the same name, but
exist within different Java packages. To prevent this error, add
the @XML.Type.namespace
class to the existing
@XMLType
annotation to differentiate between the
XML types.
wsdl:fault
class (if any)wsimport -keep -verbose wsdl_URL
-keep
option tells the tool not to delete the
generated files, and the -verbose
option tells it to
list the files that were created. The ObjectFactory.java file that
is created contains factory methods for each Java content interface
and Java element interface generated in the associated package. The
package-info.java file takes the targetNamespace
value
and creates the directory structure.servicejars
directory. The
JAXWSDeployer
will examine all jars within
that directory and deploy those classes that have JAX-WS
annotations which identify them as Web services.javax.xml.ws.Dispatch
, is a
dynamic JAX-WS client programming interface. To write a
Dispatch client, you must have expertise with the Dispatch
client APIs, the supported object types, and knowledge of the
message representations for the associated WSDL file. The
Dispatch client can send data in either MESSAGE
or PAYLOAD
mode. When using the
javax.xml.ws.Service.Mode.MESSAGE
mode, the
Dispatch client is responsible for providing the entire SOAP
envelope including the <soap:Envelope>
,
<soap:Header>
, and
<soap:Body>
elements. When using the
javax.xml.ws.Service.Mode.PAYLOAD
mode, the
Dispatch client is only responsible for providing the
contents of the <soap:Body>
and JAX-WS
includes the payload in a <soap:Envelope>
element.javax.xml.transform.Source
: Use
Source
objects to enable clients to use XML
APIs directly. You can use Source
objects with
SOAP or HTTP bindings.javax.xml.soap.SOAPMessage
: Use
SOAPMessage
objects so that clients can work
with SOAP messages. You can only use
SOAPMessage
objects with SOAP bindings.javax.activation.DataSource
: Use
DataSource
objects so that clients can work
with Multipurpose Internet Mail Extension (MIME) messages.
Use DataSource
only with HTTP bindings.Dispatch<Source> dispatch = … create a Dispatch<Source> Source request = … create a Source object Source response = dispatch.invoke(request);
invoke()
method.invoke
methodinvokeAsync
method with a callback
or polling objectinvokeOneWay
methodsjava.lang.reflect.Proxy
class and leverage the
Dynamic Proxy function in the base Java Runtime Environment
Version 5. The client application can then provide an
interface that is used to create the proxy instance while the
runtime is responsible for dynamically creating a Java object
that represents the SEI.invoke
methodinvokeAsync
method with a callback
or polling objectinvokeOneWay
methodsenableAsyncMapping
binding
declaration to the wsdl:definitions
element or
in an external binding file that is defined in the WSDL
file. Use the enableMIMEContent
binding
declaration in your custom client or server binding file to
enable or disable the default mime:content
mapping rules. For additional information on custom binding
declarations, see chapter 8 the JAX-WS specification.-wsdllocation
annotation
attribute. For example, if your MyService.wsdl file is
located in the META-INF/wsdl/ directory, then run the
wsimport tool and use the -wsdllocation
option
to specify the value to be used for the location of the
WSDL file.wsimport -keep
-wsdllocation=META-INF/wsdl/MyService.wsdl
javax.xml.ws.Dispatch
, is an XML messaging
oriented client that is intended for advanced XML developers
who prefer to work at the XML level using XML constructs. To
write a Dispatch client, you must have expertise with the
Dispatch client APIs, the supported object types, and
knowledge of the message representations for the associated
WSDL file.PAYLOAD
or MESSAGE
mode. When using the
PAYLOAD
mode, the Dispatch client is only
responsible for providing the contents of the
<soap:Body>
and JAX-WS includes the input
payload in a <soap:Envelope>
element. When
using the MESSAGE
mode, the Dispatch client is
responsible for providing the entire SOAP envelope.Source
objects, Java Architecture for XML Binding (JAXB) objects, or
data source objects. The Dispatch client supports the
following types of objects:javax.xml.transform.Source
: Use
Source
objects to enable clients to use XML
APIs directly. You can use Source
objects with
SOAP and HTTP bindings.javax.xml.soap.SOAPMessage
: Use
SOAPMessage
objects so that clients can work
with SOAP messages. You can only use
SOAPMessage
objects with SOAP version 1.1 or
SOAP version 1.2 bindings.javax.activation.DataSource
: Use
DataSource
objects so that clients can work
with Multipurpose Internet Mail Extension (MIME) messages.
Use DataSource
only with HTTP bindings.PAYLOAD
or MESSAGE
mode.Dispatch<T>
object using
either the Service.Mode.PAYLOAD
method or the
Service.Mode.MESSAGE
method.javax.xml.ws.BindingProvider
interface. Use
the request context to specify additional properties such
as enabling HTTP authentication or specifying the endpoint
address.String endpointUrl = ...; QName serviceName = new QName("http://org/apache/ws/axis2/sample/echo/", "EchoService"); QName portName = new QName("http://org/apache/ws/axis2/sample/echo/", "EchoServicePort"); /** Create a service and add at least one port to it. **/ Service service = Service.create(serviceName); service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl); /** Create a Dispatch instance from a service.**/ Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE); /** Create SOAPMessage request. **/ // compose a request message MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); // Create a message. This example works with the SOAPPART. SOAPMessage request = mf.createMessage(); SOAPPart part = request.getSOAPPart(); // Obtain the SOAPEnvelope and header and body elements. SOAPEnvelope env = part.getEnvelope(); SOAPHeader header = env.getHeader(); SOAPBody body = env.getBody(); // Construct the message payload. SOAPElement operation = body.addChildElement("invoke", "ns1", "http://org/apache/ws/axis2/sample/echo/"); SOAPElement value = operation.addChildElement("arg0"); value.addTextNode("ping"); request.saveChanges(); /** Invoke the service endpoint. **/ SOAPMessage response = dispatch.invoke(request); /** Process the response. **/
axis2
shell scripts in
the bin
directory of the installed runtime.
handleResponse()
method of the handler is called
when the result is available. Both the polling and callback
models enable the client to focus on continuing to process
work without waiting for a response to return, while
providing for a more dynamic and efficient model to invoke
Web services.
AsynchHandler
callback handler to accept and process the inbound response
object. The client callback handler implements the
javax.xml.ws.AsynchHandler
interface, which
contains the application code that is executed when an
asynchronous response is received from the server. The
javax.xml.ws.AsynchHandler
interface contains
the handleResponse(java.xml.ws.Response)
method
that is called after the run time has received and processed
the asynchronous response from the server. The response is
delivered to the callback handler in the form of a
javax.xml.ws.Response
object. The response
object returns the response content when the
get()
method is called. Additionally, if an
error was received, then an exception is returned to the
client during that call. The response method is then invoked
according to the threading model used by the executor method,
java.util.concurrent.Executor
on the client's
java.xml.ws.Service
instance that was used to
create the Dynamic Proxy or Dispatch client instance. The
executor is used to invoke any asynchronous callbacks
registered by the application. Use the
setExecutor
and getExecutor
methods
to modify and retrieve the executor configured for your
service.
get()
method is called. The client receives an object of type
javax.xml.ws.Response
from the
invokeAsync
method. That Response
object is used to monitor the status of the request to the
server, determine when the operation has completed, and to
retrieve the response results.
Response.cancel()
method on
the object returned from a polling invocation or a
Future.cancel()
method on the object returned
from a callback invocation. The cancel response does not
affect the server when processing a request.org.apache.axis2.jaxws.use.async.mep
Map<String, Object> rc = ((BindingProvider) port).getRequestContext(); rc.put("org.apache.axis2.jaxws.use.async.mep", Boolean.TRUE);
javax.xml.ws.Dispatch
interface. For an
SEI, the method name ends in Async
and has
one more parameter than the synchronous method of type
javax.xml.ws.AsyncHandler
. The
invokeAsync(Object, AsyncHandler)
method
is the one that is used on the Dispatch interface.service.setExecutor
methods to the client application. Adding the executor
methods gives the client control of the scheduling
methods for processing the response. You can also
choose to use the java.current.Executors
class factory to obtain packaged executors or implement
your own executor class. See the JAX-WS specification
for more information on using executor class methods
with your client.javax.xml.ws.AsynchHandler
interface. The
javax.xml.ws.AsynchHandler
interface only
has the
handleResponse(javax.xml.ws.Response)
method. The method must contain the logic for
processing the response or possibly an exception. The
method is called after the client run time has received
and processed the asynchronous response from the
server.handleResponse(Response)
method is
invoked on the callback object when the response is
available. The Response.get()
method is
called within this method to deliver the response.javax.xml.ws.Dispatch
interface. For an
SEI, the method name ends in Async
and has
a return type of javax.xml.ws.Response
.
The invokeAsync(Object)
method is used on
the Dispatch interface.javax.xml.ws.Response
, that is used to
monitor the status of the request to the server. The
isDone()
method indicates whether the
invocation has completed. When the
isDone()
method returns a value of true,
call the get()
method to retrieve the
response object.cancel()
method for the callback
or polling method if the client needs to stop waiting for a
response from the service. If the cancel()
method is invoked by the client, the endpoint continues to
process the request. However, the wait and response
processing for the client is stopped.jaxws:enableAsyncMapping
binding declaration
to the WSDL file. For more information on adding binding
customizations to generate an asynchronous interface, see
chapter 8 of the JAX-WS specification.enableAsyncMapping
binding declaration, ensure
that the corresponding response message your WSDL file does
not contain parts. When a response message does not contain
parts, the request acts as a two-way request, but the actual
response that is sent back is empty. The wsimport tool
does not correctly handle a void response. To avoid this
scenario, you can remove the output message from the
operation which makes your operation a one-way operation or
you can add a <wsdl:part> to your message. For more
information on the usage, syntax and parameters for the
wsimport tool, see the wsimport command for
JAX-WS applications documentation.@WebService public interface CreditRatingService { // Synchronous operation. Score getCreditScore(Customer customer); // Asynchronous operation with polling. Response<Score> getCreditScoreAsync(Customer customer); // Asynchronous operation with callback. Future<?> getQuoteAsync(Customer customer, AsyncHandler<Score> handler); }
Future<?>
method represents the result of an
asynchronous computation and is checked to see if the computation
is complete. When you want the application to find out if the
request is completed, invoke the Future.isDone()
method. Note that the Future.get()
method does not
provide a meaningful response and is not similar to the
Response.get()
method.
CreditRatingService svc = ...; Future<?> invocation = svc.getCreditScoreAsync(customerTom, new AsyncHandler<Score>() { public void handleResponse ( Response<Score> response) { score = response.get(); // process the request... } } );
CreditRatingService svc = ...; Response<Score> response = svc.getCreditScoreAsync(customerTom); while (!response.isDone()) { // Do something while we wait. } score = response.get();
javax.xml.ws.handler.LogicalHandler
interface. A
logical handler receives a LogicalMessageContext
object from which the handler can get the message
information. Logical handlers can exist on both SOAP and
XML/HTTP-based configurations.javax.xml.ws.handler.soap.SOAPHandler
interface.
Protocol handlers receive the message as a
javax.xml.soap.SOAPMessage
to read the message
data.handleMessage(MessageContext)
method or
handleFault(MessageContext)
method for a
specific handler is invoked. You must configure the handlers
for the server or client, and implement sufficient logic
within these methods to detect the inbound or outbound
direction of the current message.@HandlerChain
annotation to the
service endpoint interface or the generated service class and
provide the handler chain configuration file. The
@HandlerChain
annotation contains a file
attribute that points to a handler chain configuration file
that you create. For Web services client applications, you
can also configure the handler chain programmatically using
the Binding API. To modify the handlerchain
class programmatically, use either the default implementation
or a custom implementation of the
HandlerResolver
method.@HandlerChain
annotation on either the
service endpoint interface or the endpoint implementation
class, and provide the associated handler chain configuration
file. Handlers for the server are only configured by setting
the @HandlerChain
annotation on the service
endpoint implementation or the implementation class. The
handler classes must be included in the deployed
artifact.@HandlerChain
annotation, you must specify
the location of the handler configuration as either a
relative path from the annotated file or as an absolute URL.
For example:@HandlerChain(file="../../common/handlers/myhandlers.xml")
@HandlerChain(file="http://foo.com/myhandlers.xml")
@HandlerChain
annotation and the default
implementation of HandlerResolver
class to
build the handler chain. You can obtain the existing
handler chain from the Binding
, add or
remove handlers, and then return the modified handler
chain to the Binding
object.HandlerResolver
class on the Service
instance. The runtime
uses your custom implementation of the
HandlerResolver
class to build the handler
chain, and the default runtime implementation is not
used. In this scenario, the @HandlerChain
annotation is not read when retrieving the handler
chain from the binding after the custom
HandlerResolver
instance is registered on
the Service
instance. You can obtain the
existing handler chain from the Binding
,
add or remove handlers, and then return the modified
handler chain to the Binding
object.@HandlerChain
annotation on the service
instance or service endpoint interface, or you can modify
the handler chain programmatically to control how the
handler chain is built in the runtime. If you choose to
modify the handler chain programmatically, then you must
determine if you will use the default handler resolver or
use a custom implementation of a handler resolver that is
registered on the service instance. A service instance uses
a handler resolver when creating binding providers. When
the binding providers are created, the handler resolver
that is registered with a service is used to create a
handler chain and the handler chain is subsequently used to
configure the binding provider.@HandlerChain
annotation on the service
endpoint interface or implementation class. When the
@HandlerChain
annotation is configured on both
the service endpoint interface and the implementation
class, the implementation class takes priority.@HandlerChain
to reference.@HandlerChain
annotation. You must also
include the handler classes contained in the configuration
XML file in your class path.@HandlerChain
annotation.@HandlerChain
annotation has a file
attribute that points to a handler chain configuration XML
file that you create. The following file illustrates a
typical handler configuration file. The
protocol-bindings
,
port-name-pattern
, and
service-name-pattern
elements are all filters
that are used to restrict which services can apply the
handlers.
<?xml version="1.0" encoding="UTF-8"?> <jws:handler-chains xmlns:jws="http://java.sun.com/xml/ns/javaee"> <!-- Note: The '*" denotes a wildcard. --> <jws:handler-chain name="MyHandlerChain"> <jws:protocol-bindings>##SOAP11_HTTP ##ANOTHER_BINDING</jws:protocol-bindings> <jws:port-name-pattern xmlns:ns1="http://handlersample.samples.apache.org/">ns1:MySampl*</jws:port-name-pattern> <jws:service-name-pattern xmlns:ns1="http://handlersample.samples.apache.org/">ns1:*</jws:service-name-pattern> <jws:handler> <jws:handler-class>org.apache.samples.handlersample.SampleLogicalHandler</jws:handler-class> </jws:handler> <jws:handler> <jws:handler-class>org.apache.samples.handlersample.SampleProtocolHandler2</jws:handler-class> </jws:handler> <jws:handler> <jws:handler-class>org.apache.samples.handlersample.SampleLogicalHandler</jws:handler-class> </jws:handler> <jws:handler> <jws:handler-class>org.apache.samples.handlersample.SampleProtocolHandler2</jws:handler-class> </jws:handler> </jws:handler-chain> </jws:handler-chains>
package org.apache.samples.handlersample; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.handler.soap.SOAPMessageContext; public class SampleProtocolHandler implements javax.xml.ws.handler.soap.SOAPHandler<SOAPMessageContext> { public void close(MessageContext messagecontext) { } public Set<QName> getHeaders() { return null; } public boolean handleFault(SOAPMessageContext messagecontext) { return true; } public boolean handleMessage(SOAPMessageContext messagecontext) { Boolean outbound = (Boolean) messagecontext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (outbound) { // Include your steps for the outbound flow. } return true; } }
JSESSIONID
, and this
cookie contains the session identifier. This cookie is used
to associate the request with information stored on the
server for that session. On subsequent requests from the
JAX-WS application, the session ID is transmitted as part of
the request header, which enables the application to
associate each request for a given session ID with prior
requests from that user. The JAX-WS client applications
retrieve the session ID from the HTTP response headers and
then use those IDs in subsequent requests by setting the
session ID in the HTTP request headers.
javax.xml.ws.session.maintain
, to true on the
BindingProvider
.
Map<String, Object> rc = ((BindingProvider) port).getRequestContext(); ... ... rc.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); ... ...
// for SOAP version 1.1 @BindingType(value = SOAPBinding.SOAP11HTTP_MTOM_BINDING) // for SOAP version 1.2 @BindingType(value = SOAPBinding.SOAP12HTTP_MTOM_BINDING)
SOAPBinding binding = (SOAPBinding)dispatch.getBinding(); binding.setMTOMEnabled(true);
Service svc = Service.create(serviceName); svc.addPort(portName,SOAPBinding.SOAP11HTTP_MTOM_BINDING,endpointUrl);
// Create a BindingProvider bp from a proxy port. Service svc = Service.create(serviceName); MtomSample proxy = svc.getPort(portName, MtomSample.class); BindingProvider bp = (BindingProvider) proxy; //Enable MTOM SOAPBinding binding = (SOAPBinding) bp.getBinding(); binding.setMTOMEnabled(true);