+
SOAP, WS-* Web
Services & Spring-WS
Bruno Rossi & Juha Rikkilä
PA165 Enterprise Java
2014-2015
+
Objectives and content
Get “the big picture” of
SOAP and WS-* related web
services
Have a look at how
contract-first development
can be used with Spring-WS
Some Definitions
WSDL & SOAP
Creating a SOAP Web
service
Web services development
Using Spring-WS
Objectives Content
+
W3C Definition of Web
Services
A Web service is a software system designed to
support interoperable machine-to-machine
interaction over a network. It has an interface
described in a machine processable format
(specifically WSDL). Other systems interact
with the Web service in a manner prescribed by
its description using SOAP messages, typically
conveyed using HTTP with an XML serialization
in conjunction with other Web-related
standards.
3
+
Web Service Description Language
(WSDL)
The Web Service Description Language (WSDL) is a
technical description of a Web Service
It mentions all interfaces available, with the relevant
information for the invocation (parameters, return
type...)
It is possible to generate:
the client code for accessing the Web Service
A WSDL file from Java source code
A Java source code skeleton from WSDL file
4
Thomas Erl definition
+
What are WS-* specifications
The term "WS-*" has become a commonly used abbreviation
that refers to the second-generation Web services
specifications. These are extensions to the basic Web
services framework established by first generation
standards represented by WSDL, SOAP, and UDDI.
The term "WS-*" became popular because the majority of
titles given to second-generation Web services
specifications have been prefixed with "WS-".
5
Thomas Erl definition
+ 6
Business process
Specifications
Management
Specifications
Presentation
Specifications
Metadata
Specifications
Reliability
Specifications
Security
Specifications
Resource
Specifications
Interoperability
issues
Dependencies
Transaction
Specification
s
Messaging
Specification
s
XML Specifications
SOAP
+ Web Services Standards for SOA
The Web Services Platform Architecture
Messaging
Quality
of Service
Transport
Description
Components
Transport
Interface + Bindings
Composite
XML Non-XML
Security
Policy
Discovery,Negotiation,Agreement
Atomic
OrchestrationOrchestration ProtocolsProtocols StateState
Reliable
Messaging
Transactions
Component
Model
Component
Model
7
+ Web Services Standards for SOA
The Web Services Platform Architecture
Messaging
Quality
of Service
Transport
Description
Components
Transport
Interface + Bindings
Composite
XML Non-XML
Security
Policy
Discovery,Negotiation,Agreement
Atomic
OrchestrationOrchestration ProtocolsProtocols StateState
Reliable
Messaging
Transactions
Component
Model
Component
Model
WS-RM
WSDL* WS-Policy*
HTTP, TCP/IP, SMTP, FTP, …
UDDI,WS-Addr,MetadataExch.,…
WS-C
WS-N* WS-RFWS-BPEL
WS-Security*
WS-AT
WS-BA
SOAP, WS-Addr* JMS, RMI/IIOP, ...
SCA
8
+ Web Services Standards for SOA
The Web Services Platform Architecture
Messaging
Quality
of Service
Transport
Description
Components
Transport
Interface + Bindings
Composite
XML Non-XML
Security
Policy
Discovery,Negotiation,Agreement
Atomic
OrchestrationOrchestration ProtocolsProtocols StateState
Reliable
Messaging
Transactions
Component
Model
Component
Model
WS-RM
WSDL* WS-Policy*
HTTP, TCP/IP, SMTP, FTP, …
UDDI,WS-Addr,MetadataExch.,…
WS-C
WS-N* WS-RFWS-BPEL
WS-Security*
WS-AT
WS-BA
SOAP, WS-Addr* JMS, RMI/IIOP, ...
SCA
9
+
SOAP, in general terms
10
Originally acronym for Simple Object Access Protocol,
now a common name
A communication protocol, designed to communicate via
Internet
Extends HTTP for XML messaging
Provides data transport for Web services
Exchanges complete documents or call a remote procedure
Is used for broadcasting a message
Is platform and language independent
Is the XML way of defining what information gets sent
and how
https://kore.fi.muni.cz/wiki/index.php/PA165/WebServices_(English)
An historical overview:
+
XML (Extensible Markup
Language)
11
Sets of rules for encoding documents to structure,
store, and transport data in a convenient way
Human-readable and machine-readable format
XML 1.0 Specification produced by the W3C
two current versions of XML.
XML 1.0, currently in its fifth edition, still
recommended for general use
XML 1.1, not very widely implemented and is recommended
for use only by those who need its unique features
+
XML, markup and content
12
markup
begins with character “<” and ends with a “>”,
strings of characters that are not markup are
content
tag(s)
start-tags; for example:
end-tags; for example:
empty-element tags; for example:
element, begins with a start-tag and ends with a
matching end-tag or consists only of an emptyelement
tag.
+
Schema and validation
13
well-formed, and may be valid.
Document contains a reference
to DTD,
DTD declares elements and
attributes, and specifies the
grammatical rules
XML processors
re validating or non-validating
If error discovered it is
reported, but processing may
continue normally
schema languages constrain
the set of elements in a
document,
attributes that are applied to
them,
the order in which they appear,
the allowable parent/child
relationships
XML Schema: XSD (XML Schema
Definition)
schema language, described by
the W3C
(successor of DTD =
Document Type Definition)
XML schema is more powerful
than DTDs
XSDs use an XML-based format,
so XML tools can be used
process them.
+
XML Messaging
SOAP 1.1 defined:
An XML envelope for XML messaging:
Headers + body.
An HTTP binding for SOAP messaging:
SOAP is “transport independent”.
A convention for doing RPC,
An XML serialization format for structured data.
SOAP Attachments adds:
How to carry and reference data attachments using in a
MIME envelope and a SOAP envelope.
14
+
SOAP Message
SOAP Message
Primary MIME
part (text/xml)
Attachment
Attachment
Attachment
SOAP Envelope
SOAP Header
SOAP Body
Fault
15
+
SOAP Message Envelope
Encoding information
Header
Optional
Contains context knowledge
• Security
• Transaction
Body
Methods and parameters
Contains application data
16
+ A SOAP Request
POST /temp HTTP/1.1
Host: www.somewhere.com
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "http://www…../temp"
……………..
HTTP
headers
and the
blank line
an XML document
“The SOAPAction HTTP request header field can be used to indicate the intent of
the SOAP HTTP request. The value is a URI identifying the intent. SOAP places no
restrictions on the format or specificity of the URI or that it is resolvable. An
HTTP client MUST use this header field when issuing a SOAP HTTP Request.”
Note: in SOAP 1.2, the SOAPAction header has been replaced with the “action”
attribute on the application/soap+xml media type (Content-Type:
application/soap+xml; charset=utf-8). But it works almost exactly the same way as
SOAPAction.
17
Source: Simple Object Access Protocol (SOAP) 1.1 specifications
+
...
...
...
soap-encoding
XML message structure
Version number
18
+
SOAP encoding
When SOAP specification
was written for the first
time, XMLSchema was not
available, so a common
way to describe messages
was defined.
Now SOAP encoding defines
it's own namespace as
http://schemas.xmlsoap.or
g/soap/encoding/ and a
set of rules to follow.
Rules of expressing
application-defined data
types in XML
Based on W3C XML Schema
Simple values
Built-in types from XML
Schema, Part 2 (simple
types, enumerations,
arrays of bytes)
Compound values
Structures, arrays,
complex types
19
http://www.tutorialspoint.com/soap/soap_encoding.htm
+
WS-Addressing (1/2)
WS-* specifications are inserted on top of SOAP
messaging
For example, looking at SOAP, there is no knowledge
about where the message is going, or how to return the
response or where to post an error message → this can
be problematic in case of asynchronous communication
WS-Addressing adds this information to the SOAP
envelope
20
See https://jax-ws.java.net/nonav/jax-ws-21-ea2/docs/why-wsaddressing.html
+
WS-Addressing (2/2)
Example
21
UniqueMessageIdentifier
http://somereceiving.clienthttp://somereceiving.server/ErrorHandlerhttp://somereceiving.server/HandlerURI
http://somereceiving.server/ACTION
+
SOAP, “closer to
the bit space”
Summing up:
SOAP, originally defined as
Simple Object Access Protocol, is
a protocol specification that is
used to exchange information in a
structured way – the protocol is
used for implementation of Web
Services as it builds on top of
an Application Layer protocol,
Hypertext Transfer Protocol
(HTTP) and Simple Mail Transfer
Protocol (SMTP).
SOAP is based on on Extensible
Markup Language (XML) for its
message format.
SOAP is usually the foundation
layer of a web services protocol
stack, to provide a basic
messaging framework.
+
SOAP with Attachments,
SOAP with Attachments API for Java (SAAJ)
SOAP with Attachments (SwA)
or MIME for Web Services
refers to the method of using
Web Services to send and
receive files using a
combination of SOAP and MIME,
primarily over HTTP.
Note that SwA is not a new
specification, but rather a
mechanism for using the
existing SOAP and MIME
facilities to perfect the
transmission of files using
Web Services invocations.
The SOAP with Attachments API
for Java or SAAJ provides a
standard way to send XML
documents over the Internet
from the Java platform.
SAAJ enables developers to
produce and consume messages
conforming to the SOAP 1.1
specification and SOAP with
Attachments note.
Developers can also use it to
write SOAP messaging
applications directly instead
of using JAX-RPC (obsolete)
or JAX-WS
23
SOAP with Attachments API for Java
The Java EE 5 Tutorial
http://docs.oracle.com/javaee/5/tutorial/doc/bnbhf.html
24
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.MessageFactory;
……….
public SimpleSAAJ {
public static void main(String args[]) {
try {
//Create a SOAPConnection
SOAPConnectionFactory factory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection =
factory.createConnection();
.................
// Close the SOAPConnection
connection.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Creating a
SOAP Conection
25
……………
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPBody;
import java.net.URL;
……………
//Create a SOAPMessage
SOAPMessageFactory messageFactory =
MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPHeader header = envelope.getHeader();
SOAPBody body = envelope.getBody();
header.detachNode();
Creating a
SOAP Message
26
Populate a
SOAP Message
27
//Create a SOAPBodyElement
Name bodyName = envelope.createName("GetElement"
"n", "http://localhost");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
//Insert Content
Name name = envelope.createName("symbol");
SOAPElement symbol = bodyElement.addChildElement(name);
symbol.addTextNode("Smith");
Smith
This will produce the SOAP envelope:
java.net.URL endpoint = new URL("localhost/addr");
SOAPMessage response = connection.call(message, endpoint);
That you can send with
+
Some Remarks
SOAP is not “what it used to be”, the name
remained, but the content has changed
SOAP term is often used as synonym for WS* web
service architecture, though it is one element of
it
SOAP is not just one element of WS*, it is used in
other context as well, even parallel with ReST web
services.
SOAP is often hidden from the developer, build
into tools in such a way that developer does not
have to deal with it at a detailed level.
28
+
Use of web services
Service
requestor
Client
Directory
UDDI
Service
provider Web
services
Find
(WSDL)
Publish
(WSDL)
Bind / invoke
(SOAP)
SOAP, WSDL, UDDI, and XML in all of them
29
+
UDDI (Universal Description,
Discovery and Integration)
30
UDDI is a platform-independent, Extensible Markup
Language (XML)-based registry by which businesses
worldwide can list themselves, plus a mechanism to
register and locate web service applications.
It is a standard supported by the Organization for the
Advancement of Structured Information Standards (OASIS)
In the original plans for the discoverability of web
services, a central role should have been played by UDDI
+
Public Registries (well, it used to
be...)
IBM Registration:
https://uddi.ibm.com/ubr/registry.html
inquiryURL= https://uddi.ibm.com/ubr/inquiryapi
publishURL= https://uddi.ibm.com/ubr/publishapi
HP Registration: http://uddi.hp.com
inquiryURL = http://uddi.hp.com/ubr/inquire
publishURL = https://uddi.hp.com/ubr/publish
Microsoft Registration: http://uddi.rte.microsoft.com
inquiryURL=http://uddi.rte.microsoft.com/inquire
publishURL=https://uddi.rte.microsoft.com/publish
SAP Registration: http://udditest.sap.com
inquiryURL=http://uddi.sap.com/UDDI/api/inquiry/
publishURL=https://uddi.sap.com/UDDI/api/publish/
31
UDDI has not been as successful as its creators had
expected. IBM, Microsoft, and SAP closed their public
UDDI nodes in 2006.
The OASIS UDDI Specification Technical Committee has
been dismantled as well.
Microsoft removed UDDI services from the Windows
Server operating system.
UDDI systems are most commonly found inside companies,
where they are used to dynamically bind client systems
to implementations. However, much of the more advanced
functionalities are not used.
+
Enabling technologies
Service discovery and publication
UDDI
Service description
WSDL
XML-Based message
SOAP
Network
HTTP, …………
32
+
WS*
Web
service
WSDL
Web
service
WSDL
SOAP
messages
SOAP
messages
.NETJ2EE
Platform or
middleware
clear
specifications of
the service
interface and the
data types in use
communication
protocol
independent
(platform,
programming
language)
interoperability.
33
+
SOAP engines
SOAP engine
Serialize
into a SOAP
message
De-
serialize
into native
data types
Message
Message
SOAP engine
Serialize
into a SOAP
message
De-
serialize
into native
data typesConsumer
/ Client
Provider
/ Server
A SOAP engine is a framework used in servers and clients that
facilitates:
1.Serializing objects from a programming language into SOAP messages
2.De-serializing SOAP messages into objects in a programming language,
i.e. creating appropriate data types and populating these with the
message content.
34
+
Simple Web Service Invocation
Manual Web
Service
Lookup
Invoke Web
Service
Write
Client
Code Remote Web Service
Publish
Web
Service
Service directory
1.
2. HTTP GET
3. WSDL file
4. SOAP request
5. SOAP response
35
JAXB
SOAP
SchemaJAX-P
JAX-RUDDI
WSDL
MTOM
SAAJ
JAX-WS
Java SE
6/7
XML
Includes
In build on
Binds to
Directory for
Provides
client access
for
Uses
Provides
high-level
API for
Provides
low-level
API
for
Improves
performance
of
binary
attachments
of
Transforms Java objects
to/from
Represented by
Processes Defines
36
+
An example (1/7)
Implementing a simple web service
with Java
1.Create the “service
endpoint interface”
Interface for web
service
2.Create the “service
implementation”
Class that
implements the
service
3.Create the “service
publisher”
Java supports web
services in core Java
JAX‐WS (Java API for
XML‐Web Services)
In full production
mode, one would use a
Java application server
such as Tomcat,
Glassfish, etc.
37
+
An example (2/7)
Service Endpoint Interface
package example.echo; // echo server
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService // This is a Service Endpoint Interface
@SOAPBinding(style = Style.RPC) // Needed for the WSDL
public interface EchoServer {
@WebMethod // This method is a service operation
String EchoMessage(String strMsg); }
38
+
An example (3/7)
Service Implementation
package example.echo;
import javax.jws.WebService;
/**
* The @WebService property endpointInterface links this class
* to example.echo.EchoServer.
*/
@WebService(endpointInterface = "example.echo.EchoServer")
public class EchoServerImpl implements EchoServer {
public String EchoMessage(String Msg) {
String capitalizedMsg;
System.out.println("Server: EchoMessage() invoked...");
System.out.println("Server: Message > " + Msg);
capitalizedMsg = Msg.toUpperCase();
return(capitalizedMsg);
}
}
39
+
An example (4/7)
Service Publisher
package example.echo;
import javax.xml.ws.Endpoint;
public class EchoServerPublisher {
public static void main(String[ ] args) {
Endpoint.publish("http://localhost:8080/ws", new
EchoServerImpl());
}
}
40
+
An example (5/7)
Deploying and testing
1. Compile the Java code
2. Run the publisher
java example.echo.EchoServerPublisher
3. Testing the web service with a browser
URL: http://localhost:8080/ws?wsdl
41
inding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
An Example (6/7)
WSDL for echo
service
42
package example.echo;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
class EchoClient {
public static void main(String argv[ ]) throws Exception {
if (argv.length < 1) {
System.out.println("Usage: java EchoClient \"MESSAGE\"");System.exit(1);}
String strMsg = argv[0];
URL url = new URL(”http://localhost:8080/ws?wsdl");
// Qualified name of the service:
QName qname = new
QName(“http://localhost/”,“EchoServerImplService");
Service service = Service.create(url, qname);
// Extract the endpoint interface, the service "port".
EchoServer eif = service.getPort(EchoServer.class);
System.out.println(eif.EchoMessage(strMsg));
}
}
An Example (7/7)
EchoClient
43
+
Web server
Server side
@WebServi
ce
Dispatche
r
SOAP
binding
JAXB
binding
Endpoint
Listener
SOAP
request
WSDL
Handler
chain
44
+
Developing a Web Service
WSDL
Service
contrac
t
war file
(or ear)
Server
code
@WebService
POJO class
Servlet-based
Deploymen
t
JAXB &
JAX-WS
files
45
+
Client-side programming
WSDL
Service
contract
wsimport
tool
Client
code
@WebService
Dynamic
proxy
You develop Client
which uses proxy to
call Web Service
46
+
Client-side programming
47
Usually two ways:
Contract last: first you create the code
for your web service, then the contract
(WSDL) is generated based on the code
Contract first: you start with the
creation of the contract for the web
service and then source code templates are
generated based on the contract
+
Client side
Web Service
WSDL
Endpoint
URL
Dynamic proxy
wsimport:
WSDL to
Java
parameters
JAXB
return
value
JAXB
XService
Javax.xml.ws.Service
SOAP
response
SOAP
request
extends
Service
Endpoint
Interface
(SEI)
Invocation
Handler
48
+
WSDL
49
A WSDL describes the point of contact for a service
provider, also known as the service endpoint or just
endpoint.
Provides a formal definition of the endpoint
interface
requestors wishing to communicate with the service
provider know exactly how to structure request
messages
Establishes the physical location (address) of the
service.
+
, the data types of input
and output data, used by the web
service
, messages to be
exchanged, used by the web
service
, the operations input
and output exposed by the web
service. Note: parameters are
represented as messages
, the coupling and
protocols used by the web
service. This is were for example
SOAP can be used as protocol
service location and
binding
WSDL elements
50
+ Web Service Example
// possible implementation of WS using
the wsimport tool:
// AddFunction.jws
public class AddFunction {
int addInt(int a, int b){
return(a+b);
}
A Web service AddFunction with operation addInt is known through its WSDL:
51
+
Generating a WSDL file from a
Java class
javac –cp . Calculator.java
java2wsdl –cp . –tn calculator –stn calculator –cn Calculator
-cp = classpath; -tn target namespace; -stn schema target
namespace; -cn class name
52
public class Calculator {
int add(int a, int b){
return(a+b);
}
}
+ Generating the service code skeleton
from the WSDL file
wsdl2java -ss -sd -uri Calculator.wsdl
-ss = server side; -sd = service descriptor
A src directory is created with the source code for
our server side files
A resources directory is created with the WSDL file
for the service and a service descriptor
(services.xml) file
A build.xml file is created in the current
directory, which will be used to create the ws
deployment file
53
+
Using WSDL
WSDL allows to define a contract between client
and server
Tool support to generate code from WSDL or WSDL from
code.
Allows to have standard service interfaces.
It can also be used for dynamic discovery with
UDDI registries
54
+
Summary
WS* standards are unevenly taken into use
Service orientation is well accepted
Several competing solutions, most notably WS* vs REST
that complement each other
Successful and accepted standardization process in
technical interfaces
Many technical complexities still remains
Emergence of new new solutions is frequent
although standards are mature and widely adopted
55
+
Spring-WS
A Spring “sub-project” that allows to simplify
WS-* development
You can reuse as such your Spring application
context and configuration in your application in
your SOA application
Plus, you get access to various WS-* standards
Note that Spring-WS only supports “contract first”
development
56
+
Spring-WS - Configuration
See http://projects.spring.io/spring-ws/
57
org.springframework.wsspring-ws-core2.2.0.RELEASE
Maven dependency
Webservice client bean
Spring-WS-Core depends
On Spring's Object/XML Mapping support
(OXM) module and on Spring XML module
+
Spring-WS – Service Client
See http://projects.spring.io/spring-ws/
58
public class WebServiceClient {
private static final String MESSAGE =
"Hello World";
private final WebServiceTemplate webServiceTemplate = new
WebServiceTemplate();
public void setDefaultUri(String defaultUri) {
webServiceTemplate.setDefaultUri(defaultUri);
}
// send to the configured default URI
public void simpleSendAndReceive() {
StreamSource source = new StreamSource(new
StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult(source,
result);
}
}
+
Spring-WS – Endpoints
59
@Endpoint
public class BookEndpoint {
private static final String NAMESPACE_URI = "http://muni.cz/pa165/soa";
private final BookRepository bookRepository;
@Autowired
public BookEndpoint(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getBookRequest")
@ResponsePayload
public GetBookResponse getBook(@RequestPayload GetBookRequest request) {
GetBookResponse response = new GetBookResponse();
response.setBook(bookRepository.getBookByTitle(request.getTitle()));
return response;
}
}
+
Spring-WS
Let's look at Spring-WS documentation, in
particular:
MessageDispatcher & MessageDispatcherServlet
Automatic WSDL exposure
Endpoints & Endpoint Mapping
Interceptors
Testing in Spring-WS
http://docs.spring.io/spring-
ws/docs/2.2.0.RELEASE/reference/htmlsingle
60