This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Understand the concept of web services Know the relevant standards of web services Know the different Java APIs used to realize web services
3
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
5
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
7
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 SOAP Library
HTTP SOAP
Web Service SOAP Engine
JDBC RMI EJB JMS
App Server DB Server
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 Client
Web Service Endpoint Interface SOAP HTTP
SOAP SMTP
Other Binding
Port
9
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 Requestor
Service Provider
invoke
locates a service and uses its description to invoke it
creates a service and publishes its description in a registry
11
Web Services Technologies
Service Registry
I D
L
U
D
SD
Service Requestor
Web Services Description Language describes the interface of a service
W
Universal Description, Discovery and Integration defines the registry API
SOAP
Service 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 XML-based Messaging SOAP with Attachments API for Java
Java API for Registries
JAXR JAXM
JAX-RPC SAAJ SOAP
Java API for XML-based RPC
WSDL
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 respo disco
se
n n ec t
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
Stock Quoter
... 24
Status Codes Status codes inform the client about the status of a request and are divided into five groups: Range 100–199 200–299 300–399
Meaning Informational Success Redirection
Examples 100 Continue 200 OK 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 General
The server program The length of the data The media type of the data 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 application/xml application/zip
pdf xml, dtd zip
audio/wav
au, snd
image/gif image/jpeg
gif jpeg, jpg, jpe
text/html text/plain
html, htm 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 Web Client
HTTP
Web Container Servlet
Server 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
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(""); out.println("
Stock Quoter
"); if (data != null) out.println(data[3]); else out.println("Symbol " + symbol + " not found"); out.println(""); } 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 SOAP Envelope SOAP Header SOAP Body
The envelope is the message container The optional header may contain processing or routing information 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> <symbol>ABBN
44
SOAP Messages with Attachments SOAP Part
MIME wrapper SOAP Envelope SOAP Header SOAP Body
Attachment Parts
MIME wrapper Attachment
Attachments may contain 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> <user>jws <password>jws <env:Body> <symbol>ABBN
48
SOAP Faults Processing errors of a request are reported through SOAP faults in the body of the response message
SOAP Fault Fault Code
Default codes are VersionMismatch, 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> env:ServerNotFoundException: Symbol XXX not found <detail>...
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
Interfaces and Classes (cont.) The following interfaces are used to construct the XML content of a SAAJ message Node get/setParentElement() get/setValue() detachNode()
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 SOAPBodyElement 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
Operation
Service
Binding
Port
Message 67
Structure of a WSDL Document <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" ...> Definition of data types <message> Definition of messages <portType> Definition of interfaces and operations Definition of bindings of interfaces and operations to protocols <service> Definition of the service and its location 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/"> ...
69
The Elements ●
●
An element allows to import data type definitions from a separate XML schema document An element allows to include another WSDL document and thus to separate the generic definition of a web service from its bindings and its location
70
The Element ●
●
The 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) <schema targetNamespace="http://services.stocks.jws" xmlns="http://www.w3.org/2001/XMLSchema"> <sequence> <element name="company" type="string"/> <element name="industry" type="string"/> <element name="valor" type="string"/> ... 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 name="getQuoteResponse"> <part name="return" type="xsd:double"/> <message name="NotFoundException"> <part name="fault" element="tns:NotFoundException"/> ... 72
The <portType> and 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"> ...
73
Operation Types The appearance and order of the input and output messages determine the type of an operation Type Request-Response One-Way Solicit-Response* Notification*
The 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
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 <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <soap:operation soapAction=""/> <soap:body use="literal"/> <soap:fault name="NotFoundException" use="literal"/> 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"/>
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 Application
Service Implementation
Stubs
Ties
JAX-RPC Runtime
JAX-RPC 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
Arbitrary data classes that meet certain conditions
Holder classes
Classes that contain an object reference which can be used as output parameters
Arrays
Single- and multi-dimensional arrays whose elements are supported data types
85
Mapping of Simple Types Java Type boolean byte short int long float double java.lang.String java.util.Calendar java.util.Date java.math.BigInteger java.math.BigDecimal
XML Type xsd:boolean xsd:byte xsd:short xsd:int xsd:long xsd:float xsd:double xsd:string xsd:dateTime xsd:dateTime xsd:integer 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 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 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:complexType name="ArrayOfString"> <xsd:sequence> <xsd:element name="item" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/> 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 Interface
Client
Stub
Tie
Service Impl
89
Java to WSDL Mapping ●
●
●
Java remote interfaces are mapped to <portType> elements with the same name Java methods are mapped to elements with corresponding input and output messages Java exceptions are mapped to 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" .../> 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 newInstance() createService()
Service getServiceName() getWSDLDocumentLocation() getPort() createCall()
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 Client
StockQuoter Service
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 Client
Service
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 InvocationClient
Service
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
Servlet
Tie
Service Impl
JAX-RPC does not specify how the servlet is to be implemented
100
Developing a Web Service with JAX-RPC 1. 2. 3. 4. 5.
Define the web service endpoint interface Implement and compile the web service Write a deployment descriptor to configure the web service Package the service code with the descriptor into a web archive 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 SOAP
A
B
C
JAX-RPC Runtime
Service 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 Analyst
Registry
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 Name, contact, description, categories of a business
2
*
1
*
Relationship between two businesses
1 *
Set of services provided by the business 1 *
Description and access point of a service
Pointer to technical 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
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> %Bank%
121
Example: Finding a Business (Response) <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> Universal Bank <serviceInfos> <serviceInfo businessKey="fce05b44-...-25f207130b07" serviceKey="fce05b44-...-e5a9681c7a53"> Stock Quoter Service 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 structures Taxonomy
tModel Name
Description
NAICS
ntis-gov:naics:1997
North American Industry Classification
UNSPSC
unspsc-org: unspsc:3-1
Universal Standard Products and Services Classification
ISO 3166
iso-ch:3166:1999
International standard geographical regions
Other
uddi-org: general_keywords
General-purpose associations
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 structures Identifier
tModel name
Description
D-U-N-S
dnb-com:D-U-N-S
Dun & Bradstreet D-U-N-S number
Thomas Register
thomasregister-com: supplierId
Identifiers for manufacturing 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 <save_business> <save_service> <save_binding> <save_tModel>
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"> afd35d7cafd35d7Universal BankStock Quoter Service http://distsys.ch/stocks/services/StockQuoterService
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: Response: afd35d7cafd35d7
127
Errors UDDI errors are reported as SOAP fault messages whose <detail> element contains a document Example: <env:Fault> env:Server... <detail> <errInfo errCode="E_FATALERROR">...
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 Browser
Application 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 Organization *
Service
1
User
1
*
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 description
* *
Association 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 QueryManager getRegistryObject() findOrganizations() findServices() ...
Business LifeCycleManager createOrganization() saveOrganizations() 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 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 organizations = new ArrayList(); 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);