Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Summer 2006
2
Goals
Contents
● Introduction
● Hypertext Transfer Protocol
● Servlet Programming
● Simple Object Access Protocol
● SOAP with Attachments API for Java
● Web Services Description Language
● Java API for XML-based RPC
● Universal Description, Discovery and Integration
● Java API for XML Registries
4
Introduction
Definition
6
Motivation
Bottom-up view:
Web services allow remote procedure calls through firewalls
Top-down view:
Web services provide the means for application integration,
especially between business partners
Historical view:
Internet: network of computers
World Wide Web: network of documents
Web services: network of applications
Architecture
Web Server
8
Web Service Model
Port
Web services support the remote procedure call and the messaging
paradigm
Messaging:
– exchange of data or documents through generic interfaces
– asynchronous one-way communication
– queuing of messages
10
Service Oriented Architecture
Service
Registry
find publish
Service Service
Requestor Provider
invoke
11
Service
Registry
Universal Description, Web Services Description
Discovery and Integration Language describes the
defines the registry API interface of a service
W
I
D
SD
D
U
Service Service
SOAP
Requestor Provider
Simple Object Access
Protocol is used for
remote service invocations
12
Standards
W3C (www.w3.org):
– XML and XML Schema
– Simple Object Access Protocol (SOAP)
– Web Services Definition Language (WSDL)
OASIS (www.oasis-open.org)
– Universal Description, Discovery and Integration (UDDI)
– Electronic Business using XML (ebXML)
– Web Services Security (WSS)
WS-I (www.ws-i.org)
– Web Services Interoperability Profile
Java APIs
Application Code
Java API for
JAXR Registries
Java API for
XML-based
Messaging
JAXM JAX-RPC Java API for
XML-based
SOAP with SAAJ RPC
Attachments WSDL
API for Java SOAP
XML
14
References
● Ethan Cerami
Web Services Essential
O'Reilly, 2002
● Dave Chappell, Tyler Jewell
Java Web Services
O'Reilly, 2002
● Kim Topley
Java Web Services in a Nutshell
O'Reilly, 2003
● Richard Monson-Haefel
J2EE Web Services
Addison Wesley, 2003
● Steve Graham, Simeon Simeonov, Toufic Boubez
Building Web Services with Java
Sams, 2004
15
16
Hypertext Transfer Protocol
(HTTP)
17
Introduction
18
HTTP Transaction
Client Server
connect
request
n se
respo
n n ec t
disco
19
HTTP Request
20
Request Methods
21
22
Request Parameters
symbol=ABBN
23
HTTP Response
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 207
Date: Wed, 12 Jan 2006 08:20:00 GMT
Server: Apache-Coyote/1.1
<html>
<h1>Stock Quoter</h1>
...
</html>
24
Status Codes
Status codes inform the client about the status of a request and are
divided into five groups:
25
HTTP Headers
26
Media Types
27
HTTP implements the following features using headers and status codes:
– Caching
To improve performance, requested resources can be cached by the
web client or a server proxy
– Redirection
If a resource has moved, the web server responds with the new
location and the client resubmits a modified request
– Authentication
If a protected resource is requested, the web server asks the client for
a user authentication (name/password or certificate)
– Session Management
Cookies allow a web server to store information on the client's
machine and thus maintain a session
28
Servlet Programming
29
Introduction
● Servlets are Java classes that extend a web server in order to access
server applications via a request-response mechanism
● Servlets are managed by a so-called web container that
communicates with the servlets through standardized interfaces
Web Server
HTTP
Web Client Web Container
Server
Servlet
Application
30
Servlet Life Cycle
init() destroy()
Created Ready Destroyed
service()
31
ServletConfig
getInitParameter()
HttpSession
getAttribute()
setAttribute()
32
The Servlet API (cont.)
● HttpServlet
is an abstract base class for servlet implementations
● ServletConfig
is used by the web container to pass information to a servlet during
initialization
● HttpServletRequest
provides the data of an HTTP request to a servlet
● HttpServletResponse
assists a servlet in sending an HTTP response
● HttpSession
provides a way to store client-specific information across more than
one request
33
Servlet Initialization
After the web container created a servlet instance and before it delivers
client requests, the container calls the init method which can be used to
acquire resources
34
Service Methods
35
36
Servlet Finalization
When the web container decides to remove a servlet, it calls the destroy
method which can be used to release resources
37
Sessions
38
39
40
Simple Object Access Protocol
(SOAP)
41
Definition
42
Structure of a SOAP Message
43
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<getQuote xmlns="http://services.stocks.jws">
<symbol>ABBN</symbol>
</getQuote>
</env:Body>
</env:Envelope>
44
SOAP Messages with Attachments
SOAP Part
MIME wrapper
SOAP Envelope
SOAP Header
SOAP Body
Attachment
Parts MIME wrapper
Attachments may contain
Attachment any non-XML data
MIME wrapper
Attachment
45
SOAP Headers
46
SOAP Intermediaries
47
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header>
<authentication xmlns="http://services.stocks.jws"
env:actor="urn:security" env:mustUnderstand="1">
<user>jws</user>
<password>jws</password>
</authentication>
</env:Header>
<env:Body>
<getQuote xmlns="http://services.stocks.jws">
<symbol>ABBN</symbol>
</getQuote>
</env:Body>
</env:Envelope>
48
SOAP Faults
SOAP Fault
Default codes are VersionMismatch,
Fault Code MustUnderstand, Client and Server
49
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<env:Fault>
<faultcode>env:Server</faultcode>
<faultstring>NotFoundException: Symbol XXX not found</faultstring>
<detail>...</detail>
</env:Fault>
</env:Body>
</env:Envelope>
50
51
52
SOAP with Attachments API for Java
(SAAJ)
53
Introduction
54
Anatomy of a SAAJ Message
SOAPMessage
SOAPPart
SOAPEnvelope
SOAPHeader
SOAPHeaderElement
SOAPBody
SOAPBodyElement
SOAPElement Text
AttachmentPart
55
The following interfaces and classes are used to built the structure of a
SAAJ message
SOAPMessage SOAPPart
getMimeHeaders() getEnvelope()
getSOAPPart()
getSOAPHeader()
getSOAPBody()
createAttachmentPart()
writeTo() SOAPEnvelope
getHeader()
getBody()
SOAPHeader SOAPBody
addHeaderElement() addBodyElement()
addDocument()
addFault()
56
Interfaces and Classes (cont.)
SOAPElement Text
getElementName()
addChildElement()
getChildElements()
add/removeAttribute()
getAllAttributes()
addTextNode()
57
Creating a Message
import javax.xml.soap.*;
...
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage request = messageFactory.createMessage();
request.getSOAPHeader().detachNode();
SOAPBody body = request.getSOAPBody();
58
Adding Content to a Message
59
import javax.xml.parsers.*;
import org.w3c.dom.Document;
...
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse("document.xml");
body.addDocument(document);
60
Sending a Message
SOAPConnectionFactory connectionFactory =
SOAPConnectionFactory.newInstance();
SOAPConnection connection = connectionFactory.createConnection();
String endpoint = "http://distsys.ch/stocks/services/StockQuoterService";
SOAPMessage response = connection.call(request, endpoint);
connection.close();
61
62
Reading Fault Information
if (body.hasFault()) {
SOAPFault fault = body.getFault();
System.err.println(fault.getFaultCode());
System.err.println(fault.getFaultString());
Detail detail = fault.getDetail();
if (detail != null) {
Iterator iter = detail.getDetailEntries();
while (iter.hasNext()) {
DetailEntry entry = (DetailEntry)iter.next();
System.err.println(entry.getValue());
}
}
}
63
64
Web Services Description Language
(WSDL)
65
Introduction
66
Overview of WSDL
Message
67
68
The <definitions> Element
<definitions name="StockQuoterService"
xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://services.stocks.jws"
xmlns:tns="http://services.stocks.jws"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
...
</definitions>
69
<import namespace="http://services.stocks.jws"
location="StockQuoterTypes.xsd"/>
<import namespace="http://services.stocks.jws"
location="StockQuoterGeneric.wsdl"/>
70
The <types> Element
● The <types> element defines the data types that are used in the
messages of the web service
● The data types should be defined using the XML schema language
(either as abstract types or as elements)
<types>
<schema targetNamespace="http://services.stocks.jws"
xmlns="http://www.w3.org/2001/XMLSchema">
<complexType name="StockInfo">
<sequence>
<element name="company" type="string"/>
<element name="industry" type="string"/>
<element name="valor" type="string"/>
</sequence>
</complexType>
...
</schema>
</types>
71
<message name="getQuoteRequest">
<part name="symbol" type="xsd:string"/>
</message>
<message name="getQuoteResponse">
<part name="return" type="xsd:double"/>
</message>
<message name="NotFoundException">
<part name="fault" element="tns:NotFoundException"/>
</message>
...
72
The <portType> and <operation> Elements
<portType name="StockQuoter">
<operation name="getQuote" parameterOrder="symbol">
<input message="tns:getQuoteRequest"/>
<output message="tns:getQuoteResponse"/>
<fault name="NotFoundException"
message="tns:NotFoundException"/>
</operation>
...
</portType>
73
Operation Types
The appearance and order of the input and output messages determine
the type of an operation
Type Messages
Request-Response Input, Output, Fault
One-Way Input
Solicit-Response* Output, Input, Fault
Notification* Output
74
The <binding> Elements
● The <binding> elements define for each port type how the input and
output messages of its operations are mapped to concrete protocol
messages
● The additional elements necessary for a concrete binding are defined
by individual protocol specifications
75
<binding ...>
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="getQuote">
<soap:operation soapAction=""/>
<input><soap:body use="literal"/></input>
<output><soap:body use="literal"/></output>
<fault name="NotFoundException">
<soap:fault name="NotFoundException" use="literal"/>
</fault>
</operation>
</binding>
76
Operation Styles
Document:
– the body contains one or more child elements that correspond to
the parts of the corresponding message
– the part elements in the WSDL document point to schema
elements, therefore the content of the message body can easily be
validated
RPC:
– the body consists of a single (wrapper) element named for the
operation being invoked
– the wrapper element contains a child element for each parameter
defined by the parts of the corresponding message
77
Message Encoding
Encoded:
– data is serialized according to some encoding rules usually the
SOAP section 5 rules
– the elements in the SOAP message carry explicit type
qualification
Literal:
– data is serialized according to a schema definition usually
expressed in the XML schema language
– the types of the elements in the SOAP message implicitly rely on
the schema
78
The <service> and <port> Elements
<service name="StockQuoterService">
<port name="StockQuoterPort" binding="tns:StockQuoterBinding">
<soap:address location=
"http://distsys.ch/stocks/services/StockQuoterService"/>
</port>
</service>
79
80
Java API for XML-based RPC
(JAX-RPC)
81
Introduction
82
JAX-RPC Architecture
Client Service
Application Implementation
Stubs Ties
JAX-RPC JAX-RPC
Runtime Runtime
SOAP Messages
HTTP Transport
83
● The stub object has the same methods as the service implementation
class
● The client application invokes a stub method which is delegated to
the JAX-RPC runtime so that the appropriate SOAP message is sent
to the server
● On the server side, the tie object converts the received message into a
method call on the actual service implementation
● The stub and tie classes depend on the definition of the service
endpoint but can be generated by provider tools
84
Supported Data Types
85
86
Mapping of Value Types
<xsd:complexType name="StockInfo">
<xsd:sequence>
<xsd:element name="company" type="xsd:string"/>
<xsd:element name="industry" type="xsd:string"/>
<xsd:element name="valor" type="xsd:string"/>
<xsd:sequence>
<xsd:complexType>
87
Mapping of Arrays
<xsd:complexType name="ArrayOfString">
<xsd:complexContent>
<xsd:restriction base="soap:Array">
<xsd:attribute ref="soap:arrayType" arrayType="xsd:string[]"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="ArrayOfString">
<xsd:sequence>
<xsd:element name="item" type="xsd:string"
minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
88
Using WSDL with JAX-RPC
WSDL
Service
Client
Interface
Service
Stub Tie
Impl
89
<wsdl:portType name="StockQuoter">
<wsdl:operation name="getQuote" parameterOrder="symbol">
<wsdl:input message="tns:getQuoteRequest" .../>
<wsdl:output message="tns:getQuoteResponse" .../>
<wsdl:fault message="tns:NotFoundException" .../>
</wsdl:operation>
</wsdl:portType>
90
Client Types
91
Client Service
Request
Request-Response
Response
Request
One-Way
92
The Client-Side API
ServiceFactory Service
newInstance() getServiceName()
createService() getWSDLDocumentLocation()
getPort()
createCall()
Stub Call
_getProperty() setOperationName()
_setProperty() addParameter()
setReturnType()
setTargetEndpointAddress()
invoke()
invokeOneWay()
93
● The stub and interface classes can be generated from the WSDL
document at compile-time using provider tools
● At runtime the client obtains a stub from the service object and then
simply calls its methods
StockQuoter
ServiceLocator
StockQuoter
StockQuoter Stub
Stub
94
Static Stub Client (cont.)
95
● The service factory can be used to create a dynamic proxy from the
WSDL document at runtime which causes some overhead
● The Java interface of the web service is still needed at compile-time
ServiceFactory
DynamicProxy
Service
Client
StockQuoter
StockQuoter Stub
Stub
96
Dynamic Proxy Client (cont.)
97
ServiceFactory
Dynamic
Service
InvocationClient
Call
98
Dynamic Invocation Client (cont.)
99
Server-Side Architecture
For a web service deployed in a web container, the SOAP messages are
first handled by a servlet which locates the corresponding tie and passes
the message to it
Web Container
SOAP Service
Servlet Tie
Impl
100
Developing a Web Service with JAX-RPC
Remote
StockInfo
StockQuoter
NotFound
Exception
StockQuoter
Impl
101
import java.rmi.*;
102
User-Defined Parameter Types
103
User-Defined Exceptions
104
The Service Implementation
105
JAX-RPC does neither specify the exact content nor the format of the
deployment descriptor
106
Advanced Features
● SOAP headers
A web service can access SOAP headers by mapping the header
content to method parameters or by implementing message handlers
● Type serialization
Custom serializers and deserializers for types that are not supported
by JAX-RPC can be added to the stubs and ties
● SOAP attachments
JAX-RPC transparently places method parameters of some special
types like Image into SOAP attachments
● HTTP mechanisms
A web service hosted by a servlet can use HTTP sessions to store
client-specific information and basic HTTP authentication
107
Message Handlers
Handler Chain
JAX-RPC Service
SOAP
A B C Runtime Impl
108
Message Handler (cont.)
import javax.xml.rpc.handler.*;
110
111
112
Universal Description, Discovery and
Integration (UDDI)
113
Introduction
114
Uses of Registries
Registry
Search
Portal
Business Registry
Analyst
Software
Developer
115
Content Replication
Operator
Node
116
UDDI Specifications
117
Programmer's API
118
Data Structures
<businessEntity> <publisherAssertion>
2 *
Name, contact, Relationship between two
description, categories businesses
of a business
1
*
<businessService>
Set of services pro-
vided by the business
1
*
<bindingTemplate> <tModel>
1 *
Description and access Pointer to technical
point of a service specification (WSDL)
119
120
Example: Finding a Business (Request)
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<find_business generic="2.0" xmlns="urn:uddi-org:api_v2">
<name>%Bank%</name>
</find_business>
</env:Body>
</env:Envelope>
121
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<businessList generic="2.0" operator="jUDDI.org"
xmlns="urn:uddi-org:api_v2">
<businessInfos>
<businessInfo businessKey="fce05b44-...-25f207130b07">
<name>Universal Bank</name>
<serviceInfos>
<serviceInfo businessKey="fce05b44-...-25f207130b07"
serviceKey="fce05b44-...-e5a9681c7a53">
<name>Stock Quoter Service</name>
</serviceInfo>
</serviceInfos>
</businessInfo>
</businessInfos>
</businessList>
</env:Body>
</env:Envelope>
122
Categorization
123
Identifiers
124
Publishing to a UDDI Registry
Insertion/Update Deletion
<save_business> <delete_business>
<save_service> <delete_service>
<save_binding> <delete_binding>
<save_tModel> <delete_tModel>
<add_publisherAssertions>
<delete_publisherAssertions>
<set_publisherAssertions>
The save requests can be used to create new registry objects or to update
existing ones depending on the submitted key values
125
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Body>
<save_business generic="2.0" xmlns="urn:uddi-org:api_v2">
<authInfo>afd35d7cafd35d7</authInfo>
<businessEntity businessKey="">
<name>Universal Bank</name>
<businessServices>
<businessService serviceKey="">
<name>Stock Quoter Service</name>
<bindingTemplates>
<bindingTemplate bindingKey="">
<accessPoint URLType="http">
http://distsys.ch/stocks/services/StockQuoterService
</accessPoint>
</bindingTemplate>
</bindingTemplates>
</businessService>
</businessServives>
</businessEntity>
</save_business>
126
Authentication
Request:
<get_authToken generic="2.0" cred="jws" userID="jws"
xmlns="urn:uddi-org:api_v2"/>
Response:
<authToken generic="2.0" operator="jUDDI.org"
xmlns="urn:uddi-org:api_v2">
<authInfo>afd35d7cafd35d7</authInfo>
</authToken>
127
Errors
Example:
<env:Fault>
<faultcode>env:Server</faultcode>
<faultstring>...</faultstring>
<detail>
<dispositionReport generic="2.0" operator="jUDDI.org"
xmlns="urn:uddi-org:api_v2">
<result errno="10500">
<errInfo errCode="E_FATALERROR">...</errInfo>
</result>
</dispositionReport>
</detail>
</env:Fault>
128
Java API for XML Registries
(JAXR)
129
Introduction
130
Architecture
Registry Application
Browser Client
JAXR API
SOAP Messages
Registry Service
131
Information Model
1
Organization User
* 1 *
Service Person Name Postal Address
*
Service
Binding
*
Specification
Link
132
Registry Objects
Almost all of the interfaces of the JAXR API are derived from the
RegistryObject interface
RegistryObject
key
name *
Association
description
*
Classification
* External
Identifier
* External
Link
133
Programming Model
Connection
Registry
Service
Business Business
QueryManager LifeCycleManager
getRegistryObject() createOrganization()
findOrganizations() saveOrganizations()
findServices() deleteOrganizations()
... ...
134
Connecting to a Registry
import javax.xml.registry.*;
...
ConnectionFactory factory = ConnectionFactory.newInstance();
Properties props = new Properties();
String queryURL = "http://distsys.ch/juddi/inquiry";
props.setProperty("javax.xml.registry.queryManagerURL", queryURL);
String publishURL = "http://distsys.ch/juddi/publish";
props.setProperty("javax.xml.registry.lifeCycleManagerURL", publishURL);
factory.setProperties(props);
Connection connection = factory.createConnection();
135
136
Obtaining the Query and Life Cycle Manager
137
Finding an Organization
138
Getting Information on a Organization
import javax.xml.registry.infomodel.*;
...
for (Organization organization : organizations) {
System.out.println(organization.getName().getValue());
System.out.println(organization.getKey().getId());
}
139
A client can query the services that an organization offers and the
bindings associated with each service
140
Publishing an Organization
Organization organization =
lifeCycleManager.createOrganization("Universal Bank");
Collection<Organization> organizations = new ArrayList<Organization>();
organizations.add(organization);
BulkResponse response =
lifeCycleManager.saveOrganizations(organizations);
141
142
143
144