Web services by Spring Way
Contract-last web services
 Contract-last web services does not require to
manipulate complex WSDL and XSD files.
 In contract-last web services a service class in Java
is written and the web service framework “SOAP-
ifies” it.
 When a web service is developed in contract last,
its contract ends up being a reflection of the
application’s internal API.
 Changes to the internal API will mean changes to
your service’s contract, which will ultimately
require changes in the clients that are consuming
your service.
Contract-first web service
Step Action Purpose
1 Define the service contract This involves designing sample XML
messages that will be processed by our
web service. We’ll use these sample
messages to create XML Schema that will
later be used to create WSDL
2 Write a service endpoint. We’ll create classes that will receive and
process the messages sent to the web
service.
3 Configure the endpoint and
Spring-WS infrastructure.
We’ll wire up our service endpoint along
with a handful of Spring-WS beans that will
tie everything together.
Defining the contract
 The messages that need to be sent and received from the
service are defined regardless of the service
implementation.
 A contract-first view of web services places emphasis on the
messages that are sent to and received from services.
 Create sample XML input and output messages.
 <EvaluateHandRequest
 xmlns="http://www.springinaction.com/poker/schemas">
 <card>
 <suit>HEARTS</suit>
 <face>TEN</face>
 </card>
 </EvaluateHandRequest>
Forging the data contract
 The contract is broken into two parts: data contract and
operational contract.
 The data contract defines the messages going in and out
of the service.
 The messages include the schema definition of the
<EvaluateHandRequest> and <EvaluateHandResponse>
messages.
 The WSDL file usually contains an embedded XML Schema
that defines the data contract.
 The XML Schema (XSD) allows to precisely define what
should go into a message.
 It can not only define what elements are in the message,
but can also specify the types of those messages and place
constraints on what data goes into the message
Operational Contract
 The operational contract defines the operations that our
service will perform.
 SOAP operation does not necessarily correspond to a
method in the service’s API.
 The WSDL file except the embeded schema defines the
operational contract, including one or more
<wsdl:operation> elements within the <wsdl:binding>
element.
Handling messages with service
endpoints
 A web service client interacts with a Spring-WS application
through one of several message endpoints.
 A message endpoint is a class that receives an XML
message from the client and, based on the content of the
message, makes calls to internal application objects to
perform the actual work.
 Once the endpoint has completed processing, it returns its
response in XML output message.
 Message endpoints process incoming XML messages and
produce XML responses.
Message endpoint in Spring-WS
Abstract Endpoint Class Description
AbstractDom4jPayloadEndpoint Handles message payloads as dom4j
Elements
AbstractDomPayloadEndpoint Handles message payloads as DOM
Elements
AbstractJDomPayloadEndpoint Handles message payloads as JDOM
Elements
AbstractMarshallingPayloadEndpoint Unmarshals the request payload into an
object and marshals the response object
into XML
AbstractSaxPayloadEndpoint Handles message payloads through a
SAX ContentHandler implementation
AbstractStaxEventPayloadEndpoint Handles message payloads using event-
based StAX
AbstractStaxStreamPayloadEndpoint Handles message payloads using
streaming StAX
AbstractXomPayloadEndpoint Handles message payloads as XOM
Elements
JDOM-based message endpoint
 public class EvalDomEndpoint extends AbstractJDomPayloadEndpoint
 implements InitializingBean {
 private Namespace namespace;
 private XPath cardsXPath; private XPath suitXPath; private XPath
faceXPath
 protected Element invokeInternal(Element element) throws Exception {
 Card cards[] = extractCardsFromRequest(element);
 PokerHand pokerHand = new PokerHand();
 pokerHand.setCards(cards);
 PokerHandType handType =
 pokerHandEvaluator.evaluateHand(pokerHand);
 return createResponse(handType);
 }
 private Element createResponse(PokerHandType handType) {
 Element responseElement = new Element("EvaluateHandResponse",
 namespace);
 responseElement.addContent( new Element("handName",
 namespace).setText(handType.toString()));
 return responseElement;
 }
JDOM-based message endpoint
 private Card[] extractCardsFromRequest(Element element)
 throws JDOMException {
 Card[] cards = new Card[5];
 List cardElements = cardsXPath.selectNodes(element);
 for(int i=0; i < cardElements.size(); i++) {
 Element cardElement = (Element) cardElements.get(i);
 Suit suit = Suit.valueOf( suitXPath.valueOf(cardElement));
 Face face = Face.valueOf( faceXPath.valueOf(cardElement));
 cards[i] = new Card(); cards[i].setFace(face); cards[i].setSuit(suit);
 }
 return cards;
 }
 public void afterPropertiesSet() throws Exception {
 namespace = Namespace.getNamespace("poker",
 "http://www.springinaction.com/poker/schemas");
 cardsXPath = XPath.newInstance("/poker:EvaluateHandRequest/poker.card");
 cardsXPath.addNamespace(namespace);
 faceXPath = XPath.newInstance("poker:face");
 faceXPath.addNamespace(namespace);
 suitXPath = XPath.newInstance("poker:suit");
 suitXPath.addNamespace(namespace);
 }
JDOM-based message endpoint
 public class EvaluateHandJDomEndpoint extends AbstractJDomPayloadEndpoint
implements InitializingBean {
 private Namespace namespace;
 private XPath cardsXPath; private XPath suitXPath; private XPath faceXPath;
 protected Element invokeInternal(Element element) throws Exception {
 Card cards[] = extractCardsFromRequest(element);
 PokerHand pokerHand = new PokerHand();
 pokerHand.setCards(cards);
 PokerHandType handType = pokerHandEvaluator.evaluateHand(pokerHand);
 return createResponse(handType);
 }
 private Element createResponse(PokerHandType handType) {
 Element responseElement = new Element("EvaluateHandResponse", namespace);
 responseElement.addContent(new Element("handName",
namespace).setText(handType.toString()));
 return responseElement;
 }
 private Card[] extractCardsFromRequest(Element element) throws JDOMException {
 Card[] cards = new Card[5];
 List cardElements = cardsXPath.selectNodes(element);
 for(int i=0; i < cardElements.size(); i++) {
 Element cardElement = (Element) cardElements.get(i);
 Suit suit = Suit.valueOf(suitXPath.valueOf(cardElement));
 Face face = Face.valueOf(faceXPath.valueOf(cardElement));
 cards[i] = new Card();
 cards[i].setFace(face);
 cards[i].setSuit(suit);
 }
 return cards;
 }
 public void afterPropertiesSet() throws Exception {
 namespace = Namespace.getNamespace("poker", "http://www.springinaction.com/poker/schemas");
 cardsXPath = XPath.newInstance("/poker:EvaluateHandRequest/poker.card");
 cardsXPath.addNamespace(namespace);
 faceXPath = XPath.newInstance("poker:face");
 faceXPath.addNamespace(namespace);
 suitXPath = XPath.newInstance("poker:suit");
 suitXPath.addNamespace(namespace);
 }
 // injected
 private PokerHandEvaluator pokerHandEvaluator;
 public void setPokerHandEvaluator(PokerHandEvaluator pokerHandEvaluator) {
 this.pokerHandEvaluator = pokerHandEvaluator;
 }
 }
JDOM-based message endpoint
 The invokeInternal() method is the entry point to the endpoint.
 The invokeInternal() gets a JDOM Element object containing the
incoming message, which is the <EvaluateHandRequest>.
 The Element object is forwarded to extractCardsFromRequest().
 After getting an array of Card objects, invokeInternal() passes
those Cards to an injected PokerHandEvaluator’s
evaluateHand(), to evaluate the poker hand (has actual business
logic).
 The invokeInternal() passes the PokerHandType object off to
createResponse() to produce an <EvaluateHandResponse>
element using JDOM.
 The resulting JDOM Element is returned and
EvaluateHandJDomEndpoint’s job is done.
Marshaling message payloads
 AbstractMarshallingPayloadEndpoint is given an object to
process instead of an XML Element to pull apart for information.
 A marshaling endpoint works with an unmarshaler that converts
an incoming XML message into a POJO and a marshaler which
converts the POJO into an XML message to be returned to the
client.
 AbstractMarshallingPayloadEndpoint has a reference to an XML
marshaler which it uses to turn the XML message into an object
and vice versa.
 The key benefit of EvaluateHandMarshallingEndpoint is that it
can be unit tested similar to any other POJO.
AbstractMarshallingPayloadEndpoint Request Processing
 public class EvaluateHandMarshallingEndpoint extends
AbstractMarshallingPayloadEndpoint {
 protected Object invokeInternal(Object object) throws Exception {
 EvaluateHandRequest request = (EvaluateHandRequest) object;
 PokerHand pokerHand = new PokerHand();
 pokerHand.setCards(request.getHand());
 PokerHandType pokerHandType =
 pokerHandEvaluator.evaluateHand(pokerHand);
 return new EvaluateHandResponse(pokerHandType);
 }
 // injected
 private PokerHandEvaluator pokerHandEvaluator;
 public void setPokerHandEvaluator(
 PokerHandEvaluator pokerHandEvaluator) {
 this.pokerHandEvaluator = pokerHandEvaluator;
 }
 }
Wiring Spring-WS
 Spring-WS can be fronted by MessageDispatcherServlet, a
subclass of DispatcherServlet that knows how to dispatch SOAP
requests to Spring-WS endpoints.
 <servlet>
 <servlet-name>poker</servlet-name>
 <servlet-class>org.springframework.ws.transport.http.
 ➥ MessageDispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>poker</servlet-name>
 <url-pattern>/services/*</url-pattern>
 </servlet-mapping>
Spring-WS service configuration
Spring-WS service configuration
 ■ payloadMapping—Maps incoming XML messages to an appropriate endpoint.
 In this case, we’ll use a mapping that looks up endpoints using the
 incoming XML’s root element (by its qualified name).
 ■ evaluateHandEndpoint—This is the endpoint that will process the incoming
 XML message for the poker hand evaluation service.
 ■ marshaller—The evaluateHandEndpoint could be written to process the
 incoming XML as a DOM or JDOM element, or even as a SAX event handler.
 Instead, the marshaller bean will automatically convert XML to and from
 Java objects.
 ■ pokerHandEvaluator—This is a POJO that performs the actual poker hand
 processing. evaluateHandEndpoint will use this bean to do its work.
 ■ endpointExceptionResolver—This is a Spring-WS bean that will automatically
 convert any Java exceptions thrown while processing a request into
 appropriate SOAP faults.
 ■ poker—Although it’s not obvious from its name, this bean will serve the
 WSDL for the poker hand web service to the client. Either it can serve handcreated
 WSDL or it can be wired to automatically generate WSDL from the
 message’s XML Schema.
Mapping messages to endpoints
 The incoming messages need to be mapped to the endpoints that
process them.
 MessageDispatcherServlet uses an endpoint mapping to decide which
endpoint should receive an incoming XML message.
 <bean id="payloadMapping"
 class="org.springframework.ws.server.endpoint.mapping.
 PayloadRootQNameEndpointMapping">
 <property name="endpointMap">
 <map>
 <entry key=
 "{http://www.springinaction.com/poker/schemas}
 EvaluateHandRequest"
 value-ref="evaluateHandEndpoint" />
 </map>
 </property>
 </bean>
Mapping messages to endpoints
 PayloadRootQNameEndpointMapping maps
incoming SOAP messages to endpoints by examining
the qualified name (QName) of the message’s payload
and looking up the endpoint from its list of mappings
(configured through the endpointMap property).
 The QName is mapped to a bean named
evaluateHandEndpoint
Wiring Service Endpoint
 The JDOM-based endpoint then it is configured in Spring as
follows:
 <bean id="evaluateHandEndpoint"
 class="com.springinaction.poker.webservice.
 EvaluateHandJDomEndpoint">
 <property name="pokerHandEvaluator"
 ref="pokerHandEvaluator" />
 </bean>
 The EvaluateHandJDomEndpoint delegates to an
implementation of PokerHandEvaluator which evaluates the
poker hand.
Wiring Service Endpoint
 The EvaluateHandMarshallingEndpoint configuration:
 <bean id="evaluateHandEndpoint"
 class="com.springinaction.poker.webservice.
 EvaluateHandMarshallingEndpoint">
 <property name="marshaller" ref="marshaller" />
 <property name="unmarshaller" ref="marshaller" />
 <property name="pokerHandEvaluator"
 ref="pokerHandEvaluator" />
 </bean>
 Alongwith the pokerHandEvaluator property, the marshaling
endpoint must have its marshaller and unmarshaller properties
set as well.
Configuring a message marshaler
 The key to translating objects to and from XML
messages is object-XML mapping (OXM).
 The central elements of Spring-OXM are its Marshaller
and Unmarshaller interfaces.
 Marshaller are used to generate XML elements from
Java objects while Unmarshaller are used to construct
Java objects from XML elements.
 AbstractMarshallingPayloadEndpoint takes advantage
of the Spring-OXM marshalers and unmarshalers
when processing messages.
Spring-OXM Marshallers
OXM solution Spring-OXM marshaler
Castor XML org.springframework.oxm.castor.CastorMarshaller
JAXB v1 org.springframework.oxm.jaxb.Jaxb1Marshaller
JAXB v2 org.springframework.oxm.jaxb.Jaxb2Marshaller
JiBX org.springframework.oxm.jibx.JibxMarshaller
XMLBeans org.springframework.oxm.xmlbeans.XmlBeansMarshaller
XStream org.springframework.oxm.xstream.XStreamMarshaller
(limited support for XML namespaces)
Sample Castor XML Mapping
 <?xml version="1.0"?>
 <mapping xmlns="http://castor.exolab.org/">
 <class name="com.springinaction.poker.webservice.
 ➥ EvaluateHandRequest">
 <map-to xml="EvaluateHandRequest" />
 <field name="hand"
 collection="array"
 type="com.springinaction.poker.Card"
 required="true">
 <bind-xml name="card" node="element" />
 </field>
 </class>
 </mapping>
Handling endpoint exceptions
 Java exceptions thrown by web servicesshould be
converted into SOAP faults.
 SoapFaultMappingExceptionResolver handles any
uncaught exceptions that occur in the course of
handling a message and produce an appropriate SOAP
fault that will be sent back to the client.
SoapFaultMappingExceptionResolver
 <bean id="endpointExceptionResolver"
 class="org.springframework.ws.soap.server.endpoint.
 ➥ SoapFaultMappingExceptionResolver">
 <property name="exceptionMappings">
 <props>
 <prop key="org.springframework.oxm.
 ➥ UnmarshallingFailureException">
 SENDER,Invalid message received</prop>
 <prop key="org.springframework.oxm.
 ➥ ValidationFailureException">
 SENDER,Invalid message received</prop>
 </props>
 </property>
 <property name="defaultFault“ value="RECEIVER,Server error" />
 </bean>
SoapFaultMappingExceptionResolver
 The exceptionMappings property is configured with one or
more SOAP fault definitions mapped to Java exceptions.
 The key of each <prop> is a Java exception which needs to
be translated to a SOAP fault.
 The value of the <prop> is a two-part value where the first
part is the type of fault that is to be created and the second
part is a string that describes the fault.
 SOAP faults come in two types: sender and receiver faults.
 Sender faults indicate that the problem is on the client.
 Receiver faults indicate that the message received from the
client is having some processing problem.
Serving WSDL files
 DynamicWsdl11Definition is a special bean that
MessageDispatcherServlet works with to generate WSDL from
XML Schema.
 DynamicWsdl11Definition works by reading an XML Schema
definition, specified here as PokerTypes.xsd by the schema
property.
 DynamicWsdl11Definition reads an XML Schema definition
specified by the schema property.
 It looks through the schema file for any element definitions
whose names end with Request and Response.
 It assumes that those suffixes indicate a message that is to be
sent to or from a web service operation and creates a
corresponding <wsdl:operation> element in the WSDL it
produces.
DynamicWsdl11Definition
 <bean id="poker"
 class="org.springframework.ws.wsdl.wsdl11.
 ➥ DynamicWsdl11Definition">
 <property name="builder">
 <bean class="org.springframework.ws.wsdl.wsdl11.builder.
 ➥ XsdBasedSoap11Wsdl4jDefinitionBuilder">
 <property name="schema" value="/PokerTypes.xsd"/>
 <property name="portTypeName" value="Poker"/>
 <property name="locationUri"
 value="http://localhost:8080/Poker-WS/services"/>
 </bean>
 </property>
 </bean>
DynamicWsdl11Definition Config
 <wsdl:portType name="Poker">
 <wsdl:operation name="EvaluateHand">
 <wsdl:input message="schema:EvaluateHandRequest"
 name="EvaluateHandRequest">
 </wsdl:input>
 <wsdl:output message="schema:EvaluateHandResponse"
 name="EvaluateHandResponse">
 </wsdl:output>
 </wsdl:operation>
 </wsdl:portType>
URL Mapping
 A new <servletmapping> is added to web.xml so that
MessageDispatcherServlet will serve WSDL
definitions.
<servlet-mapping>
<servlet-name>
poker
</servlet-name>
<url-pattern>
*.wsdl
</url-pattern>
</servlet-mapping
Predefined WSDL
 SimpleWsdl11Definition serves the WSDL provided through the wsdl property.
 <bean id="poker"
 class="org.springframework.ws.wsdl.wsdl11.
 ➥ SimpleWsdl11Definition">
 <property name="wsdl" value="/PokerService.wsdl"/>
 </bean>
 MessageDispatcherServlet can rewrite the service’s location specified in static
WSDL every time it is deployed.
 It requires to set an <init-param> named transformWsdlLocations to true in
MessageDispatcherServlet.
 <servlet>
 <servlet-name>poker</servlet-name>
 <servlet-class>org.springframework.ws.transport.http.
 ➥ MessageDispatcherServlet</servlet-class>
 <init-param>
 <param-name>transformWsdlLocations</param-name>
 <param-value>true</param-value>
 </init-param>
 </servlet>
Consuming Spring Web services
 WebServiceTemplate is the centerpiece of Spring-WS’s
client API.
 It employs the Template design pattern to provide the
ability to send and receive XML messages from
message-centric web services.
Configuring WebServiceTemplate
 <bean id="webServiceTemplate"
 class="org.springframework.ws.client.core.WebServiceTemplate">
 <property name="messageFactory">
 <bean class="org.springframework.ws.soap.saaj.
 ➥ SaajSoapMessageFactory"/>
 </property>
 <property name="messageSender" ref="messageSender"/>
 </bean>
 <bean id="messageSender"
 class="org.springframework.ws.transport.http.
 ➥ HttpUrlConnectionMessageSender">
 <property name="url"
 value="http://localhost:8080/Poker-WS/services"/>
 </bean>
WebServiceTemplate
 WebServiceTemplate constructs the message and
sends it to the web service.
 The object wired into the messageFactory property
handles the task of constructing the message.
 It should be wired with an implementation of Spring-
WS’s WebServiceMessageFactory interface.
 SaajSoapMessageFactory is the default message factory
used by MessageDispatcherServlet.
Message Factory Implementations
Message factory What it does
AxiomSoapMessageFactory Produces SOAP messages using the AXIs Object
Model (AXIOM). Based on the StAX streaming XML
API. Useful when working with large messages and
performance is a problem.
DomPoxMessageFactory Produces Plain Old XML (POX) messages using a
DOM. Use this message factory when neither the
client nor the service cares to deal with SOAP
SaajSoapMessageFactory Produces SOAP messages using the SOAP with
Attachments API for Java (SAAJ). Because SAAJ uses
a DOM, large messages could consume a lot of
memory. If performance becomes an issue, consider
using AxiomSoapMessageFactory instead.
WebServiceMessageSender
 The messageSender property should be wired with a
reference to an implementation of a
WebServiceMessageSender.
 The url property specifies the location of the service and it
matches the URL in the service’s WSDL definition.
Message sender What it does
CommonsHttpMessageSender Sends the message using Jakarta
Commons HTTP Client. Supports a
preconfigured HTTP client, allowing
advanced features such as HTTP
authentication and HTTP connection
pooling.
HttpUrlConnectionMessageSender Sends the message using Java’s basic
facilities for HTTP connections.
Provides limited functionality.
Sending a message
 The sendAndReceive() method takes a
java.xml.transform.Source and a
java.xml.transform.Result as parameters to send the
message.
 The Source object represents the message payload to
send to the web service.
 The Result object is to be populated with the message
payload returned from the service.
 public boolean sendAndReceive(Source
requestPayload, Result responseResult)
 throws IOException
WebServiceTemplate Implementation
 public PokerHandType evaluateHand(Card[] cards) throws IOException {
 Element requestElement =
 new Element("EvaluateHandRequest");
 Namespace ns = Namespace.getNamespace(
 "http://www.springinaction.com/poker/schemas");
 requestElement.setNamespace(ns);
 Document doc = new Document(requestElement);
 // Process the Request message
 JDOMSource requestSource = new JDOMSource(doc);
 JDOMResult result = new JDOMResult();
 webServiceTemplate.sendAndReceive(requestSource, result);
 Document resultDocument = result.getDocument();
 Element responseElement = resultDocument.getRootElement();
 Element handNameElement =
 responseElement.getChild("handName", ns);
 return PokerHandType.valueOf(handNameElement.getText());
 }
Marshalers on Client side
 WebServiceTemplate provides marshalSendAndReceive()
method for sending and receiving XML messages that are
marshaled to and from Java objects.
 public class MarshallingPokerClient implements PokerClient {
 public PokerHandType evaluateHand(Card[] cards)
 throws IOException {
 EvaluateHandRequest request = new EvaluateHandRequest();
 request.setHand(cards);
 EvaluateHandResponse response = (EvaluateHandResponse)
 webServiceTemplate.marshalSendAndReceive(request);
 return response.getPokerHand();
 }
 }
WebServiceTemplate with Marshalers
Marshaler Configuration
 <bean id="webServiceTemplate"
 class="org.springframework.ws.client.core.WebServiceTem
plate">
 <property name="messageFactory">
 <bean class="org.springframework.ws.soap.saaj.
 ➥ SaajSoapMessageFactory"/>
 </property>
 <property name="messageSender"
ref="urlMessageSender"/>
 <property name="marshaller" ref="marshaller" />
 <property name="unmarshaller" ref="marshaller" />
 </bean>
Web Service Gateway Support
 WebServiceGatewaySupport is a convenient support class that
automatically provides a WebServiceTemplate to client classes
that subclass it, without injecting with a WebServiceTemplate.
 public class PokerServiceGateway
 extends WebServiceGatewaySupport implements PokerClient {
 public PokerHandType evaluateHand(Card[] cards)
 throws IOException {
 EvaluateHandRequest request = new EvaluateHandRequest();
 request.setHand(cards);
 EvaluateHandResponse response = (EvaluateHandResponse)
 getWebServiceTemplate().marshalSendAndReceive(request);
 return response.getPokerHand();
 }
 }

More Related Content

PDF
Spring Web Services: SOAP vs. REST
PPT
Using Java to implement SOAP Web Services: JAX-WS
PDF
Lecture 7 Web Services JAX-WS & JAX-RS
ODP
Interoperable Web Services with JAX-WS
PDF
Introduction to Ajax programming
PDF
Building RESTful applications using Spring MVC
ODP
Interoperable Web Services with JAX-WS and WSIT
PDF
Spring Mvc Rest
Spring Web Services: SOAP vs. REST
Using Java to implement SOAP Web Services: JAX-WS
Lecture 7 Web Services JAX-WS & JAX-RS
Interoperable Web Services with JAX-WS
Introduction to Ajax programming
Building RESTful applications using Spring MVC
Interoperable Web Services with JAX-WS and WSIT
Spring Mvc Rest

What's hot (20)

PDF
Spring Framework - MVC
PPT
JAX-WS Basics
PDF
RESTful Web Services with Spring MVC
PPTX
Rest with Java EE 6 , Security , Backbone.js
PPTX
Spring MVC
PDF
Java web services using JAX-WS
PDF
Introduction to SOAP/WSDL Web Services and RESTful Web Services
PDF
Java API for XML Web Services (JAX-WS)
KEY
MVC on the server and on the client
PPTX
Java web application development
PPTX
Integration of Backbone.js with Spring 3.1
PPTX
Introduction to RESTful Webservices in JAVA
ODP
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
PDF
Spring Web Service, Spring Integration and Spring Batch
PPTX
Mail OnLine Android Application at DroidCon - Turin - Italy
PPTX
ASP.NET Web API
PDF
jQuery - Chapter 1 - Introduction
KEY
Multi Client Development with Spring
PDF
Dynamic content generation
PPT
ASP.NET 12 - State Management
Spring Framework - MVC
JAX-WS Basics
RESTful Web Services with Spring MVC
Rest with Java EE 6 , Security , Backbone.js
Spring MVC
Java web services using JAX-WS
Introduction to SOAP/WSDL Web Services and RESTful Web Services
Java API for XML Web Services (JAX-WS)
MVC on the server and on the client
Java web application development
Integration of Backbone.js with Spring 3.1
Introduction to RESTful Webservices in JAVA
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Spring Web Service, Spring Integration and Spring Batch
Mail OnLine Android Application at DroidCon - Turin - Italy
ASP.NET Web API
jQuery - Chapter 1 - Introduction
Multi Client Development with Spring
Dynamic content generation
ASP.NET 12 - State Management
Ad

Similar to Spring Web Services (20)

DOCX
Web services Concepts
PPT
java-webservices introduction ppt for beginners
PDF
Steps india technologies .com
PDF
Steps india technologies
PPTX
Web Services
DOCX
Web services in java
PDF
Spring ws
PPTX
Java Web services
PPTX
Ogsi protocol perspective
ODP
SCDJWS 5. JAX-WS
PPTX
Soap and restful webservice
PDF
Web service introduction
PPT
Web Services
PPT
Web Services
PPTX
Lecture 16 - Web Services
PPTX
Web service- Guest Lecture at National Wokshop
PPT
webservicearchitecture-150614164814-lva1-app6892.ppt
PPTX
Cloud computing 20 service modelling
PPT
Java web services
PDF
Java Web Services [3/5]: WSDL, WADL and UDDI
Web services Concepts
java-webservices introduction ppt for beginners
Steps india technologies .com
Steps india technologies
Web Services
Web services in java
Spring ws
Java Web services
Ogsi protocol perspective
SCDJWS 5. JAX-WS
Soap and restful webservice
Web service introduction
Web Services
Web Services
Lecture 16 - Web Services
Web service- Guest Lecture at National Wokshop
webservicearchitecture-150614164814-lva1-app6892.ppt
Cloud computing 20 service modelling
Java web services
Java Web Services [3/5]: WSDL, WADL and UDDI
Ad

More from Emprovise (20)

PDF
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
PPTX
Leadership and Success Lessons for Life/Business
PPTX
Secure socket layer
PPTX
Effective java
PPTX
EJB3 Advance Features
PPTX
Enterprise Java Beans 3 - Business Logic
PPTX
EJB3 Basics
PPTX
RESTful WebServices
PPTX
J2EE Patterns
PPTX
Spring JMS
PPTX
PPTX
Spring Web Webflow
PPTX
Spring Web Views
PPTX
Enterprise Spring
PPTX
Spring Basics
PPTX
Apache Struts 2 Advance
PPTX
Apache Struts 2 Framework
PPTX
Java Servlets
PPTX
Java Advance Concepts
PPTX
Java Basics
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Leadership and Success Lessons for Life/Business
Secure socket layer
Effective java
EJB3 Advance Features
Enterprise Java Beans 3 - Business Logic
EJB3 Basics
RESTful WebServices
J2EE Patterns
Spring JMS
Spring Web Webflow
Spring Web Views
Enterprise Spring
Spring Basics
Apache Struts 2 Advance
Apache Struts 2 Framework
Java Servlets
Java Advance Concepts
Java Basics

Recently uploaded (20)

PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
PDF
Hybrid model detection and classification of lung cancer
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
WOOl fibre morphology and structure.pdf for textiles
PPT
Module 1.ppt Iot fundamentals and Architecture
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPT
Geologic Time for studying geology for geologist
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
The various Industrial Revolutions .pptx
sustainability-14-14877-v2.pddhzftheheeeee
Developing a website for English-speaking practice to English as a foreign la...
A Late Bloomer's Guide to GenAI: Ethics, Bias, and Effective Prompting - Boha...
Hybrid model detection and classification of lung cancer
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
DP Operators-handbook-extract for the Mautical Institute
Assigned Numbers - 2025 - Bluetooth® Document
A comparative study of natural language inference in Swahili using monolingua...
A novel scalable deep ensemble learning framework for big data classification...
Taming the Chaos: How to Turn Unstructured Data into Decisions
WOOl fibre morphology and structure.pdf for textiles
Module 1.ppt Iot fundamentals and Architecture
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
NewMind AI Weekly Chronicles – August ’25 Week III
Geologic Time for studying geology for geologist
Group 1 Presentation -Planning and Decision Making .pptx
Enhancing emotion recognition model for a student engagement use case through...
O2C Customer Invoices to Receipt V15A.pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
The various Industrial Revolutions .pptx

Spring Web Services

  • 1. Web services by Spring Way
  • 2. Contract-last web services  Contract-last web services does not require to manipulate complex WSDL and XSD files.  In contract-last web services a service class in Java is written and the web service framework “SOAP- ifies” it.  When a web service is developed in contract last, its contract ends up being a reflection of the application’s internal API.  Changes to the internal API will mean changes to your service’s contract, which will ultimately require changes in the clients that are consuming your service.
  • 3. Contract-first web service Step Action Purpose 1 Define the service contract This involves designing sample XML messages that will be processed by our web service. We’ll use these sample messages to create XML Schema that will later be used to create WSDL 2 Write a service endpoint. We’ll create classes that will receive and process the messages sent to the web service. 3 Configure the endpoint and Spring-WS infrastructure. We’ll wire up our service endpoint along with a handful of Spring-WS beans that will tie everything together.
  • 4. Defining the contract  The messages that need to be sent and received from the service are defined regardless of the service implementation.  A contract-first view of web services places emphasis on the messages that are sent to and received from services.  Create sample XML input and output messages.  <EvaluateHandRequest  xmlns="http://www.springinaction.com/poker/schemas">  <card>  <suit>HEARTS</suit>  <face>TEN</face>  </card>  </EvaluateHandRequest>
  • 5. Forging the data contract  The contract is broken into two parts: data contract and operational contract.  The data contract defines the messages going in and out of the service.  The messages include the schema definition of the <EvaluateHandRequest> and <EvaluateHandResponse> messages.  The WSDL file usually contains an embedded XML Schema that defines the data contract.  The XML Schema (XSD) allows to precisely define what should go into a message.  It can not only define what elements are in the message, but can also specify the types of those messages and place constraints on what data goes into the message
  • 6. Operational Contract  The operational contract defines the operations that our service will perform.  SOAP operation does not necessarily correspond to a method in the service’s API.  The WSDL file except the embeded schema defines the operational contract, including one or more <wsdl:operation> elements within the <wsdl:binding> element.
  • 7. Handling messages with service endpoints  A web service client interacts with a Spring-WS application through one of several message endpoints.  A message endpoint is a class that receives an XML message from the client and, based on the content of the message, makes calls to internal application objects to perform the actual work.  Once the endpoint has completed processing, it returns its response in XML output message.  Message endpoints process incoming XML messages and produce XML responses.
  • 8. Message endpoint in Spring-WS Abstract Endpoint Class Description AbstractDom4jPayloadEndpoint Handles message payloads as dom4j Elements AbstractDomPayloadEndpoint Handles message payloads as DOM Elements AbstractJDomPayloadEndpoint Handles message payloads as JDOM Elements AbstractMarshallingPayloadEndpoint Unmarshals the request payload into an object and marshals the response object into XML AbstractSaxPayloadEndpoint Handles message payloads through a SAX ContentHandler implementation AbstractStaxEventPayloadEndpoint Handles message payloads using event- based StAX AbstractStaxStreamPayloadEndpoint Handles message payloads using streaming StAX AbstractXomPayloadEndpoint Handles message payloads as XOM Elements
  • 9. JDOM-based message endpoint  public class EvalDomEndpoint extends AbstractJDomPayloadEndpoint  implements InitializingBean {  private Namespace namespace;  private XPath cardsXPath; private XPath suitXPath; private XPath faceXPath  protected Element invokeInternal(Element element) throws Exception {  Card cards[] = extractCardsFromRequest(element);  PokerHand pokerHand = new PokerHand();  pokerHand.setCards(cards);  PokerHandType handType =  pokerHandEvaluator.evaluateHand(pokerHand);  return createResponse(handType);  }  private Element createResponse(PokerHandType handType) {  Element responseElement = new Element("EvaluateHandResponse",  namespace);  responseElement.addContent( new Element("handName",  namespace).setText(handType.toString()));  return responseElement;  }
  • 10. JDOM-based message endpoint  private Card[] extractCardsFromRequest(Element element)  throws JDOMException {  Card[] cards = new Card[5];  List cardElements = cardsXPath.selectNodes(element);  for(int i=0; i < cardElements.size(); i++) {  Element cardElement = (Element) cardElements.get(i);  Suit suit = Suit.valueOf( suitXPath.valueOf(cardElement));  Face face = Face.valueOf( faceXPath.valueOf(cardElement));  cards[i] = new Card(); cards[i].setFace(face); cards[i].setSuit(suit);  }  return cards;  }  public void afterPropertiesSet() throws Exception {  namespace = Namespace.getNamespace("poker",  "http://www.springinaction.com/poker/schemas");  cardsXPath = XPath.newInstance("/poker:EvaluateHandRequest/poker.card");  cardsXPath.addNamespace(namespace);  faceXPath = XPath.newInstance("poker:face");  faceXPath.addNamespace(namespace);  suitXPath = XPath.newInstance("poker:suit");  suitXPath.addNamespace(namespace);  }
  • 11. JDOM-based message endpoint  public class EvaluateHandJDomEndpoint extends AbstractJDomPayloadEndpoint implements InitializingBean {  private Namespace namespace;  private XPath cardsXPath; private XPath suitXPath; private XPath faceXPath;  protected Element invokeInternal(Element element) throws Exception {  Card cards[] = extractCardsFromRequest(element);  PokerHand pokerHand = new PokerHand();  pokerHand.setCards(cards);  PokerHandType handType = pokerHandEvaluator.evaluateHand(pokerHand);  return createResponse(handType);  }  private Element createResponse(PokerHandType handType) {  Element responseElement = new Element("EvaluateHandResponse", namespace);  responseElement.addContent(new Element("handName", namespace).setText(handType.toString()));  return responseElement;  }
  • 12.  private Card[] extractCardsFromRequest(Element element) throws JDOMException {  Card[] cards = new Card[5];  List cardElements = cardsXPath.selectNodes(element);  for(int i=0; i < cardElements.size(); i++) {  Element cardElement = (Element) cardElements.get(i);  Suit suit = Suit.valueOf(suitXPath.valueOf(cardElement));  Face face = Face.valueOf(faceXPath.valueOf(cardElement));  cards[i] = new Card();  cards[i].setFace(face);  cards[i].setSuit(suit);  }  return cards;  }  public void afterPropertiesSet() throws Exception {  namespace = Namespace.getNamespace("poker", "http://www.springinaction.com/poker/schemas");  cardsXPath = XPath.newInstance("/poker:EvaluateHandRequest/poker.card");  cardsXPath.addNamespace(namespace);  faceXPath = XPath.newInstance("poker:face");  faceXPath.addNamespace(namespace);  suitXPath = XPath.newInstance("poker:suit");  suitXPath.addNamespace(namespace);  }  // injected  private PokerHandEvaluator pokerHandEvaluator;  public void setPokerHandEvaluator(PokerHandEvaluator pokerHandEvaluator) {  this.pokerHandEvaluator = pokerHandEvaluator;  }  }
  • 13. JDOM-based message endpoint  The invokeInternal() method is the entry point to the endpoint.  The invokeInternal() gets a JDOM Element object containing the incoming message, which is the <EvaluateHandRequest>.  The Element object is forwarded to extractCardsFromRequest().  After getting an array of Card objects, invokeInternal() passes those Cards to an injected PokerHandEvaluator’s evaluateHand(), to evaluate the poker hand (has actual business logic).  The invokeInternal() passes the PokerHandType object off to createResponse() to produce an <EvaluateHandResponse> element using JDOM.  The resulting JDOM Element is returned and EvaluateHandJDomEndpoint’s job is done.
  • 14. Marshaling message payloads  AbstractMarshallingPayloadEndpoint is given an object to process instead of an XML Element to pull apart for information.  A marshaling endpoint works with an unmarshaler that converts an incoming XML message into a POJO and a marshaler which converts the POJO into an XML message to be returned to the client.  AbstractMarshallingPayloadEndpoint has a reference to an XML marshaler which it uses to turn the XML message into an object and vice versa.  The key benefit of EvaluateHandMarshallingEndpoint is that it can be unit tested similar to any other POJO.
  • 15. AbstractMarshallingPayloadEndpoint Request Processing  public class EvaluateHandMarshallingEndpoint extends AbstractMarshallingPayloadEndpoint {  protected Object invokeInternal(Object object) throws Exception {  EvaluateHandRequest request = (EvaluateHandRequest) object;  PokerHand pokerHand = new PokerHand();  pokerHand.setCards(request.getHand());  PokerHandType pokerHandType =  pokerHandEvaluator.evaluateHand(pokerHand);  return new EvaluateHandResponse(pokerHandType);  }  // injected  private PokerHandEvaluator pokerHandEvaluator;  public void setPokerHandEvaluator(  PokerHandEvaluator pokerHandEvaluator) {  this.pokerHandEvaluator = pokerHandEvaluator;  }  }
  • 16. Wiring Spring-WS  Spring-WS can be fronted by MessageDispatcherServlet, a subclass of DispatcherServlet that knows how to dispatch SOAP requests to Spring-WS endpoints.  <servlet>  <servlet-name>poker</servlet-name>  <servlet-class>org.springframework.ws.transport.http.  ➥ MessageDispatcherServlet</servlet-class>  </servlet>  <servlet-mapping>  <servlet-name>poker</servlet-name>  <url-pattern>/services/*</url-pattern>  </servlet-mapping>
  • 18. Spring-WS service configuration  ■ payloadMapping—Maps incoming XML messages to an appropriate endpoint.  In this case, we’ll use a mapping that looks up endpoints using the  incoming XML’s root element (by its qualified name).  ■ evaluateHandEndpoint—This is the endpoint that will process the incoming  XML message for the poker hand evaluation service.  ■ marshaller—The evaluateHandEndpoint could be written to process the  incoming XML as a DOM or JDOM element, or even as a SAX event handler.  Instead, the marshaller bean will automatically convert XML to and from  Java objects.  ■ pokerHandEvaluator—This is a POJO that performs the actual poker hand  processing. evaluateHandEndpoint will use this bean to do its work.  ■ endpointExceptionResolver—This is a Spring-WS bean that will automatically  convert any Java exceptions thrown while processing a request into  appropriate SOAP faults.  ■ poker—Although it’s not obvious from its name, this bean will serve the  WSDL for the poker hand web service to the client. Either it can serve handcreated  WSDL or it can be wired to automatically generate WSDL from the  message’s XML Schema.
  • 19. Mapping messages to endpoints  The incoming messages need to be mapped to the endpoints that process them.  MessageDispatcherServlet uses an endpoint mapping to decide which endpoint should receive an incoming XML message.  <bean id="payloadMapping"  class="org.springframework.ws.server.endpoint.mapping.  PayloadRootQNameEndpointMapping">  <property name="endpointMap">  <map>  <entry key=  "{http://www.springinaction.com/poker/schemas}  EvaluateHandRequest"  value-ref="evaluateHandEndpoint" />  </map>  </property>  </bean>
  • 20. Mapping messages to endpoints  PayloadRootQNameEndpointMapping maps incoming SOAP messages to endpoints by examining the qualified name (QName) of the message’s payload and looking up the endpoint from its list of mappings (configured through the endpointMap property).  The QName is mapped to a bean named evaluateHandEndpoint
  • 21. Wiring Service Endpoint  The JDOM-based endpoint then it is configured in Spring as follows:  <bean id="evaluateHandEndpoint"  class="com.springinaction.poker.webservice.  EvaluateHandJDomEndpoint">  <property name="pokerHandEvaluator"  ref="pokerHandEvaluator" />  </bean>  The EvaluateHandJDomEndpoint delegates to an implementation of PokerHandEvaluator which evaluates the poker hand.
  • 22. Wiring Service Endpoint  The EvaluateHandMarshallingEndpoint configuration:  <bean id="evaluateHandEndpoint"  class="com.springinaction.poker.webservice.  EvaluateHandMarshallingEndpoint">  <property name="marshaller" ref="marshaller" />  <property name="unmarshaller" ref="marshaller" />  <property name="pokerHandEvaluator"  ref="pokerHandEvaluator" />  </bean>  Alongwith the pokerHandEvaluator property, the marshaling endpoint must have its marshaller and unmarshaller properties set as well.
  • 23. Configuring a message marshaler  The key to translating objects to and from XML messages is object-XML mapping (OXM).  The central elements of Spring-OXM are its Marshaller and Unmarshaller interfaces.  Marshaller are used to generate XML elements from Java objects while Unmarshaller are used to construct Java objects from XML elements.  AbstractMarshallingPayloadEndpoint takes advantage of the Spring-OXM marshalers and unmarshalers when processing messages.
  • 24. Spring-OXM Marshallers OXM solution Spring-OXM marshaler Castor XML org.springframework.oxm.castor.CastorMarshaller JAXB v1 org.springframework.oxm.jaxb.Jaxb1Marshaller JAXB v2 org.springframework.oxm.jaxb.Jaxb2Marshaller JiBX org.springframework.oxm.jibx.JibxMarshaller XMLBeans org.springframework.oxm.xmlbeans.XmlBeansMarshaller XStream org.springframework.oxm.xstream.XStreamMarshaller (limited support for XML namespaces)
  • 25. Sample Castor XML Mapping  <?xml version="1.0"?>  <mapping xmlns="http://castor.exolab.org/">  <class name="com.springinaction.poker.webservice.  ➥ EvaluateHandRequest">  <map-to xml="EvaluateHandRequest" />  <field name="hand"  collection="array"  type="com.springinaction.poker.Card"  required="true">  <bind-xml name="card" node="element" />  </field>  </class>  </mapping>
  • 26. Handling endpoint exceptions  Java exceptions thrown by web servicesshould be converted into SOAP faults.  SoapFaultMappingExceptionResolver handles any uncaught exceptions that occur in the course of handling a message and produce an appropriate SOAP fault that will be sent back to the client.
  • 27. SoapFaultMappingExceptionResolver  <bean id="endpointExceptionResolver"  class="org.springframework.ws.soap.server.endpoint.  ➥ SoapFaultMappingExceptionResolver">  <property name="exceptionMappings">  <props>  <prop key="org.springframework.oxm.  ➥ UnmarshallingFailureException">  SENDER,Invalid message received</prop>  <prop key="org.springframework.oxm.  ➥ ValidationFailureException">  SENDER,Invalid message received</prop>  </props>  </property>  <property name="defaultFault“ value="RECEIVER,Server error" />  </bean>
  • 28. SoapFaultMappingExceptionResolver  The exceptionMappings property is configured with one or more SOAP fault definitions mapped to Java exceptions.  The key of each <prop> is a Java exception which needs to be translated to a SOAP fault.  The value of the <prop> is a two-part value where the first part is the type of fault that is to be created and the second part is a string that describes the fault.  SOAP faults come in two types: sender and receiver faults.  Sender faults indicate that the problem is on the client.  Receiver faults indicate that the message received from the client is having some processing problem.
  • 29. Serving WSDL files  DynamicWsdl11Definition is a special bean that MessageDispatcherServlet works with to generate WSDL from XML Schema.  DynamicWsdl11Definition works by reading an XML Schema definition, specified here as PokerTypes.xsd by the schema property.  DynamicWsdl11Definition reads an XML Schema definition specified by the schema property.  It looks through the schema file for any element definitions whose names end with Request and Response.  It assumes that those suffixes indicate a message that is to be sent to or from a web service operation and creates a corresponding <wsdl:operation> element in the WSDL it produces.
  • 30. DynamicWsdl11Definition  <bean id="poker"  class="org.springframework.ws.wsdl.wsdl11.  ➥ DynamicWsdl11Definition">  <property name="builder">  <bean class="org.springframework.ws.wsdl.wsdl11.builder.  ➥ XsdBasedSoap11Wsdl4jDefinitionBuilder">  <property name="schema" value="/PokerTypes.xsd"/>  <property name="portTypeName" value="Poker"/>  <property name="locationUri"  value="http://localhost:8080/Poker-WS/services"/>  </bean>  </property>  </bean>
  • 31. DynamicWsdl11Definition Config  <wsdl:portType name="Poker">  <wsdl:operation name="EvaluateHand">  <wsdl:input message="schema:EvaluateHandRequest"  name="EvaluateHandRequest">  </wsdl:input>  <wsdl:output message="schema:EvaluateHandResponse"  name="EvaluateHandResponse">  </wsdl:output>  </wsdl:operation>  </wsdl:portType>
  • 32. URL Mapping  A new <servletmapping> is added to web.xml so that MessageDispatcherServlet will serve WSDL definitions. <servlet-mapping> <servlet-name> poker </servlet-name> <url-pattern> *.wsdl </url-pattern> </servlet-mapping
  • 33. Predefined WSDL  SimpleWsdl11Definition serves the WSDL provided through the wsdl property.  <bean id="poker"  class="org.springframework.ws.wsdl.wsdl11.  ➥ SimpleWsdl11Definition">  <property name="wsdl" value="/PokerService.wsdl"/>  </bean>  MessageDispatcherServlet can rewrite the service’s location specified in static WSDL every time it is deployed.  It requires to set an <init-param> named transformWsdlLocations to true in MessageDispatcherServlet.  <servlet>  <servlet-name>poker</servlet-name>  <servlet-class>org.springframework.ws.transport.http.  ➥ MessageDispatcherServlet</servlet-class>  <init-param>  <param-name>transformWsdlLocations</param-name>  <param-value>true</param-value>  </init-param>  </servlet>
  • 34. Consuming Spring Web services  WebServiceTemplate is the centerpiece of Spring-WS’s client API.  It employs the Template design pattern to provide the ability to send and receive XML messages from message-centric web services.
  • 35. Configuring WebServiceTemplate  <bean id="webServiceTemplate"  class="org.springframework.ws.client.core.WebServiceTemplate">  <property name="messageFactory">  <bean class="org.springframework.ws.soap.saaj.  ➥ SaajSoapMessageFactory"/>  </property>  <property name="messageSender" ref="messageSender"/>  </bean>  <bean id="messageSender"  class="org.springframework.ws.transport.http.  ➥ HttpUrlConnectionMessageSender">  <property name="url"  value="http://localhost:8080/Poker-WS/services"/>  </bean>
  • 36. WebServiceTemplate  WebServiceTemplate constructs the message and sends it to the web service.  The object wired into the messageFactory property handles the task of constructing the message.  It should be wired with an implementation of Spring- WS’s WebServiceMessageFactory interface.  SaajSoapMessageFactory is the default message factory used by MessageDispatcherServlet.
  • 37. Message Factory Implementations Message factory What it does AxiomSoapMessageFactory Produces SOAP messages using the AXIs Object Model (AXIOM). Based on the StAX streaming XML API. Useful when working with large messages and performance is a problem. DomPoxMessageFactory Produces Plain Old XML (POX) messages using a DOM. Use this message factory when neither the client nor the service cares to deal with SOAP SaajSoapMessageFactory Produces SOAP messages using the SOAP with Attachments API for Java (SAAJ). Because SAAJ uses a DOM, large messages could consume a lot of memory. If performance becomes an issue, consider using AxiomSoapMessageFactory instead.
  • 38. WebServiceMessageSender  The messageSender property should be wired with a reference to an implementation of a WebServiceMessageSender.  The url property specifies the location of the service and it matches the URL in the service’s WSDL definition. Message sender What it does CommonsHttpMessageSender Sends the message using Jakarta Commons HTTP Client. Supports a preconfigured HTTP client, allowing advanced features such as HTTP authentication and HTTP connection pooling. HttpUrlConnectionMessageSender Sends the message using Java’s basic facilities for HTTP connections. Provides limited functionality.
  • 39. Sending a message  The sendAndReceive() method takes a java.xml.transform.Source and a java.xml.transform.Result as parameters to send the message.  The Source object represents the message payload to send to the web service.  The Result object is to be populated with the message payload returned from the service.  public boolean sendAndReceive(Source requestPayload, Result responseResult)  throws IOException
  • 40. WebServiceTemplate Implementation  public PokerHandType evaluateHand(Card[] cards) throws IOException {  Element requestElement =  new Element("EvaluateHandRequest");  Namespace ns = Namespace.getNamespace(  "http://www.springinaction.com/poker/schemas");  requestElement.setNamespace(ns);  Document doc = new Document(requestElement);  // Process the Request message  JDOMSource requestSource = new JDOMSource(doc);  JDOMResult result = new JDOMResult();  webServiceTemplate.sendAndReceive(requestSource, result);  Document resultDocument = result.getDocument();  Element responseElement = resultDocument.getRootElement();  Element handNameElement =  responseElement.getChild("handName", ns);  return PokerHandType.valueOf(handNameElement.getText());  }
  • 41. Marshalers on Client side  WebServiceTemplate provides marshalSendAndReceive() method for sending and receiving XML messages that are marshaled to and from Java objects.  public class MarshallingPokerClient implements PokerClient {  public PokerHandType evaluateHand(Card[] cards)  throws IOException {  EvaluateHandRequest request = new EvaluateHandRequest();  request.setHand(cards);  EvaluateHandResponse response = (EvaluateHandResponse)  webServiceTemplate.marshalSendAndReceive(request);  return response.getPokerHand();  }  }
  • 43. Marshaler Configuration  <bean id="webServiceTemplate"  class="org.springframework.ws.client.core.WebServiceTem plate">  <property name="messageFactory">  <bean class="org.springframework.ws.soap.saaj.  ➥ SaajSoapMessageFactory"/>  </property>  <property name="messageSender" ref="urlMessageSender"/>  <property name="marshaller" ref="marshaller" />  <property name="unmarshaller" ref="marshaller" />  </bean>
  • 44. Web Service Gateway Support  WebServiceGatewaySupport is a convenient support class that automatically provides a WebServiceTemplate to client classes that subclass it, without injecting with a WebServiceTemplate.  public class PokerServiceGateway  extends WebServiceGatewaySupport implements PokerClient {  public PokerHandType evaluateHand(Card[] cards)  throws IOException {  EvaluateHandRequest request = new EvaluateHandRequest();  request.setHand(cards);  EvaluateHandResponse response = (EvaluateHandResponse)  getWebServiceTemplate().marshalSendAndReceive(request);  return response.getPokerHand();  }  }