Presentation on theme: "Service-Oriented Programming"— Presentation transcript:
1Service-Oriented Programming Introduction to service-oriented programming
2Aims You should able to: Articulate the motivation behind service-oriented programmingUnderstand the concept of web servicesUnderstand the service-oriented architecture and web service standardsBuild a web services using C# or JavaDevelop an application that uses a public web services
3Motivation: What does service-orientation mean? What do we do when we have a complex problem?We decompose it into sub problems (i.e., abstraction).Object-Orientation defines an abstraction on the level of objects.It allows to model, develop, and use software components as objects.Service-Orientation defines an abstraction on the level of services.It allows to model, develop, and use software systems as services.
4The evolution of Programming Abstractions Figure: Evolution of Programming Abstractions (1)(1) Dr. Marcello La Rosa, QUT, Introduction to Web Services
5What is Service-Oriented Programming (SOP)? SOP is a programming paradigm that uses “services” as the building block to develop software applications.Develop services.Invoke services.Combine servicesKernel component: Web Services
6What is a Web Service? Naïve answer: a service on the Web… Different from a web application:A web application is consumed by humansSuch asA web service is consumed by programsSuch as Twitter APIs https://dev.twitter.com/docs/api/1
7What is a Web Service? (2) W3C (World Wide Web Consortium) definition: 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 (specially WSDL (web service description language)). Other systems interact with the Web service in a manner prescribed by its description using SOAP (simple object access protocol) messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.
8What is new in web services? Global accessibility:A web service is available on the WebIt leverages the powerful communication paradigm of the webIt is accessible via HTTP (cross firewall)Standardization:WSDL: for service description (www.w3.org/TR/wsdl)UDDI (Universal Description, Discovery and Integration): for service publish and discovery (http://uddi.xml.org/)SOAP: for service invocation (www.w3.org/TR/SOAP/)More standards…They are XML-based…
9More about web services A Web service can be:A self-contained business taskE.g., a funds withdrawal or funds deposit serviceself-contained means it does not need other resourcesbusiness task is a simple stepA full-fledged business processE.g., the automated purchasing of office suppliersbusiness process consists of several steps, or business tasksAn applicationE.g., a life insurance applicationA service-enabled resourceE.g., access to a particular back-end database containing patient medical records
10What web service brings to SOP? Foster software reuseDeal with heterogeneity issues:Using the same data types?Using the same programming languages?Using the same development platform?Using the same operating systems?Solution: provide XML-based InterfacesXML is ubiquitoustraditional oop needs those items with ?
11What web service brings to SOP? (2) Deal with the accessibility issues:Downloading libraries and including in the project?Solution: access to functionalities on the webUse existing networking infrastructureHTTP is ubiquitoustraditional oop needs that
12SOP as a new problem-solving methodology Instead of develop an application to solve a complex problem from scratch, use the existing services:decompose the problem to sub problems,for each sub problem, select/or develop appropriate services,compose these services together.
13Current stage of SOP Major IT companies have led the efforts Microsoft, IBM, HP, Oracle, BEA, Sun, SAP…A large number of web services onlineMajor IT companies deliver their functionalities as web servicesMicrosoft, Yahoo!, Google, Facebook, Twitter, Bing, Amazon, … you name itthere are Web services and 6610 mashups (SOP applications) published in programmableWeb.Other search engines……The Web is taking a step to transform from an information repository to a service repository
14Web service commercial frameworks Microsoft:IBM:Oracle:Hewlett Packard
15An Example of SOP Applications: Suppose we want to develop a web-based hotel query application that allows users to view the information of hotels. Given a locationInput: addressOutput: a list of hotels, local weather, driving directions.
16A SOP Example (2)The process of developing this application contains the following steps:Develop a hotel service:Input: addressOutput: a list of hotelsDevelop a weather service:Output: local weatherDevelop a route service:Input: two addressesOutput: Driving directionsIt is not trivial to develop any of the above services, so, let’s take a look at existing services on the web…
17Hotel Service: Expedia APIs: Input: city, stateOutput: the list of hotels (in Jason format)name, average daily price, a short descriptionDemo.
18Weather Service: Weather underground weather API Input: GeocodeOutput: current weather conditionweather, humidity, temperature, wind mph,…Demo.
19Route Service The Google directions API https://developers.google.com/maps/documentation/directions/Input: origin, destinationOutput: Driving directionduration, instructions, distances,…Demo
21Service-Oriented Architecture(SOA) Roles of interactionWeb services providerOwns the Web service and implements the business logicHosts and controls access to the servicee.g., Microsoft, Amazon, Facebook, …Web services requestorRequires the certain functions to be satisfiedLooks for and invokes the servicee.g., a client program, a server, or another web serviceWeb services registrySearchable directory where service descriptions can be published and searchede.g., UDDI registryFrom a business perspective, the Web services provider is the organization that owns the Web service and implements the business logic that underlies the serviceFrom an architecture perspective, it is the platform that hosts and controls access to the serviceFrom a business perspective, the web service requestor is the enterprise that requires the certain functions to be satisfied.From an architecture perspective, this is the application that is looking for, and subsequently invoking the serviceService requestors find service descriptions in the registry and obtain binding information for services. This information is sufficient for the service requestor to contact, or bind to, the service provider and thus make use of the service it provides.
22Operations in SOA Publish operation Describing the Web service itself Business information: information regarding the Web service provider or the implementer of the serviceService information: information about the nature of the Web serviceTechnical information: information about implementation details and the invocation methods for the Web serviceActual registration of the Web serviceStoring the three basic categories of descriptive information about a service in the Web service registry
23Operations in SOA (2) Find operation Discovering the services in the registry of the discovery agencySearch criteria: type of service, preferred price range, products associated with the service, company categoryCan be specifiedStatically at the design time to retrieve a service’s interface description for program developmentorDynamically (at run-time) to retrieve a service’s binding and location description for invocation.Selecting the desired Web service from the search resultManual selectionAutomatic selectionManual selection implies that the Web service requestor selects the desired Web service directly from the returned set of Web services after manual inspection.Automatic selection: a special client application program provided by the Web service registry can achieve this. In this case, the We services requestor has to specify preferences to enable the application to infer which web service the web services requestor is most likely to invoke.
24Operations in SOA (3) Bind operation Service requestor invokes or initiates an interaction at run-time using the binding details in the service description to locate and contract to the service.Two possibilities:Direct invocation of the Web service by the Web service requestorMediation by the service agency when invoking the Web serviceDuring the binding operation the service requestor invokes or initiates an interaction at run-time using the binding details in the service description to locate and contract to the service. The technical information entered in the registry by the web services provider is used here. Tow different possibilities exist for this invocation. The first possibility is direct invocation of the web service by the web services requestor using the technical information included in the description of the service. The second possibility is mediation by the discovery agency when invoking the web service . In this case all communication between the web services requestor and the web services provider goes through the web services registry of the discovery agency.
25Service-Oriented Programming Web service standards and technologies: XML, WSDL, SOAP, REST.
26XML XML: eXtensible Markup Language It is the universal format for structured documents and data on the WebIt is the common data format of Web servicesIt is a semi-structured data model
27XML: Key concepts Document Elements Attributes Text Others: namespace declarations, comments, processing instructions, …
28Elements Enclosed in Tags: book, title, author, …Start tag: <book> End tag: </book>Empty element <red></red> OR <red/>Elements are ordered, may be repeated or nested
29Basic XML Tag Syntax Tags written as with HTML, but … Case-sensitive namesAlways need end tagsSpecial empty-elementAlways quote attribute valuesSome other constraints for tagsStart with a letter or underscoreAfter 1st character, numbers, -, and . are allowedCannot contain white-spaces.
30Attributes Associated to Elements, … Attributes are unordered. <book price=“20”>Attributes are unordered.Attribute names must be unique.Attributes cannot be nested (good for atomic value)
31Attributes Attributes provide metadata for the element The value of each attribute must be enclosed in “ ”If an element contains several attributes, then there is no comma in betweenSame naming conventions as elements
33WSDL WSDL: Web Service Description Language Pronounced “Whiz Dull” XML-basedWhy we need WSDL for web services?Web services are designed to support machine-to-machine interactionNo human in the loopNeeds a specified and self-explanatory programming interface
34What is included in a WSDL file?(1) WSDL describes a service’s functionalityA service interface:a list of operations that can be invoked by service users, such as getRoute, getMap,…for each operationa list of input parameters whose values need to be provided by service users, such as zipcode, address, …a list of output parameters whose value will be returned to service users, such as directions, map image, …By parsing a WSDL file, a program can:determine if the service is suitable,how to format the request,how to handle the response.
35What is included in a WSDL file?(2) WSDL describes how to bind a serviceMessaging styleFormatting (encoding) styleTransport protocol:such as http, smtp, soapWSDL describes where to locate a web servicea set of portsA port defines the location of a web service, e.g., network address location or URLBy parsing a WSDL file, a program can:Locate and bind a web serviceWeb services are interacted via message exchange
36WSDL document content Abstract (interface) definitions <types> data type definitions<message> operation parameters<operation> abstract description of service actions<portType> set of operation definitionsConcrete (implementation) definitions<binding> operation bindings<port> association of an endpoint with abinding<service> location/address for each binding
38SOAP (Simple Object Access Protocol) It is the standard messaging protocol used by web services.It supports inter application communication.
39SOAP-based middleware It codifies the use of XML as an encoding scheme for request and responses parameters using HTTP as a means for transport.Service providerService requestorApplication object(client)(service provider)SOAP-based middlewareSOAP messages exchanged on top of, HTTP, SMTP, or other transportConverts procedure calls to/from XML messages sent through HTTP or other protocols.
40SOAP MessageSOAP messages are seen as enveloper where the application encloses the data to be sent.A SOAP message consists of an <Envelope> element containing an optional <Header> and a mandatory <Body> element.SOAP envelopeSOAP headerheader blockSOAP bodybody block
41SOAP header Contains several header blocks Contains information relevant to:Security, QoS values, transactionExample:<env:Envelopexmlns:env=“http://www.w3.org/2003/05/soap-envelope” >…<env:Header><tx:transaction-idxmlns:tx=”http://www.transaction.com/transaction”env:mustUnderstand=”true”>512</tx:transaction-id><notary:token xmlns:notary=”http://www.notarization-services.com/token”GRAAL-5YF3</notary:token></env:Header>……………</env:Envelope>
42SOAP BodyThe SOAP body is the area of the SOAP message, where the application specific XML data (payload) being exchanged in the message is placed.The <Body> element must be present and is an immediate child of the envelope. It may contain a number of child elements, called body entries, but it may also be empty. The <Body> element contains either of the following:Application-specific data is the information that is exchanged with a Web service. The SOAP <Body> is where the method call information and its related arguments are encoded. It is where the response to a method call is placed, and where error information can be stored.A fault message is used only when an error occurs.A SOAP message may carry either application-specific data or a fault, but not both.
43SOAP Body (Example) Envelope Header Blocks Body <?xml version='1.0' ?><env:Envelope xmlns:env="http://www.w3.org/2002/06/soap-envelope" ><env:Header><t:transactionIDxmlns:t="http://intermediary.example.com/procurement"env:role="http://www.w3.org/2002/06/soap-envelope/role/next"env:mustUnderstand="true" >57539</t:transactionID></env:Header><env:Body><m:orderGoodsenv:encodingStyle="http://www.w3.org/2002/06/soap-encoding"xmlns:m="http://example.com/procurement"><m:productItem><name>ACME Softener</name></m:productItem><m:quantity>35</m:quantity></m:orderGoods></env:Body></env:Envelope>EnvelopeHeaderBlocksBody
44Example of SOAP Request <SOAP-ENV:Envelopexmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/”><SOAP-ENV:Header><t:transId xmlns:t=“http://a.com/trans”>345</t:transId></SOAP-ENV:Header><SOAP-ENV:Body><m:Add xmlns:m=“http://a.com/Calculator”><n1>3</n1><n2>4</n2></m:Add></SOAP-ENV:Body></SOAP-ENV:Envelope>
45Example of SOAP Response <SOAP-ENV:Envelopexmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/”SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/”><SOAP-ENV:Header><t:transId xmlns:t=“http://a.com/trans”>345</t:transId></SOAP-ENV:Header><SOAP-ENV:Body><m:AddResponse xmlns:m=“http://a.com/Calculator”><result>7</result></m:AddResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
46More example:Sample SOAP Request and Response Message for Google's Web Service Interface (illustration purpose only)
47The SOAP Communication Model SOAP supports two possible communication styles:remote procedure call (RPC) anddocument (or message).RPC-style interactionDocument-style interaction
48RPC-style SOAP Services A remote procedure call (RPC)-style Web service appears as a remote object to a client application. The interaction between a client and an RPC-style Web service centers around a service-specific interface. Clients express their request as a method call with a set of arguments, which returns a response containing a return value.SOAP envelopeSOAP bodyMethod nameorderGoodsInput parameter 1product itemInput parameter 2quantityMethod returnReturn valueorder id
49RPC-style web services <env:Envelopexmlns:SOAP=“http://www.w3.org/2003/05/soap-envelope”xmlns:m="http://www.plastics_supply.com/product-prices"><env:Header><tx:Transaction-idxmlns:t=”http://www.transaction.com/transactions”env:mustUnderstand='1'>512</tx:Transaction-id></env:Header><env:Body><m:GetProductPrice><product-id> 450R6OP </product-id ></m:GetProductPrice ></env:Body></env:Envelope>Example of RPC-style SOAP body<env:Envelopexmlns:SOAP=“http://www.w3.org/2003/05/soap-envelope”xmlns:m="http://www.plastics_supply.com/product-prices"><env:Header><--! – Optional context information --></env:Header><env:Body><m:GetProductPriceResponse><product-price> </product-price></m:GetProductPriceResponse></env:Body></env:Envelope>Example of RPC-style SOAP response message
50Document (Message)-style SOAP Services In the document-style of messaging, the SOAP <Body> contains an XML document fragment. The <Body> element reflects no explicit XML structure.The SOAP run-time environment accepts the SOAP <Body> element as it stands and hands it over to the application it is destined for, unchanged. There may or may not be a response associated with this message.SOAP envelopeSOAP bodyPurchaseOrderdocumentproduct itemquantityAcknowledgementorder id
51Example of document-style SOAP body <env:Envelopexmlns:SOAP=“http://www.w3.org/2003/05/soap-envelope”><env:Header><tx:Transaction-idxmlns:t=”http://www.transaction.com/transactions”env:mustUnderstand='1'>512</env:Header><env:Body><po:PurchaseOrder oderDate=” ”xmlns:m="http://www.plastics_supply.com/POs"><po:from><po:accountName> RightPlastics </po:accountName><po:accountNumber> PSC </po:accountNumber></po:from><po:to><po:supplierName> Plastic Supplies Inc. </po:supplierName><po:supplierAddress> Yara Valley Melbourne </po:supplierAddress></po:to><po:product><po:product-name> injection molder </po:product-name><po:product-model> G-100T </po:product-model><po:quantity> 2 </po:quantity></po:product></ po:PurchaseOrder ></env:Body></env:Envelope>Example of document-style SOAP body
52SOAP Fault element SOAP provides a model for handling faults. It distinguishes between the conditions that result in a fault, and the ability to signal that fault to the originator of the faulty message or another node. The SOAP <Body> is the place where fault information is placed.<env:Envelopexmlns:SOAP=“http://www.w3.org/2003/05/soap-envelope”xmlns:m="http://www.plastics_supply.com/product-prices"><env:Header><tx:Transaction-idxmlns:t=”http://www.transaction.com/transactions”env:mustUnderstand='1'>512</tx:Transaction-id></env:Header><env:Body><env:Fault><env:Code><env:Value>env:Sender</env:Value><env:Subcode><env:Value> m:InvalidPurchaseOrder </env:Value></env:Subcode></env:Code><env:Reason><env:Text xml:lang="en-UK"> Specified product did not exist </env:Text></env:Reason><env:Detail><err:myFaultDetailsxmlns:err="http://www.plastics_supply.com/faults"><err:message> Product number contains invalid characters </err:message><err:errorcode> 129 </err:errorcode></err:myFaultDetails></env:Detail></env:Fault></env:Body></env:Envelope>
53REST Representational State Transfer Resource Client ... Boeing747.htmlFuel requirementsMaintenance schedule...The Client references a Web resource using a URL.A representation of the resource is returned (in this case as an HTML document).The representation (e.g., Boeing747.html) places the client in a new state.When the client selects a hyperlink in Boeing747.html, it accesses another resource.The new representation places the client application into yet another state.Thus, the client application transfers state with each resource representation.
54Web Resource Can be: Information from database Image Audio Video e.g., invoice, resume, price, phone number,…Imagee.g., map, photo,…Audioe.g., song, speech,…Videoe.g., movie clip,Others…
55Resource Representations Each resource is represented as a distinct Uniform Resource Identifier (URI)Uniform Resource Name (URN)e.g., isbn-10:orUniform Resource Locator (URL)e.g.,
56The REST Design Pattern Create a resource for every service.Uniquely identify each resource with a logical URL.Design your information to link to other information. That is, the information that a resource returns to a client should link to other information in a network of related information.
57The REST Design Pattern (cont.) All interactions between a client and a web service are done with simple operations. Most web interactions are done using HTTP and just four operations:retrieve information (HTTP GET)create information (HTTP PUT)update information (HTTP POST)delete information (HTTP DELETE)
58REST Principles: Statelessness Every HTTP request is isolated from others.Every HTTP request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server.All of the information related to application states is kept entirely on the client side.Application states are maintained if requests need to be made in a certain order, for example: make payment after adding products to a shopping cart
59Learn by ExampleParts Depot, Inc has deployed some web services to enable its customers to:get a list of partsget detailed information about a particular partsubmit a Purchase Order (PO)
60The REST way of Designing the Web Services HTTP GET requestURL 1PartsListHTTP responseResponse(HTML/XML doc)HTTP GET requestURL 2PartDataWeb ServerHTTP responseResponse(HTML/XML doc)PO(HTML/XML)HTTP POSTURL 3POHTTP responseURL to submitted PO
61The First Web Service Service: Get a list of parts The web service makes an available URL to a parts list resource. A client uses this URL to get the parts list:Note that how the web service generates the parts list is completely transparent to the client. This is loose coupling.
62Data Returned - Parts List <?xml version="1.0"?><Parts><Part id="00345" href="http://www.parts-depot.com/parts/00345"/><Part id="00346" href="http://www.parts-depot.com/parts/00346"/><Part id="00347" href="http://www.parts-depot.com/parts/00347"/><Part id="00348" href="http://www.parts-depot.com/parts/00348"/></Parts>Each resource is identified as a URL.Note that the parts list has links to get detailed info about each part.This is a key feature of the REST design pattern. The client transfers from one state to the next by examining and choosing from among the alternative URLs in the response document.
63The second Web ServiceGet detailed information about a particular partThe web service makes available a URL to each part resource. For example, here's how a client requests a specific part:Data returned<?xml version="1.0"?><Part><Part-ID>00345</Part-ID><Name>Widget-A</Name><Description>This part is used within the frap assembly</Description><Specification href="http://www.parts-depot.com/parts/00345/specification"/><UnitCost currency="USD">0.10</UnitCost><Quantity>10</Quantity></Part>Again observe how this data is linked to still more data - thespecification for this part may be found by traversing the hyperlink.Each response document allows the client to drill down to getmore detailed information.
64The Third Web Service Submit a Purchase Order (PO) The web service allows users to create a new purchase orderand insert it into the database. For example, here is a HTTP request a user will make:URL:Method: POSTRequest body:Returns:201 Created&Location401 Unauthorized415 Unsupported Media Type<?xml version="1.0"?><PurchaseOrder><PO-ID> </PO-ID><Date>01/14/2005</Date><Customer-ID> </Customer-ID><ItemNo>A-00832<ItemNo><Quality>12<Quality><Price>35<Price><Total>420</Total></PurchaseOrder>
65Web Service Examplesweather service: http://vhost3.cs.rit.edu/weather/Service.svcIMDB service: http://vhost3.cs.rit.edu/IMDB/Service.svcCalculator service: You can test the services via the following link:here are some urls, source codes and documentationsof sample services