Jee course web services

71
Web Services Copyright © Oded Nissan 2009

description

Introduction to web services. Examples of SOAP based webservices. Introduction to REST

Transcript of Jee course web services

Page 1: Jee course web services

Web Services

Copyright © Oded Nissan 2009

Page 2: Jee course web services

Web Services

• Overview• The Web Services Architecture.• Web Services Development

– Exercises

• Restful Web Services• Streaming API for XML (StAX)• Summary

Copyright © Oded Nissan 2009

Page 3: Jee course web services

Overview

Copyright © Oded Nissan 2009

Page 4: Jee course web services

Web Service Definition (W3C)

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

Copyright © Oded Nissan 2009

Page 5: Jee course web services

Web Services

• Provide a way to connect heterogonous systems in a Language neutral, platform neutral manner.

• Use the HTTP protocol to pass messages in the SOAP protocol.

• Described by a Web Services Description language (WSDL) document.

• Vendors provide tools to generate web service clients from a WSDL.

• Web services can be registered and looked up in a UDDI directory.

Copyright © Oded Nissan 2009

Page 6: Jee course web services

Web Services

Copyright © Oded Nissan 2009

Page 7: Jee course web services

Web Services

Copyright © Oded Nissan 2009

Page 8: Jee course web services

Why do we need Web Services?

• Interoperability between heterogeneous systems.

• Self describing.• Automatic discovery• Use of standard platform neural protocols.• Scalable

Copyright © Oded Nissan 2009

Page 9: Jee course web services

When should we use Web Services ?

• When we need to access heterogeneous systems.

• When we expect our service to be accessed by different heterogeneous systems.

• When we want to define a simple standard API for our services that does not require proprietary client libraries.

Copyright © Oded Nissan 2009

Page 10: Jee course web services

The Web Services Architecture

Copyright © Oded Nissan 2009

Page 11: Jee course web services

Web Service Platform Elements

• HTTP – used as the transfer protocol.• SOAP (Simple Object Access Protocol)• UDDI (Universal Description, Discovery and

Integration)• WSDL (Web Services Description Language)

Copyright © Oded Nissan 2009

Page 12: Jee course web services

Web Services Architecture

Copyright © Oded Nissan 2009

Page 13: Jee course web services

What is SOAP ?• SOAP stands for Simple Object Access Protocol• SOAP is a communication protocol• SOAP is a format for sending messages• SOAP is designed to communicate via Internet • SOAP is platform independent• SOAP is language independent• SOAP is based on XML• SOAP is simple and extensible• SOAP allows you to get around firewalls• SOAP is a W3C standard

Copyright © Oded Nissan 2009

Page 14: Jee course web services

SOAP• SOAP is an XML-based protocol that can be carried over any

transport mechanism capable of delivering a byte stream. In practice, SOAP messages are usually exchanged between clients and services that are resident in web containers and are typically encapsulated inside an HTTP request or response message

• A basic SOAP message consists of an envelope that may contain any number of headers plus a body. These parts are delimited by XML elements called Envelope, Header, and Body, which belong to a namespace defined by the SOAP specification.

Copyright © Oded Nissan 2009

Page 15: Jee course web services

The SOAP Message Structure

A SOAP message is an ordinary XML document containing the following elements:

• An Envelope element that identifies the XML document as a SOAP message

• A Header element that contains header information• A Body element that contains call and response

information• A Fault element containing errors and status

information

Copyright © Oded Nissan 2009

Page 16: Jee course web services

The SOAP Message Structure

Copyright © Oded Nissan 2009

Page 17: Jee course web services

The SOAP Envelope ElementThe required SOAP Envelope element is the root element of a

SOAP message. This element defines the XML document as a SOAP message.

Example<?xml version="1.0"?>

<soap:Envelopexmlns:soap="http://www.w3.org/2001/12/soap-envelope"soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> ... Message information goes here ...</soap:Envelope>

Copyright © Oded Nissan 2009

Page 18: Jee course web services

The SOAP Header ElementThe optional SOAP Header element contains application-specific

information (like authentication, payment, etc) about the SOAP message.

Example:<?xml version="1.0"?>

<soap:Envelopexmlns:soap="http://www.w3.org/2001/12/soap-envelope"soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"><soap:Header> <m:Trans xmlns:m="http://www.w3schools.com/transaction/"

soap:mustUnderstand="1">234 </m:Trans></soap:Header>

Copyright © Oded Nissan 2009

Page 19: Jee course web services

The SOAP Body ElementThe required SOAP Body element contains the actual SOAP

message intended for the ultimate endpoint of the message. Immediate child elements of the SOAP Body element may be

namespace-qualified.Example<?xml version="1.0"?>

<soap:Envelopexmlns:soap="http://www.w3.org/2001/12/soap-envelope"soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"><soap:Body> <m:GetPrice xmlns:m="http://www.w3schools.com/prices"> <m:Item>Apples</m:Item> </m:GetPrice></soap:Body></soap:Envelope>

Copyright © Oded Nissan 2009

Page 20: Jee course web services

The SOAP fault Element

• The optional SOAP Fault element is used to indicate error messages.

• If a Fault element is present, it must appear as a child element of the Body element. A Fault element can only appear once in a SOAP message.

• The Fault element contains the following attributes:– <faultcode> A code for identifying the fault – <faultstring> A human readable explanation of the fault – <faultactor> Information about who caused the fault to happen – <detail> Holds application specific error information related to the

Body element

Copyright © Oded Nissan 2009

Page 21: Jee course web services

SOAP MessageExample Request:<?xml version="1.0"?>

<soap:Envelopexmlns: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.example.org/stock">  <m:GetStockPrice>    <m:StockName>IBM</m:StockName>  </m:GetStockPrice></soap:Body></soap:Envelope>

Copyright © Oded Nissan 2009

Page 22: Jee course web services

SOAP MessageExample Response:

<?xml version="1.0"?><soap:Envelopexmlns: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.example.org/stock">  <m:GetStockPriceResponse>    <m:Price>34.5</m:Price>  </m:GetStockPriceResponse></soap:Body>

</soap:Envelope>

Copyright © Oded Nissan 2009

Page 23: Jee course web services

SOAP Styles• RPC Style

The RPC style specifies that the <soap:body> contains an element with the name of the Web method being invoked. This element in turn contains an entry for each parameter and the return value of this method.

• Document Style

The message parts appear directly under the <soap:body> element. There are no SOAP formatting rules for what the <soap:body> contains. The server application is responsible for mapping the server objects (parameters, method calls, and so forth) and the values of the XML documents.

Copyright © Oded Nissan 2009

Page 24: Jee course web services

What is WSDL ?

• WSDL is an XML-based language for locating and describing Web services.

• WSDL stands for Web Services Description Language• WSDL is based on XML• WSDL is used to describe Web services• WSDL is used to locate Web services• WSDL is a W3C Standard• Used by Web Services tools to generate client code.

Copyright © Oded Nissan 2009

Page 25: Jee course web services

WSDL Structure

• The types element declares complex data types and elements that are used elsewhere in the WSDL document.

• Import element is similar to an import element in an XML schema document; it's used to import WSDL definitions from other WSDL documents.

• The Message element describes the message's payload using XML schema built-in types, complex types, or elements that are defined in the WSDL document's types element, or defined in an external WSDL document the import element refers to.

Copyright © Oded Nissan 2009

Page 26: Jee course web services

WSDL Structure• The portType and operation elements describe a Web

service's interface and define its methods. A portType and its operation elements are analogous to a Java interface and its method declarations. An operation element uses one or more message types to define its input and output payloads.

• The binding element assigns a portType and its operation elements to a particular protocol (for instance, SOAP 1.1) and encoding style.

• The service element is responsible for assigning an Internet address to a specific binding.

• The documentation element explains some aspect of the WSDL document to human readers. Any of the other WSDL elements may contain documentation elements.

Copyright © Oded Nissan 2009

Page 27: Jee course web services

WSDL Example<?xml version="1.0" encoding="UTF-8"?>

<definitions name="BookQuoteWS" targetNamespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" xmlns:soapbind="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"> <!-- message elements describe the input and output parameters --> <message name="GetBookPriceRequest">

<part name="isbn" type="xsd:string" /> </message> <message name="GetBookPriceResponse">

<part name="price" type="xsd:float" /> </message> <!-- portType element describes the abstract interface of a Web service --> <portType name="BookQuote">

<operation name="getBookPrice"> <input name="isbn" message="mh:GetBookPriceRequest"/> <output name="price"

message="mh:GetBookPriceResponse"/> </operation>

</portType>

Copyright © Oded Nissan 2009

Page 28: Jee course web services

WSDL Example<!-- binding tells us which protocols and encoding styles are used -->

<binding name="BookPrice_Binding" type="mh:BookQuote"> <soapbind:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/><operation name="getBookPrice">

<soapbind:operation style="rpc" soapAction= "http://www.Monson- Haefel.com/jwsbook/BookQuote/GetBookPrice"/>

<input> <soapbind:body use="literal"

namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" />

</input> <output> <soapbind:body use="literal" namespace="http://www.Monson-Haefel.com/jwsbook/BookQuote" /> </output>

</operation> </binding>

Copyright © Oded Nissan 2009

Page 29: Jee course web services

WSDL Example<!-- service tells us the Internet address of a Web service --> <service name="BookPriceService">

<port name="BookPrice_Port" binding="mh:BookPrice_Binding"> <soapbind:address location= "http://www.Monson-Haefel.com/jwsbook/BookQuote" />

</port> </service> </definitions>

Copyright © Oded Nissan 2009

Page 30: Jee course web services

UDDI

• UDDI is a directory service where companies can register and search for Web services.

• UDDI stands for Universal Description, Discovery and Integration

• UDDI is a directory for storing information about web services

• UDDI is a directory of web service interfaces described by WSDL

• UDDI communicates via SOAP

Copyright © Oded Nissan 2009

Page 31: Jee course web services

UDDI

Copyright © Oded Nissan 2009

Page 32: Jee course web services

WS-I• The Web Services Interoperability Organization (WS-

I) is an industry consortium that promotes interoperability amongst the stack of web services specs. WS-I does not define standards for web services; rather, it creates guidelines and tests for interoperability.

• WS-I defines a profile which is set of named web services specifications at specific revision levels, together with a set of implementation and interoperability guidelines recommending how the specifications may be used to develop interoperable web services.

Copyright © Oded Nissan 2009

Page 33: Jee course web services

WS-I Basic Profile

• The Basic Profile is the heart of web services interoperability, vendors need to be compliant with the Basic Profile in order to assure interoperability.

• The Basic Profile is needed because the specifications are too broad. The Basic Profile coordinates the use of technologies like XML, SOAP, WSDL, and UDDI.

• The Basic Profile is currently at version 1.1 of the spec. Version 2.0 is currently being written.

Copyright © Oded Nissan 2009

Page 34: Jee course web services

The Java Web Services Stack

• Web Services are a W3C standard. The Java implementation however, varies.

• In order to implement Web Services, Java must use Java specific APIs. These APIs have been standardized in the Java world but are not part of the Web Services spec.

• The current Java Web Services implementation standard is JAX-WS 2.0

Copyright © Oded Nissan 2009

Page 35: Jee course web services

The Java Web Services Stack

• Some popular Java Web Services implementations:– Axis (Apache) – supports the older standards.– Axis2 (Apache) – supports JAX-WS and REST.– JBoss-WS– Metro (Glassfish)

Copyright © Oded Nissan 2009

Page 36: Jee course web services

JAX-WS (Java API for XML Web Services)• JAX-WS is a technology for building web services and

clients that communicate using XML. JAX-WS allows developers to write message-oriented as well as RPC-oriented web services.

• The JAX-WS runtime system converts the API calls and responses to and from SOAP messages, so the developer does not need to parse the SOAP messages.

• JAX-WS replaces JAX-RPC in the JEE 5 standard.

Copyright © Oded Nissan 2009

Page 37: Jee course web services

JAX-WS

Copyright © Oded Nissan 2009

Page 38: Jee course web services

JAXB (Java XML Binding)

• Allows converting Java object to and from XML.

• Used by the Web Services implementation in order to do the XML data binding.

• JAXB uses compilers to generate either Java classes from an XML schema or an XML schema from Java classes.

Copyright © Oded Nissan 2009

Page 39: Jee course web services

JAXB Binding Process

Copyright © Oded Nissan 2009

Page 40: Jee course web services

JAXR

• JAXR is the Java API for XML Registries. Provides access to UDDI registries.

• JAXR gives developers the ability to write registry client programs that are portable across different target registries.

• JAXR consists of:– JAXR client - client program that uses the JAXR API to

access a business registry via a JAXR provider. – JAXR provider - an implementation of the JAXR API that

provides access to a specific registry provider or to a class of registry providers that are based on a common specification.

Copyright © Oded Nissan 2009

Page 41: Jee course web services

SaaJ

• SOAP with Attachments API for Java• Use this API when you want to write SOAP

messages directly rather than use JAX-WS.• Using SaaJ we can create a dynamic Web

Services client without the need to generate stubs from a WSDL document.

• The SaaJ API extends the DOM API for parsing XML.

Copyright © Oded Nissan 2009

Page 42: Jee course web services

SOAP Message with Attachments.

Copyright © Oded Nissan 2009

Page 43: Jee course web services

Web Services Development

Copyright © Oded Nissan 2009

Page 44: Jee course web services

Development Models

• Bottom-Up– Develop the service implementation.– Generate supporting classes.– Generate WSDL.– Deploy

• Top-Down– Write the WSDL– Generate service implementation – Generate supporting classes.– Develop the service implementation.– Deploy

Copyright © Oded Nissan 2009

Page 45: Jee course web services

Development Models

• Client Development– Get the WSDL for the Web Service.– Generate proxy classes from WSDL.– Write client code to activate proxy.– Deploy

Copyright © Oded Nissan 2009

Page 46: Jee course web services

Developing a Web Service with JAX-WS• Write the service implementation.• Add annotations to the service

implementation.• Generate WSDL and supporting classes using

wsgen.• Publish the service using the EndPoint class.

Copyright © Oded Nissan 2009

Page 47: Jee course web services

Developing a Web Service Client with JAX-WS• Get the service’s WSDL file• Generate client stubs from the WSDL using

the wsimport utility.• Write client code that invokes the generated

stubs.

Copyright © Oded Nissan 2009

Page 48: Jee course web services

Developing a Web Service with JAX-WSExamine code sample in Eclipse…

Copyright © Oded Nissan 2009

Page 49: Jee course web services

Exercise

Copyright © Oded Nissan 2009

Page 50: Jee course web services

Restful Web Services

Copyright © Oded Nissan 2009

Page 51: Jee course web services

What is REST ?

• Stands for Representational State transfer.• Defined as software architectural style for

distributed hypermedia systems like the world wide web.

• Used to describe any simple interface that user XML over HTTP without using SOAP.

• Make use of the existing web infrastructure to implement platform neutral client-server services.

Copyright © Oded Nissan 2009

Page 52: Jee course web services

REST Features

• Use HTTP protocol commands (GET, PUT,DELETE etc.) to specify the operation type.

• Use URL parameters as method parameters.• The URI specifies the web service to invoke.

Copyright © Oded Nissan 2009

Page 53: Jee course web services

REST Benefits

• A simpler lightweight framework. • No WSDL and SOAP complexity and

compatibility issue.• Ease of use.• Less dependency on 3rd party libraries.

Copyright © Oded Nissan 2009

Page 54: Jee course web services

REST

Copyright © Oded Nissan 2009

Page 55: Jee course web services

REST and HTTP

• HTTP commands represent CRUD operations:– GET – retrieve a resource.– POST – create a new resource.– PUT – update an existing resource.– DELETE – delete a resource.

Copyright © Oded Nissan 2009

Page 56: Jee course web services

REST Implementation

• JAX-WS provides full support for building RESTful web services.

• JAX-WS enables building RESTful endpoints through a javax.xml.ws.Provider interface in the API. Provider is a generic interface that can be implemented by a class as a dynamic alternative to a service endpoint interface (SEI), and a service implementing this interface can be deployed in a Java EE container or published in a stand-alone mode through the JAX-WS Endpoint API.

Copyright © Oded Nissan 2009

Page 57: Jee course web services

REST Implementation

• Errors in REST are signaled by returning standard HTTP error codes:– 400 – Bad Request– 403 – Forbidden.– Etc.

• The error message text is returned as part of the reply.

Copyright © Oded Nissan 2009

Page 58: Jee course web services

REST Web Service Example@WebServiceProvider @ServiceMode(value=Service.Mode.PAYLOAD) public class MyProvider implements Provider<Source> {

public Source invoke(Source source) {

String replyElement = new String("<p>hello world</p>"); StreamSource reply = new StreamSource( new

StringReader(replyElement)); return reply; }

public static void main(String args[]) { Endpoint e = Endpoint.create( HTTPBinding.HTTP_BINDING, new

MyProvider()); e.publish("http://127.0.0.1:8084/hello/world"); // Run forever e.stop(); }

}

Copyright © Oded Nissan 2009

Page 59: Jee course web services

REST Client ExampleService service = Service.create(qname); service.addPort(qname, HTTPBinding.HTTP_BINDING, url + "acceptPO"); Dispatch<Source> dispatcher = service.createDispatch(qname, Source.class, Service.Mode.MESSAGE); Map<String, Object> requestContext = dispatcher.getRequestContext(); requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "POST"); Source result = dispatcher.invoke(new StreamSource(new StringReader(poXML))); printSource(result);

Copyright © Oded Nissan 2009

Page 60: Jee course web services

WADL

• Stands for the Web Application Description Language.

• The REST equivalent of WSDL• Used to describe RESTful web services.• The purpose of WADL is to provide better

tooling support for RESTful web services.• Currently in early adoption phases, there is

argument about its need.

Copyright © Oded Nissan 2009

Page 61: Jee course web services

Streaming API for XML

Copyright © Oded Nissan 2009

Page 62: Jee course web services

Streaming API for XML (StAX)

• StAX is a streaming Java-based, event-driven, pull-parsing API for reading and writing XML documents.

• StAX enables you to create bidrectional XML parsers that are fast, relatively easy to program, and have a light memory footprint.

• StAX provides is the latest API in the JAXP family, and provides an alternative to SAX, DOM and others.

Copyright © Oded Nissan 2009

Page 63: Jee course web services

Streaming vs DOM

• The DOM model involves creating in-memory objects representing an entire document tree and the complete infoset state for an XML document.

• Streaming refers to a programming model in which XML infosets are transmitted and parsed serially at application runtime, often in real time, and often from dynamic sources whose contents are not precisely known beforehand (SAX).

Copyright © Oded Nissan 2009

Page 64: Jee course web services

Pull Parsing and Push Parsing• Streaming pull parsing refers to a programming

model in which a client application calls methods on an XML parsing library when it needs to interact with an XML infoset--that is, the client only gets (pulls) XML data when it explicitly asks for it.

• Streaming push parsing refers to a programming model in which an XML parser sends (pushes) XML data to the client as the parser encounters elements in an XML infoset--that is, the parser sends the data whether or not the client is ready to use it at that time.

Copyright © Oded Nissan 2009

Page 65: Jee course web services

StAX and SAX• StAX-enabled clients are generally easier to code

than SAX clients. While it can be argued that SAX parsers are marginally easier to write, StAX parser code can be smaller and the code necessary for the client to interact with the parser simpler.

• StAX is a bidirectional API, meaning that it can both read and write XML documents. SAX is read only, so another API is needed if you want to write XML documents.

• SAX is a push API, whereas StAX is pull.

Copyright © Oded Nissan 2009

Page 66: Jee course web services

The StAX Cursor API• The StAX cursor API represents a cursor with which you can

walk an XML document from beginning to end. This cursor can point to one thing at a time, and always moves forward, never backward, usually one infoset element at a time.

• The two main cursor interfaces are XMLStreamReader and XMLStreamWriter. XMLStreamReader includes accessor methods for all possible information retrievable from the XML Information model.

• You can call methods on XMLStreamReader, such as getText and getName, to get data at the current cursor location.

Copyright © Oded Nissan 2009

Page 67: Jee course web services

The StAX Cursor API Examplepublic class ReadingUsingCurorApi {

private XMLInputFactory inputFactory = null; private XMLStreamReader xmlReader = null; public ReadingUsingCurorApi() {

inputFactory = XMLInputFactory.newInstance(); } public void read() throws Exception {

xmlReader = inputFactory.createXMLStreamReader( new FileReader(".\\src\\myCalendar.xml"));

while (xmlReader.hasNext()) { Integer eventType = xmlReader.next(); if (eventType.equals(XMLEvent.START_ELEMENT)) {

System.out.print(" " + xmlReader.getName() + " "); }else if (eventType.equals(XMLEvent.CHARACTERS)){

System.out.print(" " + xmlReader.getText() + " "); }else if (eventType.equals(XMLEvent.ATTRIBUTE)) {

System.out.print(" " + xmlReader.getName() + " "); }else if (eventType.equals(XMLEvent.END_ELEMENT)){

System.out.print(" " + xmlReader.getName() + " "); }

} xmlReader.close();

}

Copyright © Oded Nissan 2009

Page 68: Jee course web services

The StAX Iterator API

• The StAX iterator API represents an XML document stream as a set of discrete event objects. These events are pulled by the application and provided by the parser in the order in which they are read in the source XML document.

• The primary parser interface for reading iterator events is XMLEventReader, and the primary interface for writing iterator events is XMLEventWriter. The XMLEventReader interface contains five methods, the most important of which is nextEvent(), which returns the next event in an XML stream.

Copyright © Oded Nissan 2009

Page 69: Jee course web services

The StAX Iterator API Examplepublic class ReadingUsingEventIteratorApi {

private XMLInputFactory inputFactory = null; private XMLEventReader xmlEventReader = null; public ReadingUsingEventIteratorApi() {

inputFactory = XMLInputFactory.newInstance(); } public void read() throws Exception {

xmlEventReader = inputFactory.createXMLEventReader( new FileReader(".\\src\\myCalendar.xml"));

while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); if (xmlEvent.isStartElement()) {

System.out.print( xmlEvent.asStartElement().getName() + " "); } else if (xmlEvent.isCharacters()){

System.out.print(" " + xmlEvent.asCharacters().getData() + " "); }else if (xmlEvent.isEndElement()) {

System.out.print(" " + xmlEvent.asEndElement().getName() + " ");

} } xmlEventReader.close();

}

Copyright © Oded Nissan 2009

Page 70: Jee course web services

Choosing between the Cursor API and the Iterator API• The cursor API produces smaller more efficient code.• The cursor API has better performance.• If you want to create XML processing pipelines, use the

iterator API.• The iterator API allows modifying the event stream.• In general, if you do not have a strong preference one way or

the other, using the iterator API is recommended because it is more flexible and extensible.

Copyright © Oded Nissan 2009

Page 71: Jee course web services

Summary

• What did we discuss ?– Overview– The Web Services Architecture.– Web Services Development– Restful Web Services– Streaming API for XML

Copyright © Oded Nissan 2009