Date post: | 11-Jan-2016 |
Category: |
Documents |
Upload: | sheila-french |
View: | 212 times |
Download: | 0 times |
Design of Distributed Software
2.7 Web Services2.7 Web Services
1. Introduction : Service Oriented Architectures2. Technology building blocks3. Java Web Services
Design of Distributed Software 2
Web ServiceWeb Service1. Introduction
“A Web service is a software application identified by a URI whose interfaces and binding are capable of being defined, described, and discovered by XML artifacts, and supports direct interactions with other software applications using XML-based messages via Internet-based protocols.”
Ser
vice
inte
rfac
e
Service implementation
Service implementation :-any application
- any programming language- any platform
- remotely available through web service provider
Service definition/interface :- defines the service- in XML-syntax- not necessarily on same machine as service implementation- includes :
- data types involved- supported method calls- network location
WEB SERVICE
XML-message
Design of Distributed Software 3
Service-Oriented ArchitecturesService-Oriented Architectures1. Introduction
VisionServices should be dynamically discoverable,Separation between service description and implementationAssemble application “ad hoc” based on discovered services
“Service-oriented architectures”
provider
requestor registry broker
• owner of the service• runs the service remotely• offers XML-description of service
• manages info repository on providers and services• white pages : business info on provider
(name , description, …)• green pages : info how to use the service
(policies, software bindings, …)• yellow pages :
key-word based search engine for services
• discovers and invokes service• can be person/application/service
Design of Distributed Software 4
Service-Oriented ArchitecturesService-Oriented Architectures1. Introduction
provider
requestor
registry
1 : publish2 : find
Alternative : no registry - direct publishing :
offline mechanism to locate service- use HTTP GET request on service provider
webserver
Dynamic publishing
•Query public/private registry•Specifies service type•Can include QoS requirements
3 : bind
• retrieve service description (how to access service ?)• default : from provider• alternative : from broker
• access the service
Design of Distributed Software 5
Web Service Technology Web Service Technology 2. Technology
• “Simple Object Access Protocol”• RPC-protocol for web services• used to access remote service
• “Web Services Description Language”• description of how to access web service• used to access remote service
• “Representational State Transfer”• XML directly over HTTP• URI per method
Design of Distributed Software 6
Web Service Technology Web Service Technology 2. Technology
ServletJSP/ASP
Web service
CORBARMI
HTTP
SOAP over HTTP/SMTP
IIOP • binary protocol• object oriented
• text protocol• not object oriented
• text protocol• object oriented
Design of Distributed Software 7
SOAP : philosophy and architectureSOAP : philosophy and architecture2. Technology
• text-oriented protocol (XML-messages) • messages can have attachments• object oriented (descendant from XML-RPC)
• specifies object attributes• methods to call
• easy access : on top of HTTP or SMTP (no blocking, clear text)
Layered approach SOAP RPC
Encoding Rules
Messaging Framework
HTTPBinding
SMTPBinding
HTTP SMTP
Syntax of SOAP-messages“Envelopes”
Mapping to transport protocol
Map RPC requestTo message(data-type -> XML)
Rules for SOAP-RPC
Design of Distributed Software 8
SOAP messagesSOAP messages2. Technology
SOAP envelope
SOAP header
SOAP body
SOAP block
SOAP block
SOAP block
SOAP block
…
…
Container for SOAP messageDefines relevant xml namespaces, encodings
Directives to SOAP-processorNot always forwarded by intermediary SOAP-nodesHeader content standardized by SOAP
Payload, message dataTo be processed by ultimate receiver
SOAP-processor = environment receiving/processing/forwarding SOAP-message(e.g. J2EE application server, .NET server, …)
Design of Distributed Software 9
SOAP message : request exampleSOAP message : request example2. Technology
POST /InStock HTTP/1.1 Host: www.stock.org Content-Type: application/soap+xml; charset=utf-8 Content-Length: nnn
<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.stock.org/stock"> <m:GetStockPrice> <m:StockName>IBM</m:StockName> </m:GetStockPrice> </soap:Body></soap:Envelope>
HTTP protocolbinding
Specify namespacesAnd encoding rules
RPC-specification
SOAP RPC request
stock.GetStockPrice(“IBM”)
Design of Distributed Software 10
SOAP message : reply exampleSOAP message : reply example2. Technology
HTTP/1.1 200 OK Content-Type: application/soap; charset=utf-8 Content-Length: nnn
<?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.stock.org/stock"> <m:GetStockPriceResponse> <m:Price>34.5</m:Price> </m:GetStockPriceResponse> </soap:Body></soap:Envelope>
“return 34.5”
SOAP RPC reply
Design of Distributed Software 11
SOAP message : parametersSOAP message : parameters2. Technology
<SOAP-ENV:Body><ns1:getPrice xmlns:ns1=http://mydomain/price SOAP-ENV:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/>
<isbn xsi:type=“xsd:string”>0103785920</isbn><title xsi:type:string”>SOAP and Web Services</title>
</ns1:getPrice></SOAP-ENV:Body>
Method declared as : getPrice(String, String)Invoked through : price.getPrice(“0103785920”,” SOAP and Web Services”)
Native Soap types :• string• base64Binary (binary formatted objects, e.g. JavaBeans)• integer, byte, short, int, long• decimal, float, double• boolean• dateTime, time, date, duration
Design of Distributed Software 12
WSDL1.1WSDL1.12. Technology
• XML grammar to specify collection of “access end points” (1 URL specifies a single access end point)
• designed to automate application-to-application interaction (or B2B interaction)• defines the communication protocol to be used at runtime
• message format• methods to be invoked• parameter lists, return types• …
• WSDL descriptions can be automatically generated for existing code• stub classes can be generated from WSDL descriptions
Web Services Description Language
Design of Distributed Software 13
A simple Web Service JAX-RPC A simple Web Service JAX-RPC
package random;import java.rmi.Remote;import java.rmi.RemoteException; public interface RandomServiceIF extends Remote { public String sayHello(String s) throws RemoteException; public int getRandomNumber(int max) throws RemoteException;}
RandomServiceIF.java
• interface MUST extend java.rmi.Remote• each method MUST throw java.rmi.RemoteException• can NOT be in default package• method arguments must obey to special rules (map to SOAP-types)
2. Technology
Design of Distributed Software 14
A simple Web Service JAX-RPC A simple Web Service JAX-RPC
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="RandomService" targetNamespace="urn:RandomService" xmlns:tns="urn:RandomService" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"> <types/> <message name="RandomServiceIF_getRandomNumber"> <part name="int_1" type="xsd:int"/></message> <message name="RandomServiceIF_getRandomNumberResponse"> <part name="result" type="xsd:int"/></message> <message name="RandomServiceIF_sayHello"> <part name="String_1" type="xsd:string"/></message> <message name="RandomServiceIF_sayHelloResponse"> <part name="result" type="xsd:string"/></message> <portType name="RandomServiceIF"> <operation name="getRandomNumber" parameterOrder="int_1"> <input message="tns:RandomServiceIF_getRandomNumber"/> <output message="tns:RandomServiceIF_getRandomNumberResponse"/></operation> <operation name="sayHello" parameterOrder="String_1"> <input message="tns:RandomServiceIF_sayHello"/> <output message="tns:RandomServiceIF_sayHelloResponse"/></operation></portType>
RandomService.wsdl
Automatically generated
2. Technology
Design of Distributed Software 15
A simple Web Service JAX-RPC A simple Web Service JAX-RPC
<binding name="RandomServiceIFBinding" type="tns:RandomServiceIF"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> <operation name="getRandomNumber"> <soap:operation soapAction=""/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:RandomService"/></input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:RandomService"/></output></operation> <operation name="sayHello"> <soap:operation soapAction=""/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:RandomService"/></input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded"
namespace="urn:RandomService"/></output></operation></binding> <service name="RandomService"> <port name="RandomServiceIFPort" binding="tns:RandomServiceIFBinding"> <soap:address location="REPLACE_WITH_ACTUAL_URL"/></port></service></definitions>
RandomService.wsdlAutomatically generated
2. Technology
Design of Distributed Software 16
A simple Web Service JAX-RPC A simple Web Service JAX-RPC http://localhost:8080/random/rs?wsdlAfter deployment to server
2. Technology
Design of Distributed Software 17
A simple Web Service JAX-RPC A simple Web Service JAX-RPC http://localhost:8080/random/rs?wsdlAfter deployment to server
2. Technology
Design of Distributed Software 18
WSDL1.1 : document structureWSDL1.1 : document structure2. Technology
<definitions> <import>* <types>
<schema></schema>* </types> <message>*
<part></part>* </message> <PortType>*
<operation>*<input></input><output></output><fault></fault>*
</operation> </PortType> <binding>*
<operation>*<input></input><output></output>
</operation> <binding> <service>*
<port></port>* </service></definitions>
<definitions>• container for service description• global declaration of document scope namespaces
<import>• similar to java-import
(modularization of WSDL docs)• include of namespaces (not file itself !)
<types>• contains definition of all datatypes used in messages• currently : XSD (XML Schema Definitions)
<message>• defines message structure
(for each part : type and name are defined)<portType>
• specifies legal operations for web service endpoint (=group of actions)• <operation> : method definition specifies
• method name• input message• output message• error message
Design of Distributed Software 19
WSDL1.1 : document structureWSDL1.1 : document structure2. Technology
<definitions> <import>* <types>
<schema></schema>* </types> <message>*
<part></part>* </message> <PortType>*
<operation>*<input></input><output></output><fault></fault>*
</operation> </PortType> <binding>*
<operation>*<input></input><output></output>
</operation> <binding> <service>*
<port></port>* </service></definitions>
<binding>• concrete protocol & data format spec for portType• standard soap-bindings available
<service>• defines URL for service endpoint• <port> = single access point for webservice• each port specifies
• name• binding info• URL of webservice (<soap:address> element)
Design of Distributed Software 20
WSDL1.1 : supported interactionsWSDL1.1 : supported interactions2. Technology
<operation>
Request – response<input> before <output> client server
1
2
Solicit - response<output> before <input>
client server
1
2
One-way (asynchronous)only <input> client server1
Notificationonly <output>
client server1
Design of Distributed Software 21
WSDL1.1: different styles WSDL1.1: different styles
RPC/encoded RPC/literal Document/encoded (not used) Document/literal
2. Technology
Design of Distributed Software 22
RPC/encodedRPC/encoded
<message name="myMethodRequest"> <part name="x" type="xsd:int"/> <part name="y" type="xsd:float"/></message><message name="empty"/>
<portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> <output message="empty"/> </operation></portType>
<binding .../> <!-- ... -->
2. Technology
<soap:envelope> <soap:body> <myMethod> <x xsi:type="xsd:int">5</x> <y xsi:type="xsd:float">5.0</y> </myMethod> </soap:body></soap:envelope>
public void myMethod(int x, float y);
-XSI types usually overhead
- no easy validation
- not WS-I compliant (WS-I defines
interoperability rules)
Design of Distributed Software 23
RPC/literalRPC/literal2. Technology
<message name="myMethodRequest"> <part name="x" type="xsd:int"/> <part name="y" type="xsd:float"/>;</message><message name="empty"/>
<portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> <output message="empty"/> </operation></portType>
<binding .../> <!-- ... -->
<soap:envelope> <soap:body> <myMethod> <x>5</x> <y>5.0</y> </myMethod> </soap:body></soap:envelope>
public void myMethod(int x, float y);
- no overhead from XSI types
- still no easy validation
-WS-I compliant
Design of Distributed Software 24
Document/literalDocument/literal2. Technology
<types> <schema> <element name="xElement" type="xsd:int"/> <element name="yElement" type="xsd:float"/> </schema></types>
<message name="myMethodRequest"> <part name="x" element="xElement"/> <part name="y" element="yElement"/></message><message name="empty"/>
<portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> <output message="empty"/> </operation></portType>
<binding .../> <!-- ... -->
<soap:envelope> <soap:body> <xElement>5</xElement> <yElement>5.0</yElement> </soap:body></soap:envelope>
public void myMethod(int x, float y);
- no operation name (difficult dispatching)
- easy validation (soap:body can be
defined in a schema)
- not WS-I compliant
Design of Distributed Software 25
Document/literal wrappedDocument/literal wrapped2. Technology
<types> <schema> <element name="myMethod"> <complexType> <sequence> <element name="x" type="xsd:int"/> <element name="y" type="xsd:float"/> </sequence> </complexType> </element> <element name="myMethodResponse"> <complexType/> </element> </schema></types><message name="myMethodRequest"> <part name="parameters" element="myMethod"/></message><message name="empty"> <part name="parameters" element="myMethodResponse"/></message>
<portType name="PT"> <operation name="myMethod"> <input message="myMethodRequest"/> <output message="empty"/> </operation></portType>
<binding .../> <!-- ... -->
<soap:envelope> <soap:body> <myMethod> <x>5</x> <y>5.0</y> </myMethod> </soap:body></soap:envelope>
public void myMethod(int x, float y);
- operation name is available
- easy validation (soap:body can be
defined in a schema)
- WS-I compliant
Design of Distributed Software 26
Summary WSDL stylesSummary WSDL styles
Use document/literal wrapped except: when overloaded operations
then: use document/literal unwrapped however: when several methods have same signature
then: use RPC/literal in case of data graphs (e.g. binary trees), literal style is
not an option, prefer RPC/encoded
public void myMethod(int x, float y);public void myMethod(int x);
public void myMethod(int x, float y);public void myMethod(int x);public void myOtherMethod(int x, float y);
2. Technology
Design of Distributed Software 27
WS-AddressingWS-Addressing WS-Addressing defines standard ways to route a
message over multiple transports or direct a response to a third party. Without WS-Addressing: a standard SOAP request is
sent over HTTP, the URI of the HTTP request serves as the message's destination. The message response is packaged in the HTTP response and received by the client over the HTTP connection.
For example, a client application might send a request over JMS and ask to receive the response through e-mail or SMS.
To enable these kinds of applications, WS-Addressing incorporates delivery, reply-to, and fault handler addressing information into a SOAP envelope.
2. Technology
Design of Distributed Software 28
WS-Addressing exampleWS-Addressing example
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://www.w3.org/2004/12/addressing"> <S:Header> <wsa:MessageID> http://... </wsa:MessageID> <wsa:ReplyTo> <wsa:Address>http://…</wsa:Address> </wsa:ReplyTo> <wsa:FaultTo> <wsa:Address>http://…</wsa:Address> </wsa:FaultTo> <wsa:To>http://…</wsa:To> <wsa:Action>http://…</wsa:Action> </S:Header> <S:Body> <!-- The message body of the SOAP request --> </S:Body></S:Envelope>
2. Technology
Design of Distributed Software 29
WSDL2.0WSDL2.0 W3C working draft since 2004, recommendation
since july 2007 rarely used for the moment: WSDL 1.1 still widely
used
support for WS-Addressing interface type instead of port type no operation overloading allowed
2. Technology
Design of Distributed Software
Web ServicesWeb Services1. Introduction : Service Oriented Architectures2. Technology building blocks3. Java Web Services4. Netbeans support for Web Services
Design of Distributed Software 31
Java Web ServicesJava Web Services3. Java WS
Web service front-end implemented through Servlet
Application server
Servlet
EJBs
Other resources
e.g. JCA-adapters (Java Connector Architecture)
JMS-resources (Java Message Service)
SOAP/HTTP
Servlet responsibilitiet :• SOAP Parsing• Resource lookup• Behaviour handling
Design of Distributed Software 32
JAX WS JAX WS Java EE 5 provides a robust platform on which web services can be
built and deployed
(previous JAX-RPC) Web service can be built either as:
Option 1: regular Java class Option 2: EJB 3 stateless session bean
Option 2 allows for use of declarative transactions and security. Advantage Option 1: can be run in a web container, no need for
application container. Both options can use annotations, definition of life cycle methods. Option 1 requires annotation processing in an external Annotation
Processing Tool (APT)
3. Java WS
Design of Distributed Software 33
EJB as a Web Service exampleEJB as a Web Service example
@WebService@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
@Statelesspublic class eBayBean implements eBayInterface {
@PersistenceContext private EntityManager em;public eBayBean() {}@WebMethod@WebResult(name = "bidNumber")
public Long addBid(@WebParam(name = "User") String userId,@WebParam(name = "Item") Long itemId,@WebParam(name = "Price") Double bidPrice) {
return persistBid(userId, itemId, bidPrice);}
private Long persistBid(String userId, Long itemId, Double bidPrice){}
}
3. Java WS
Design of Distributed Software 34
@WebService annotation options@WebService annotation options
@ WebService {String name() default "";String targetNamespace() default "";String serviceName() default "";String wsdlLocation() default "";String endpointInterface() default "";String portName() default "";
};
3. Java WS
Design of Distributed Software 35
@SOAPBinding annotation optionsannotation options
@ SOAPBinding {public enum Style {
DOCUMENT,RPC
};public enum Use {LITERAL,ENCODED
}; public enum ParameterStyle {
BARE,WRAPPED
};
Style style() default Style.DOCUMENT;Use use() default Use.LITERAL;ParameterStyle parameterStyle() default ParameterStyle.WRAPPED;
}
3. Java WS
Design of Distributed Software 36
@WebMethod annotationannotation
@WebService
@Stateless
public class eBayBean {
public Long addBid(..) {
}
@WebMethod(exclude = "true")
public Long persistBid(..) {
}
}
3. Java WS
Design of Distributed Software 37
@WebMethod annotation optionsannotation options
@WebMethod {
String operationName() default "";
String action() default "" ;
boolean exclude() default false;
};
3. Java WS
Design of Distributed Software 38
@WebParam annotationannotation
@WebMethod
public Long addBid(
@WebParam(name = "user",
mode = WebParam.Mode.IN) String userId, ...) {
...
}
3. Java WS
Design of Distributed Software 39
@WebParam annotation optionsannotation options
@WebParam {public enum Mode { IN, OUT, INOUT };String name() default "";String targetNamespace() default "";Mode mode() default Mode.IN;boolean header() default false;String partName() default "";
};
3. Java WS
Design of Distributed Software 40
@WebResult annotation + options@WebResult annotation + options
@WebMethod
@WebResult(name = "bidNumber")
public Long addBid(...){}
Options:
@WebResult {
String name() default "return";
String targetNamespace() default "";
boolean header() default false;
String partName() default "";
};
3. Java WS
Design of Distributed Software 41
Accessing a web service from an EJB
The client for the EJB web service can be any of the following types: Java application client Dynamic proxy Dynamic Invocation Interface (DII)
import javax.xml.ws.WebServiceRef ;
@WebServiceRef(wsdlLocation="http://localhost:8080/eBayService/eBayBean?WSDL")private static eBayService ebs;
public static void main(String [] args) {try {
eBayBean ebay = ebs.geteBayBeanPort();
System.out.println("Bid Successful, BidId Received is:“
+ebay.addBid(“test", 1001, 185,0 ));} catch (Exception ex) {
ex.printStackTrace();}
}
3. Java WS
Design of Distributed Software 42
EJB as a web service client
@Statelesspublic class AmazonOrderBean implements AmazonOrder {@WebServiceRef(AmazonDeliveryService.class)private AmazonDeliverySEI deliveryService;
public String checkOrderDeliverStatus(String shipId) {...String deliveryStatus =
deliveryService.checkDeliveryStatus(shipId);...
}}
3. Java WS