Sei sulla pagina 1di 72

Java Web Services

Dr. Stephan Fischli

Summer 2006

2
Goals

● Understand the concept of web services


● Know the relevant standards of web services
● Know the different Java APIs used to realize web services

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

Web Services are self-contained, modular applications that can be


described, published, located and invoked over a network, generally the
World Wide Web.

(IBM, September 2000)

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 services use standardized protocols and data formats (e.g.


HTTP, XML, SOAP)
● The access of a web service is independent of its implementation and
deployment platform
● The service description provides all the details necessary to invoke a
web service

Web Server

Client Web App Server


Service JDBC DB Server
HTTP
SOAP RMI
SOAP SOAP EJB
Library Engine JMS

8
Web Service Model

● The endpoint interface defines the operations of a web service


● A binding maps the endpoint interface to a protocol stack
● A port defines the endpoint address that a client can use to access the
web service

Web Service Web Service


Client Endpoint Interface

SOAP SOAP Other


HTTP SMTP Binding

Port

RPC versus Messaging

Web services support the remote procedure call and the messaging
paradigm

Remote procedure call:


– invocation of remote code through specific interfaces
– synchronous request-response calls
– passing of application-level data structures

Messaging:
– exchange of data or documents through generic interfaces
– asynchronous one-way communication
– queuing of messages

10
Service Oriented Architecture

provides the infrastructure


to publish and find service
descriptions

Service
Registry

find publish

Service Service
Requestor Provider
invoke

locates a service and uses creates a service and publishes


its description to invoke it its description in a registry

11

Web Services Technologies

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

BEA, IBM, Microsoft, SAP


– Business Process Execution Language for Web Services
(BPEL4WS)
13

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

● HTTP is the protocol used by web clients and web servers to


communicate with each other
● HTTP allows to exchange different types of data
● HTTP is a stateless protocol, it does not maintain any information
from one request to the next
● HTTP exists in two versions:
– HTTP/1.0 (RFC 1945)
basic protocol
– HTTP/1.1 (RFC 2616)
support for persistent connections, absolute URLs and chunked
data transfer

18
HTTP Transaction

An HTTP transaction proceeds in four steps:


1. Client connects to the server at a designated port (usually 80)
2. Clients sends a request
3. Server replies with a response
4. Server disconnects from the client

Client Server

connect

request

n se
respo

n n ec t
disco

19

HTTP Request

An HTTP request consists of three sections:


– The request line contains a request method, a relative URL that
identifies the requested resource and the protocol version used by the
client
– Headers may provide information about the client or the data entity
– The optional body (which is separated by an empty line) contains the
data being sent to the server

GET /stocks/index.html HTTP/1.1


Accept: text/html, text/plain, image/gif, image/jpeg, */*
User-Agent: Mozilla/5.0
Connection: Keep-Alive
Host: distsys.ch

[body would come here]

20
Request Methods

HTTP supports the following request methods


– GET
Retrieves the resource identified by the request URL
– HEAD
Returns the headers identified by the request URL
– POST
Sends data of unlimited length to the web server
– PUT
Stores a resource under the request URL
– DELETE
Removes the resource identified by the request URL
– OPTIONS
Returns the HTTP methods supported by the server
– TRACE
Returns the header fields sent with the request

21

Uniform Resource Locator (URL)

A URL is an address that identifies a resource on the web


Syntax:
scheme://host:port/path?query
where
– scheme is the protocol used to connect to the server that hosts the
resource (e.g. http, ftp)
– host is the name or the address of the server
– port is the port on which the server is accepting connections
(e.g. 80, 21)
– path is the path of the resource on the server (relative to the
document root)
– query contains optional request parameters

A relative URL only contains the path and query information

22
Request Parameters

● Request parameters are used when addressing a server program and


usually originate from an HTML form
● Request parameters are URL encoded name-value pairs
● With a GET request, parameters are added to the request URL

GET /stocks/getQuote?symbol=ABBN HTTP/1.1

● With a POST request, parameters are submitted in the request body

POST /stocks/getQuote HTTP/1.1


...
Content-Type: application/x-www-form-urlencoded
Content-Length: 11

symbol=ABBN

23

HTTP Response

An HTTP response consists of three sections:


– The response line consists of the protocol version used by the server,
the status code and a description of the status
– Headers may provide information about the server or the data entity
– The body (which is separated by an empty line) contains the data
being sent to the client

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:

Range Meaning Examples


100–199 Informational 100 Continue
200–299 Success 200 OK
300–399 Redirection 301 Moved Permanently
304 Not Modified
400–499 Client Error 400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500–599 Server Error 500 Internal Server Error
501 Not Implemented

25

HTTP Headers

Headers provide additional information to the server or the client


Syntax: name: value
There are four categories of headers:

Category Examples Meaning


General Connection: close Connection options
Date: Wed, 12 Jan 2005 Current date and time
Request Accept: text/html, image/gif Acceptable media types
Host: distsys.ch The host and port of the URL
User-Agent: Mozilla/5.0 The client program
Response Server: Apache-Coyote/1.1 The server program
Entity Content-Length: 207 The length of the data
Content-Type: html/text The media type of the data
Location: http://www.bfh.ch The location of the resource

26
Media Types

Media types describe the format of the body data


Syntax: type/subtype
Servers usually determine the format of a document from its filename
suffix:

Media Type File Extensions


application/pdf pdf
application/xml xml, dtd
application/zip zip
audio/wav au, snd
image/gif gif
image/jpeg jpeg, jpg, jpe
text/html html, htm
text/plain txt
video/mpeg mpeg, mpg, mpe

27

Advanced HTTP Features

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

The life cycle of a servlet is controlled by the web container:


1. Load the servlet class
2. Create a servlet instance
3. Initialize the servlet instance
4. Invoke the service methods
5. Destroy the servlet instance

init() destroy()
Created Ready Destroyed

service()

31

The Servlet API

ServletConfig

getInitParameter()

HttpServletRequest HttpServlet HttpServletResponse

getHeader() init() setContentType()


getParameter() doGet() setContentLength()
getInputStream() doPost() getOutputStream()
getReader() doPut() getWriter()
getSession() doDelete()
destroy()

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

public class StockQuoterServlet extends HttpServlet {


private StockDB stockDB;
public void init() {
stockDB = StockDB.getInstance();
}
...
}

34
Service Methods

When the web container receives a request for a servlet, it creates a


request and response object and invokes the corresponding service
method of the servlet

public class StockQuoterServlet extends HttpServlet {


...
public void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
}
public void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
}
}

35

Service Methods (cont.)

The general pattern of a service method is to extract information from


the request, to access external resources and to populate the response
based on that information

public void doGet(


HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String symbol = request.getParameter("symbol");
Object[] data = stockDB.get(symbol);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<h1>Stock Quoter</h1>");
if (data != null)
out.println(data[3]);
else out.println("Symbol " + symbol + " not found");
out.println("</html>");
}

36
Servlet Finalization

When the web container decides to remove a servlet, it calls the destroy
method which can be used to release resources

public class StockQuoterServlet extends HttpServlet {


private StockDB stockDB;
...
public void destroy() {
stockDB = null;
}
}

37

Sessions

● If required, the web container creates a session object and associates


it with all requests coming from the same client
● Sessions are tracked by identifiers which are transferred between the
client and the server using cookies or URL rewriting

public void doGet(


HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
HttpSession session = request.getSession();
List<String> history = (List<String>)session.getAttribute("history");
if (history == null) {
history = new ArrayList<String>();
session.setAttribute("history", history);
}
...
}

38
39

40
Simple Object Access Protocol
(SOAP)

41

Definition

SOAP is an XML-based communication protocol that defines


– the structure of messages (envelope)
– bindings to transport protocols (e.g. HTTP)
– encoding rules for data types
– conventions for remote procedure calls
– a mechanism for error handling

42
Structure of a SOAP Message

Protocol specific wrapper


The envelope is the message
SOAP Envelope container

SOAP Header The optional header may contain


processing or routing information

SOAP Body The body contains arbitrary


XML data or a SOAP fault

43

Example of a SOAP Message

POST /stocks/services/StockQuoterService HTTP/1.1


Content-Type: text/xml; charset="utf-8"
Content-Length: 338
Host: distsys.ch
SOAPAction: ""

<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

SOAP Headers are not standardized and may contain additional


information such as
– authentication and authorization
– transaction management
– tracing and auditing
– payment information
– etc.

46
SOAP Intermediaries

● SOAP intermediaries allow to route a message to multiple recipients


● Header elements may be associated to a specific recipient by the actor
attribute
● The mustUnderstand attribute says whether the recipient is required
to process the corresponding header element

Requestor Intermediary Provider

47

A SOAP Message with Header

<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

Processing errors of a request are reported through SOAP faults in the


body of the response message

SOAP Fault
Default codes are VersionMismatch,
Fault Code MustUnderstand, Client and Server

Fault String Description of the error

Fault Actor Causer of the error (optional)

Detail Object Error details (optional)

49

A SOAP Message with Fault

<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

● SAAJ is a simple API for manipulating and sending SOAP messages


● SAAJ is especially suitable for accessing document oriented web
services
● JAXM which is based on SAAJ allows for asynchronous messaging
using messaging providers

54
Anatomy of a SAAJ Message

A SAAJ message consists of a hierarchy of objects representing the


different parts of the SOAP message and the XML elements

SOAPMessage

SOAPPart

SOAPEnvelope

SOAPHeader

SOAPHeaderElement

SOAPBody

SOAPBodyElement

SOAPElement Text

AttachmentPart

55

Interfaces and Classes

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.)

The following interfaces are used to construct the XML content of a


SAAJ message
Node
get/setParentElement()
get/setValue()
detachNode()

SOAPElement Text

getElementName()
addChildElement()
getChildElements()
add/removeAttribute()
getAllAttributes()
addTextNode()

57

Creating a Message

A newly created message contains a SOAPEnvelope with an empty


SOAPHeader and an empty SOAPBody element

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

Content can be added to a message by creating a SOAPBodyElement


and adding child elements to it

SOAPFactory soapFactory = SOAPFactory.newInstance();


String namespace = "http://services.stocks.jws";
Name bodyName = soapFactory.createName("getQuote", "", namespace);
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement element = bodyElement.addChildElement("symbol");
element.addTextNode("ABBN");

59

Adding a Document to a Message

Instead of setting the content of a message, it is possible to add an entire


DOM document to the body of a message

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

A message can be sent by creating a SOAPConnection and providing the


endpoint address of the web service

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

Reading the Content of a Message

The content of a message can be read by retrieving the SOAPBody-


Element and its child elements

SOAPBody body = response.getSOAPBody();


SOAPBodyElement bodyElement =
(SOAPBodyElement)body.getFirstChild();
SOAPElement element = (SOAPElement)bodyElement.getFirstChild();
System.out.println(element.getValue());

62
Reading Fault Information

If a message contains a fault, its information can be read by retrieving


the SOAPFault element from the body

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

● WSDL is an XML language that is used to describe the interface of a


web service
● WSDL is platform, protocol and programming language independent
● The WSDL document of a web service is published at a well-known
URL or in a registry
● Provider tools can parse WSDL and generate the code necessary to
implement or to access a web service

66
Overview of WSDL

A WSDL document describes a web service in terms of


– the operations that the web service provides
– the data types that each operation requires by its input and output
messages
– the binding that maps the input and output messages onto a
protocol
– the address at which the service can be accessed

Port Type Service

Operation Binding Port

Message

67

Structure of a WSDL Document

<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" ...>


<import .../>
<types>
Definition of data types
</types>
<message>
Definition of messages
</message>
<portType>
Definition of interfaces and operations
</portType>
<binding>
Definition of bindings of interfaces and operations to protocols
</binding>
<service>
Definition of the service and its location
</service>
</definitions>

68
The <definitions> Element

● The <definitions> element is the root element of a WSDL document


● The name given to the web service is for documentation purpose only
● The target namespace determines to which namespace the elements
belong used to describe the web service

<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

The <import> Elements

● An <import> element allows to import data type definitions from a


separate XML schema document
● An <import> element allows to include another WSDL document and
thus to separate the generic definition of a web service from its
bindings and its location

<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

The <message> Elements

● The <message> elements define the messages used by the operations


of the web service
● Each message may contain any number of part elements that
represent an item of data
● The data type of a message part is declared by an element or a type
attribute referencing a standard type or a user-defined type

<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

● The <portType> element defines the operations of a web service


● Each operation can have an input, an output and any number of fault
messages

<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

*Not supported by WS-I and JAX-RPC

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

<binding name="StockQuoterBinding" type="tns:StockQuoter">


...
<operation name="getQuote">
...
<input>...</input>
<output>...</output>
<fault name="NotFoundException">...</fault>
</operation>
...
</binding>

75

The SOAP Binding

The SOAP binding defines


– the transport protocol used to carry the SOAP messages
– the style of the operations (document or RPC)
– the value of the SOAPAction header used to access the service
– the appearance (body or header) and encoding (literal or encoded) of
each message

<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

The style of an operation determines how the SOAP messages are


constructed from the WSDL description

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

The encoding rules of a message determines the serialization format of


the message parts

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

● A <port> element maps a binding of a port type to a URI which can


be used to access it
● A <service> element groups together a set of related ports

<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

● JAX-RPC provides a simple way to implement RPC-based web


services and web service clients
● Programming with JAX-RPC is very similar to using Java RMI or
CORBA to create a distributed application
● JAX-RPC maps a service endpoint interface to a Java interface and
the web service operations to Java methods
● JAX-RPC services and clients are encoded using an XML-based
protocol and can be carried by different transport protocols

82
JAX-RPC Architecture

Client Service
Application Implementation
Stubs Ties
JAX-RPC JAX-RPC
Runtime Runtime
SOAP Messages
HTTP Transport

JAX-RPC supports interoperation with other SOAP-based RPC


implementations that use the same transport protocol

83

Stubs and Ties

● 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

Data Type Description


boolean, byte, short, int, long,
Java primitive types
float, double
Boolean, Byte, Short, Integer, Long,
Wrapper classes
Float, Double
String, Date, Calendar, BigInteger,
Standard Java classes
BigDecimal
Arbitrary data classes that meet certain
Value types
conditions
Classes that contain an object reference
Holder classes
which can be used as output parameters
Single- and multi-dimensional arrays
Arrays
whose elements are supported data types

85

Mapping of Simple Types

Java Type XML Type


boolean xsd:boolean
byte xsd:byte
short xsd:short
int xsd:int
long xsd:long
float xsd:float
double xsd:double
java.lang.String xsd:string
java.util.Calendar xsd:dateTime
java.util.Date xsd:dateTime
java.math.BigInteger xsd:integer
java.math.BigDecimal xsd:decimal

86
Mapping of Value Types

● Value types are Java classes with a public no-argument constructor


whose fields are public or have public accessor methods
● Value types are mapped to a <complexType> element with a
sequence compositor

public class StockInfo {


public String company;
public String industry;
public String valor;
}

<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

● Java arrays are mapped to a <complexType> element which is


derived from a SOAP array or has a sequence compositor with the
maxOccurs attribute set to unbounded

<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

● JAX-RPC allows to import a WSDL document and to generate the


corresponding Java code required to link a client to the service
● JAX-RPC can create a WSDL document from the Java interface
which can then be published at a well-known URL or in a registry

WSDL

Service
Client
Interface

Service
Stub Tie
Impl

89

Java to WSDL Mapping

● Java remote interfaces are mapped to <portType> elements with the


same name
● Java methods are mapped to <operation> elements with
corresponding input and output messages
● Java exceptions are mapped to <fault> elements

public interface StockQuoter extends Remote {


public double getQuote(String symbol)
throws NotFoundException, RemoteException;
}

<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

● Static stub client


The client invokes the web service through a stub which is generated
from the WSDL document of the service at development time
● Dynamic proxy client
The client invokes the web service through a dynamic proxy which is
generated at runtime
● Dynamic invocation interface client
The client invokes the web service dynamically by creating a call
object at runtime

91

Client Invocation Modes

● In the synchronous request-response mode, the client blocks until the


web service performs the requested operation
● In the asynchronous one-way mode, the client does not expect a
response from the web service and returns immediately (only
possible with the dynamic invocation interface)

Client Service

Request

Request-Response
Response

Request

One-Way

92
The Client-Side API

The service interface acts as a factory for generated stubs, dynamic


proxies and call objects for the dynamic invocation

ServiceFactory Service

newInstance() getServiceName()
createService() getWSDLDocumentLocation()
getPort()
createCall()

Stub Call

_getProperty() setOperationName()
_setProperty() addParameter()
setReturnType()
setTargetEndpointAddress()
invoke()
invokeOneWay()

93

Static Stub Client

● 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

StaticStub StockQuoter Service


Client Service

StockQuoter

StockQuoter Stub
Stub

94
Static Stub Client (cont.)

public class StaticStubClient {


static String endpoint = "http://distsys.ch/stocks/services/StockQuoterService";

public static void main(String[] args) throws Exception {


StockQuoterService service = new StockQuoterServiceLocator();
StockQuoter stockquoter =
service.getStockQuoterPort(new URL(endpoint));
double quote = stockquoter.getQuote("ABBN");
...
}
}

95

Dynamic Proxy Client

● 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.)

public class DynamicProxyClient {


static String endpoint = "http://distsys.ch/stocks/services/StockQuoterService";
static String namespace = "http://services.stocks.jws";

public static void main(String[] args) throws Exception {


ServiceFactory factory = ServiceFactory.newInstance();
QName serviceName = new QName(namespace, "StockQuoterService");
Service service =
factory.createService(new URL(endpoint + "?wsdl"), serviceName);
QName portName = new QName(namespace, "StockQuoterPort");
StockQuoter stockquoter =
(StockQuoter)service.getPort(portName, StockQuoter.class);
double quote = stockquoter.getQuote("ABBN");
...
}
}

97

Dynamic Invocation Client

● The dynamic invocation interface allows to access a web service even


if its operations are unknown until runtime
● The client creates a call object, configures all the needed parameters
and finally invokes it

ServiceFactory

Dynamic
Service
InvocationClient

Call

98
Dynamic Invocation Client (cont.)

public class DynamicInvocationClient {


static String endpoint = "http://distsys.ch/stocks/services/StockQuoterService";
static String namespace = "http://services.stocks.jws";

public static void main(String[] args) throws Exception {


ServiceFactory factory = ServiceFactory.newInstance();
QName serviceName = new QName(namespace, "StockQuoterService");
Service service = factory.createService(serviceName);
QName portName = new QName(namespace, "StockQuoterPort");
Call call = service.createCall(portName);
QName operationName = new QName(namespace, "getQuote");
call.setOperationName(operationName);
call.addParameter("symbol", XMLType.XSD_STRING,ParameterMode.IN);
call.setReturnType(XMLType.XSD_DOUBLE);
call.setTargetEndpointAddress(endpoint);
Double quote = (Double)call.invoke(new Object[] { "ABBN" });
...
}
}

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

JAX-RPC does not specify how the servlet is to be implemented

100
Developing a Web Service with JAX-RPC

1. Define the web service endpoint interface


2. Implement and compile the web service
3. Write a deployment descriptor to configure the web service
4. Package the service code with the descriptor into a web archive
5. Deploy the web archive into a web container (the tie class and the
WSDL document of the web service are generated)

Remote

StockInfo
StockQuoter
NotFound
Exception
StockQuoter
Impl

101

The Service Endpoint Interface

● A service endpoint interface must extend the Remote interface and


every method must declare to throw a RemoteException
● All method arguments are passed to the service implementation by
value

import java.rmi.*;

public interface StockQuoter extends Remote {


public String[] getSymbols() throws RemoteException;
public double getQuote(String symbol)
throws NotFoundException, RemoteException;
public StockInfo getInfo(String symbol)
throws NotFoundException, RemoteException;
}

102
User-Defined Parameter Types

● JAX-RPC supports the use of value types as method parameters


● For other object types custom serializers are needed which convert an
object to and from its XML representation

public class StockInfo {


private String company;
private String industry;
...
public StockInfo() {}
public String getCompany() { return company; }
public void setCompany(String company) {
this.company = company;
}
}

103

User-Defined Exceptions

● JAX-RPC allows methods to throw service-specific exceptions


● Such exceptions are derived from the standard Exception class and
each parameter of the constructor must have a corresponding get
method

public class NotFoundException extends Exception {


public NotFoundException(String message) {
super(message);
}
public String getMessage() {
return super.getMessage();
}
}

104
The Service Implementation

The service implementation (servant) must have a public no-argument


constructor and must implement the methods of the service endpoint
interface

public class StockQuoterImpl implements StockQuoter {


private StockDB stockDB;
public StockQuoterImpl () {
stockDB = StockDB.getInstance();
}
public double getQuote(String symbol) throws NotFoundException {
if (!stockDB.containsKey(symbol))
throw new NotFoundException("Symbol " + symbol + " not found");
Object[] data = stockDB.get(symbol);
return (Double)data[3];
}
...
}

105

The Deployment Descriptor

The deployment descriptor configures the web service and specifies:


– the Java classes that define and implement the web service
– the target namespace of the web service
– the mapping between Java and XML names
– message handlers that intercept the SOAP messages
– serializers and deserializers for the non built-in data types

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

● Message handlers are used to process SOAP messages, in particular


SOAP headers, e.g. for logging, validation, filtering, security
● Message handlers are grouped into handler chains which are inserted
into the processing path on the client side, the server side or both

Handler Chain
JAX-RPC Service
SOAP
A B C Runtime Impl

108
Message Handler (cont.)

● A message handler must implement the interface Handler


● The getHeaders method returns the names of the processed headers
● The return values of the handle methods indicate whether to continue
processing of the handler chain or not

import javax.xml.rpc.handler.*;

public class LogHandler implements Handler {


public QName[] getHeaders() { return null; }
public boolean handleRequest(MessageContext context) {
SOAPMessage message =
((SOAPMessageContext)context).getMessage();
message.writeTo(System.out);
return true;
}
public boolean handleResponse(MessageContext context) { ... }
public boolean handleFault(MessageContext context) { ... }
...
}
109

110
111

112
Universal Description, Discovery and
Integration (UDDI)

113

Introduction

● A registry contains information that allows businesses to discover the


web services of potential partners
● A provider company submits an entry to the registry and categorizes
it by including links to technical specifications or marketing
information
● An inquiring company searches the registry for information using
various criteria like name hints (white pages), categories of interest
(yellow pages) or technical information (green pages)

114
Uses of Registries

● Business analysts use a marketplace or search portal to browse the


businesses and services referenced by various registries
● Software developers use the registry's programming interface to
publish or to discover services

Registry
Search
Portal

Business Registry
Analyst

Software
Developer

115

The UDDI Business Registry

● The UDDI Business Registry (UBR) is a registry system built from


multiple nodes that have their data synchronized through replication
● Content inserted into the UBR is done at a single node which
becomes the master owner of that content

Content Replication

Operator
Node

116
UDDI Specifications

UDDI defines the following set of specifications:


● UDDI Replication
describes the data replication process and interfaces to which a
registry operator must conform
● UDDI Operators
outlines the behavior and operational parameters required by a node
operator (e.g. data persistence, completeness and integrity)
● UDDI Programmer's API
defines a set of functions for publishing and inquiring information
about services hosted by the registry
● UDDI Data Structures
covers the XML structures contained within the SOAP messages
defined by the programmer's API

117

Programmer's API

The UDDI programmer's specification describes two APIs which are


accessed using the same techniques but different XML documents:
● Inquiry API
locates information about a business, the services a business offers
and the specifications of those services
● Publishing API
is used to create, store or update information about a business and
requires an authentication of the client

The publishing API is usually accessed over HTTPS with a different


URL than the inquiry 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

Inquiring a UDDI Registry

The following messages allow a client to retrieve information from a


UDDI registry

Searching basic information Getting detailed information


<find_business> <get_businessDetail>
<find_service> <get_serviceDetail>
<find_binding> <get_bindingDetail>
<find_tModel> <get_tModelDetail>
<find_relatedBusinesses>

Each registry object has a universally unique identifier (UUID) which


must be provided as input to the get requests

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

Example: Finding a Business (Response)

<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

● Categorization allows data in a UDDI registry to be associated with


an industry, product or geographic code
● UDDI supports different categorization taxonomies which are
registered as <tModel> structures

Taxonomy tModel Name Description


North American Industry
NAICS ntis-gov:naics:1997
Classification
unspsc-org: Universal Standard Products
UNSPSC
unspsc:3-1 and Services Classification
International standard
ISO 3166 iso-ch:3166:1999
geographical regions
uddi-org:
Other General-purpose associations
general_keywords

123

Identifiers

● An identifier can be associated to a business or a specification to


uniquely identify it
● Like categorizations, identifiers can be used as part of a search and
are registered as <tModel> structures

Identifier tModel name Description


Dun & Bradstreet D-U-N-S
D-U-N-S dnb-com:D-U-N-S
number
Thomas thomasregister-com: Identifiers for manufacturing
Register supplierId and e-commerce companies

124
Publishing to a UDDI Registry

The following messages allow a program to publish information 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

Example: Publishing a Business

<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

Most operator nodes implement a name/password scheme that allows a


client to retrieve an authentication token which must be submitted as
input of all subsequent publishing requests

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

UDDI errors are reported as SOAP fault messages whose <detail>


element contains a <dispositionReport> document

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

● JAXR is a client-side API that provides a common interface to access


various types of registries like UDDI or ebXML registries
● JAXR transparently maps the information models of the different
registry implementations to its own information model
● Since an ebXML registry has more features than a UDDI registry,
each method in the JAXR API is assigned a capability level

130
Architecture

The mapping of the programming interface and information model to a


specific registry is performed by a JAXR provider

Registry Application
Browser Client

JAXR API

JAXR JAXR Other


UDDI ebXML JAXR
Provider Provider Provider

SOAP Messages

Registry Service

131

Information Model

A JAXR client views the registry as a set of Java objects

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

The BusinessQueryManager and BusinessLifeCycleManager interfaces


provide methods to search and to modify the content of a registry

Connection

Registry
Service

Business Business
QueryManager LifeCycleManager
getRegistryObject() createOrganization()
findOrganizations() saveOrganizations()
findServices() deleteOrganizations()
... ...

134
Connecting to a Registry

To use a registry, a client creates a connection factory, sets the URLs of


the registry and obtains a connection to the 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

Providing Authentication Information

Publishing to a registry requires that authentication credentials are set on


the connection

String username = "jws", password = "jws";


PasswordAuthentication authentication =
new PasswordAuthentication(username, password.toCharArray());
Set credentials = new HashSet();
credentials.add(authentication);
connection.setCredentials(credentials);

136
Obtaining the Query and Life Cycle Manager

From a connection a client can obtain a RegistryService interface which


provides references to the Manager interfaces

RegistryService registry = connection.getRegistryService();


BusinessQueryManager queryManager =
registry.getBusinessQueryManager();
BusinessLifeCycleManager lifeCycleManager =
registry.getBusinessLifeCycleManager();

137

Finding an Organization

The BusinessQueryManager interface allows to search for organizations


based on name patterns

Collection<String> namePatterns = new ArrayList<String>();


patterns.add("%Bank%");
BulkResponse response = queryManager.findOrganizations(
null, namePatterns, null, null, null, null);
Collection<Organization> organizations = response.getCollection();

138
Getting Information on a Organization

After a client has located an organization, it can obtain basic information


on that organization through the Organization interface

import javax.xml.registry.infomodel.*;
...
for (Organization organization : organizations) {
System.out.println(organization.getName().getValue());
System.out.println(organization.getKey().getId());
}

139

Getting Services and Service Bindings

A client can query the services that an organization offers and the
bindings associated with each service

Collection<Service> services = organization.getServices();


for (Service service : services) {
System.out.println(service.getName().getValue());
Collection<ServiceBinding> bindings = service.getServiceBindings();
for (ServiceBinding binding : bindings)
System.out.println(binding.getAccessURI());
}

140
Publishing an Organization

To publish an organization, a client creates an Organization object,


populates it with information and saves it to the registry

Organization organization =
lifeCycleManager.createOrganization("Universal Bank");
Collection<Organization> organizations = new ArrayList<Organization>();
organizations.add(organization);
BulkResponse response =
lifeCycleManager.saveOrganizations(organizations);

141

Adding Services and Service Bindings

A client can add services to an organization and specify different


bindings for each service

Service service = lifeCycleManager.createService("Stock Quoter Service");


organization.addService(service);

ServiceBinding binding = lifeCycleManager.createServiceBinding();


binding.setAccessURI(
"http://distsys.ch/stocks/services/StockQuoterService");
service.addServiceBinding(binding);

142
143

144

Potrebbero piacerti anche