SOAP-based and RESTful Web Services - PowerPoint PPT Presentation

About This Presentation
Title:

SOAP-based and RESTful Web Services

Description:

Title: Verdana Bold 30 Author: Intel Corporation Last modified by: cjochoa Created Date: 2/3/2006 6:17:02 PM Document presentation format: On-screen Show – PowerPoint PPT presentation

Number of Views:833
Avg rating:3.0/5.0
Slides: 95
Provided by: Intel45
Category:

less

Transcript and Presenter's Notes

Title: SOAP-based and RESTful Web Services


1
SOAP-based and RESTful Web Services
  • Claudio Ochoa, PhD
  • Sr Software Engineer _at_ Intel
  • SEG UNSL
  • September 2007

2
Agenda
  • Web Services
  • Definition
  • Advantages and reservations
  • Classification SOAP vs REST
  • SOAP-based WS
  • XML, XSL, XPath, XSLT
  • WSDL/ UDDI
  • SOAP
  • SOA (Service Oriented Architecture)
  • SOA Benefits
  • Demo Creating and consuming a SOAP-based WS

3
Agenda (contd)
  • RESTful WS
  • AJAX
  • The XmlHttpRequest object
  • The HttpRequest object
  • JSON
  • JSON data structures
  • JSON vs XML
  • Benefits and lowlights of JSON
  • Generating and Consuming JSON
  • Demo JSON and REST-WS

4
Agenda (contd)
  • Mashups
  • Example of mashups
  • Mashing up a yahoo map object
  • Hands On
  • Consuming a REST-WS
  • Creating/Adding a mashup
  • Wrap up

5
Agenda
  • Web Services
  • Definition
  • Advantages and reservations
  • Classification SOAP vs REST
  • SOAP-based WS
  • XML, XSL, XPath, XSLT
  • WSDL/ UDDI
  • SOAP
  • SOA (Service Oriented Architecture)
  • SOA Benefits
  • Demo Creating and consuming a SOAP-based WS

6
Need for Web Services
  • Distributed Computing allows sharing information
    and processing
  • Traditional distributed processing models assume
  • Common environment or architecture (J2EE, COM)
  • Interoperability is easier to achieve
  • Distributed processing using different platforms,
    architectures, and dev languages is complicated
  • Interoperability between different systems is key
  • WS are an approach for dealing with this problem

7
Web Services
  • WS provide a way to access biz or app logic using
    Internet standard protocols (e.g. HTTP, SMTP,
    FTP)
  • Organizations already have communication SW and
    infrastructure needed to support WS
  • What are WS for?
  • Early Internet apps (mail, web sites) helped
    individuals communicate with each other
  • WS help applications communicate with each other
  • WS allow interoperability across independent
    processing environments and domains

8
WS advantages
  • Interaction between different companies systems
  • Interoperation between apps inside a company
  • Processing is loosely coupled
  • No need for common application environment
  • Do not abandon existing investments in software
  • Add WS front end to existing apps
  • Big players (Microsoft, IBM, Sun) are investing
    in WS and creating tools to support them

9
WS reservations
  • WS are not proven technology
  • Fashionable solution of the day?
  • SOAP WS rely on XML
  • XML expands the size of data several times over
  • More processing is needed to format and parse
    msgs
  • Internal apps are now exposed to external threats
  • WS can expose valuable corporate data, apps,
    systems

10
WS Classification
  • WS can be classified in two main kinds
  • SOAP-based WS
  • RESTful WS
  • SOAP-based WS have been around for a while
  • Google (except blogger), enterprise software
  • RESTful WS are the trendy way for designing WS
  • Yahoo, Flickr, del.icio.us, pubsub, bloglines,
    technorati
  • eBay and Amazon use both REST and SOAP

11
SOAP-based WS overview
  • SOAP is a protocol for exchanging XML-based
    messages over computer networks
  • SOAP stands for SOAP
  • Originally stood for Simple Object Access
    Protocol
  • Later stood for Service Oriented Architecture
    Protocol
  • Provides a basic messaging framework
  • Successor of XML-RPC (still used for some apps
    like blogger)
  • Makes use of Internet transport protocol
    (HTTP/SMTP)

12
SOAP-based WS (contd)
Web Services building blocks
Web services
UDDI
WSDL
SOAP
XML
HTTP
FTP
SMTP
Internet Protocols
13
Advantages of SOAP WS
  • Easier communication behind proxies and firewalls
    than previous remote execution technology.
  • Versatile - allows the use of different transport
    protocols.
  • Easy to consume (sometimes)
  • Rigid - type checking, adheres to a contract
  • Development tools

14
RESTful WS
  • REST stands for Representational State Transfer
  • Collection of network architecture principles
    that outline how resources are defined and
    addressed
  • All resources can be uniquely identified by an
    URI
  • No need for additional message layer like SOAP
  • An application interacts with a resource by
    knowing
  • the identifier of the resource
  • the action required
  • No need to know if there are caches, proxies,
    gateways, firewalls, tunnels between client and
    server...
  • The application needs to understand the format of
    the information (representation) returned,
  • HTML, XML, JSON, images

15
Advantages of Restful WS
  • Lightweight - not a lot of extra xml markup
  • Human Readable Results
  • Improved response times and server loading
    characteristics
  • Improves server scalability by reducing the need
    to maintain communication state.
  • different servers can be used to handle initial
    and subsequent requests
  • A single browser can access any any resource
  • Easy to build, no toolkits required
  • Does not require a separate resource discovery
    mechanism

16
Agenda
  • Web Services
  • Definition
  • Advantages and reservations
  • Classification SOAP vs REST
  • SOAP-based WS
  • XML, XSL, XPath, XSLT
  • WSDL/ UDDI
  • SOAP
  • SOA (Service Oriented Architecture)
  • SOA Benefits
  • Demo Creating and consuming a SOAP-based WS

17
SOAP-based Web Services
  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and
    self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
    (Interoperability)
  • XML is the basis for SOAP-Web services

18
XML Overview
  • XML stands for eXtensible Markup Language.
  • XML is a markup language much like HTML.
  • XML tags are not predefined.
  • XML uses a Document Type Definition (DTD) or an
    XML Schema to describe the data.
  • XML with a DTD is designed to be
    self-descriptive.
  • XML was designed to store, carry, describe and
    exchange data.

19
XML elements
  • Begin with a start tag and end with an end tag
  • Unlike html, every start tag must have a matching
    end tag
  • XML elements can be nested

ltpricegt 123.45 lt/pricegt
ltbookgt lttitlegt Web Services lt/titlegt
ltauthorgt ltfirstnamegtJohnlt/firstnamegt
ltlastnamegt Doe lt/lastnamegt lt/authorgt
ltisbngt 0-471-26716-5 lt/isbngt lt/bookgt
20
XML Syntax
  • XML documents use a self-describing and simple
    syntax.
  • lt?xml version"1.0" encoding"ISO-8859-1"?gt
    ltnotegt lttogtJuanlt/togt ltfromgtPedrolt/fromgt
    ltheadinggtReminderlt/headinggt ltbodygtDon't
    forget me this weekend!lt/bodygt lt/notegt
  • XML elements are extensible.
  • ltnotegt
  • ltdategt2002-08-01lt/dategt
  • lttogtJuanlt/togt
  • ltfromgtPedrolt/fromgt
  • ltheadinggtReminderlt/headinggt
  • ltbodygtDon't forget me this weekend!lt/bodygt
  • lt/notegt

21
XML Attributes
  • XML elements can have attributes.
  • Attributes are used to provide additional
    information about elements.
  • Data can be stored in child elements or in
    attributes.
  • ltperson sex"female"gt ltfirstnamegtAnnalt/firstnam
    egt ltlastnamegtSmithlt/lastnamegtlt/persongt
  • ltpersongt ltsexgtfemalelt/sexgt ltfirstnamegtAnnalt/firs
    tnamegt ltlastnamegtSmithlt/lastnamegtlt/persongt

22
XML ValidationWell Formed vs Valid XML
  • A Well Formed XML document has correct XML
    syntax.
  • lt?xml version"1.0" encoding"ISO-8859-1"?gt
    ltnotegt lttogtTovelt/togt ltfromgtJanilt/fromgt
    ltheadinggtReminderlt/headinggt ltbodygtDon't forget
    me this weekend!lt/bodygt lt/notegt
  • A Valid XML document also conforms to a DTD.
  • lt?xml version"1.0" encoding"ISO-8859-1"?gt
    lt!DOCTYPE note SYSTEM "InternalNote.dtd"gt
    ltnotegt lttogtTovelt/togt ltfromgtJanilt/fromgt
    ltheadinggtReminderlt/headinggt ltbodygtDon't
    forget me this weekend!lt/bodygt lt/notegt

23
XML Other basic concepts
  • XML Namespaces
  • Provide a method to avoid element name conflicts.
  • XML Encoding
  • Allow representing extended or foreign characters
  • XML Parsers
  • Provide a way to create and manipulate an XML
    document.
  • XML CDATA
  • Provide a way to store text data which is ignored
    by the parser.

24
URIs
  • URIs identify abstract or physical resources
  • A URI follows the form ltschemegtltscheme-specific-p
    artgt
  • The most familiar form of a URI is the URL
  • It denotes location and protocol to access a
    resource

25
XSL languages
  • XSL stands for EXtensible Stylesheet Language
  • CSS HTML Style Sheets
  • XSL XML Style Sheets
  • XSL started as a way to describe how XML data
    should be displayed, but rapidly evolved to 3
    main languages
  • XSLT - a language for transforming XML documents
  • XPath - a language for navigating in XML
    documents
  • XSL-FO - a language for formatting XML documents

26
XPath
  • Language for finding information in an XML
    document.
  • Is used to navigate through elements and
    attributes in an XML document.
  • Syntax for defining parts of an XML document.
  • Library of standard functions.
  • W3C Standard.

27
XPath Nodes
  • In XPath, XML documents are treated as trees of
    nodes. There are seven types of nodes
  • Document (root)
  • Element
  • Attribute
  • Text
  • Namespace
  • Processing-instruction
  • Comment
  • lt?xml version"1.0" encoding"ISO-8859-1"?gtltbooks
    toregt ltbookgt lttitle lang"en"gtHarry
    Potterlt/titlegt ltauthorgtJ K. Rowlinglt/authorgt
    ltyeargt2005lt/yeargt ltpricegt29.99lt/pricegt
    lt/bookgtlt/bookstore

28
XPath Syntax
  • XPath uses path expressions to select nodes or
    node-sets in an XML document.

Path Expression Result
/bookstore/ Selects all the child nodes of the bookstore element
// Selects all elements in the document
//title_at_ Selects all title elements which have any attribute
  • XPath wildcards can be used to select unknown XML
    elements.

Wildcard Description
Matches any element node
_at_ Matches any attribute node
node() Matches any node of any kind
29
XSLT basics
  • XSLT is a language for transforming XML docs into
    XHTML documents or to other XML documents.
  • XSLT stands for XSL Transformations
  • XSLT is the most important part of XSL
  • XSLT uses XPath to navigate in XML documents
  • XSLT is a W3C Recommendation

30
XSLT Transformation example
lt?xml version"1.0" encoding"ISO-8859-1"?gtltxsls
tylesheet version"1.0" xmlnsxsl"http//www.w3.o
rg/1999/XSL/Transform"gt ltxsltemplate
match"/"gt lthtmlgt ltbodygt lth2gtMy CD
Collectionlt/h2gt lttable border"1"gt lttr
bgcolor"9acd32"gt ltth align"left"gtTitlelt/t
hgt ltth align"left"gtArtistlt/thgt lt/trgt
ltxslfor-each select"catalog/cd"gt lttrgt
lttdgtltxslvalue-of select"title"/gtlt/tdgt
lttdgtltxslvalue-of select"artist"/gtlt/tdgt
lt/trgt lt/xslfor-eachgt lt/tablegt lt/bodygt
lt/htmlgt lt/xsltemplategtlt/xslstylesheetgtgt
lt?xml version"1.0" encoding"ISO-8859-1"?gt
ltcataloggt ltcdgt lttitlegtEmpire
Burlesquelt/titlegt ltartistgtBob Dylanlt/artistgt
ltcountrygtUSAlt/countrygt ltcompanygtColumbialt/comp
anygt ltpricegt10.90lt/pricegt
ltyeargt1985lt/yeargt lt/cdgt . . . lt/cataloggt
31
Web Services Operations
Requestors query registry to discover a set of
services that it can interact with
Providers advertise their services to service
registry
Service Registry
find
publish
Service Provider
Service Requestor
bind
Requestors negotiate with providers to access and
invoke services
32
XML Web Services Framework
33
SOAP
  • SOAP is a simple XML based protocol to let
    applications exchange information over HTTP.
  • Stands for Simple Object Access Protocol.
  • Protocol for accessing a Web Service.
  • Platform and language independent.
  • Allows you to get around firewalls.
  • A SOAP message MUST be encoded using XML
  • A SOAP message MUST use the SOAP Envelope
    namespace
  • A SOAP message MUST use the SOAP Encoding
    namespace
  • A SOAP message must NOT contain a DTD reference
  • A SOAP message must NOT contain XML Processing
    Instructions
  • ltsoapEnvelope
  • xmlnssoap"http//www.w3.org/2001/12/soap-e
    nvelope"
  • soapencodingStyle"http//www.w3.org/2001/12
    /soap-encoding"gt ltsoapHeadergt ... ...
    lt/soapHeadergt ltsoapBodygt ... ...
    ltsoapFaultgt ... ... lt/soapFaultgt
    lt/soapBodygtlt/soapEnvelopegt

34
SOAP Envelope Header element
  • The optional SOAP Header element contains
    application specific information (like
    authentication, payment, etc) about the SOAP
    message.
  • If the Header element is present, it must be the
    first child element of the Envelope element.

35
SOAP Envelope Body element
  • The required SOAP Body element contains the
    actual SOAP message intended for the ultimate
    endpoint of the message.
  • SOAP Request Envelope
  • SOAP Response Envelope

lt?xml version"1.0" encoding"UTF-8" ?gt
ltsoapenvEnvelope xmlnsxsd"http//...."xmlnsso
apenvhttp//.... xmlnsxsi"http//..."gt ltsoapen
vBodygt ltns0getBalance xmlnsns0"http//bank.s
ample soapenvencodingStyle"http//..."gt ltac
countId xsitype"xsdint"gt1lt/accountIdgt
lt/ns0getBalancegt lt/soapenvBodygt lt/soapenvEn
velopegt
ltsoapenvEnvelope xmlnssoapenv"http//..."
xmlnsxsd"http//..." xmlnsxsi"http//..."gt lts
oapenvBodygt ltns1getBalanceResponse
soapenvencodingStyle"http//..."
xmlnsns1"http//bank.sample"gt ltgetBalanceRetur
n xsitype"xsdstring"gt1 Pedro pedro_at_hotmail.com
34.1lt/getBalanceReturngt
lt/ns1getBalanceResponsegt lt/soapenvBodygt lt/soape
nvEnvelopegt
36
SOAP Envelope Fault element
  • The optional SOAP Fault element is used to hold
    error and status information for a SOAP message.

Sub Element Description
ltfaultcodegt A code for identifying the fault
ltfaultstringgt A human readable explanation of the fault
ltfaultactorgt Information about who caused the fault to happen
ltdetailgt Holds application specific error information related to the Body element
FaultCode Description
VersionMismatch Found an invalid namespace for the SOAP Envelope element
MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
Client The message was incorrectly formed or contained incorrect information
Server There was a problem with the server so the message could not proceed
37
WSDL
  • WSDL is an XML-based language for describing Web
    services and how to access them.
  • Stands for Web Services Description Language.
  • Used to describe and locate Web services.

38
Service contracts WSDL files
lt?xml version"1.0" encoding"UTF-8"?gt ltwsdldefin
itions ............ ltwsdlmessage
name"getBalanceResponse"gt ltwsdlpart
name"getBalanceReturn" type"xsdstring"/gt
lt/wsdlmessagegt ltwsdlmessage
name"getBalanceRequest"gt ltwsdlpart
name"accountId" type"xsdint"/gt
lt/wsdlmessagegt ltwsdlportType
name"BankService"gt ltwsdloperation
name"getBalance" parameterOrder"accountId"gt
ltwsdlinput name"getBalanceRequest"
message"implgetBalanceRequest"/gt
ltwsdloutput name"getBalanceResponse"
message"implgetBalanceResponse"/gt
lt/wsdloperationgt lt/wsdlportTypegt
ltwsdlbinding name"BankServiceSoapBinding"
type"implBankService"gt ltwsdlsoapbinding
style"rpc" transport"http//schemas.xmlsoap.org/
soap/http"/gt ltwsdloperation
name"getBalance"gt ltwsdlsoapoperation
soapAction""/gt ltwsdlinput
name"getBalanceRequest"gt
ltwsdlsoapbody use"encoded" encodingStyle...
namespace"http//bank.sample"/gt
lt/wsdlinputgt ltwsdloutput
name"getBalanceResponse"gt
ltwsdlsoapbody use"encoded" encodingStyle
namespace"http//bank.sample"/gt
lt/wsdloutputgt lt/wsdloperationgt
lt/wsdlbindinggt ltwsdlservice
name"BankServiceService"gt ltwsdlport
name"BankService" binding"implBankServiceSoapBi
nding"gt ltwsdlsoapaddress
location"http//cbl-javoos8082/BankWEB/services/
BankService"/gt lt/wsdlportgt
lt/wsdlservicegt lt/wsdldefinitionsgt
39
WSDL Contract Architecture
40
UDDI Registry
  • UDDI is a directory service where businesses can
    register and search for Web services.
  • Platform-independent framework for describing
    services, discovering businesses, and integrating
    business services by using the Internet.
  • Stands for Universal Description, Discovery and
    Integration.
  • Directory of web service interfaces described by
    WSDL
  • UDDI communicates via SOAP

41
UDDI Registry (contd)
  • Helps to find a web service and its description
  • Search by business
  • Search by service type
  • Two types of UDDI registries
  • Public registries
  • Private registries

42
Service Oriented Architecture
The Details of SOA depends on your role
Business
Implementation
Architecture
Architectural style which requires a service
provider, requestor and a service
description. Set of architectural principles,
patterns and criteria which address
characteristics such as modularity,
encapsulation, loose coupling, separation of
concerns, reuse, composability and single
implementation.
Programming model complete with standards, tools
and technologies such as Web Services.
Set of services that a business exposes to their
customers and partners, or other portions of the
organization.
43
SOA WS relationship
Web Services
"Web services are software components described
via WSDL which are capable of being accessed via
standard network protocols such as SOAP over
HTTP.
  • Web services achieves most of the goals of SOA.
  • Web Services technology is one style of creating
    services for SOA.

BUT
  • SOA does not require the use of Web Services.
  • We can create useful services that don't speak
    SOAP.

SOA and WS are not the same thing.
44
SOA WS relationship
Most of today's production Web Services systems
are not service oriented architectures they're
simple remote procedure calls or point-to-point
messaging via SOAP or well structured integration
architectures.
There are production service oriented
architectures that do not primarily use Web
Services - they use ftp, batch files,
asynchronous messaging, etc.
45
Benefits of SOA
  • Support for all major vendors. WS Standards.
  • Interoperability and integration capability.
  • Services reuse. Well defined public interfaces.
  • High abstraction level.
  • User roles. Specialized profiles.
  • Easy assembling for new business process.

46
Limitations of SOA
  • Business components in closed application
    domains.
  • Performance issues in XML parsing.
  • Long-running asynchronous processes.
  • WS-Security implementation.
  • WS-Transaction overhead.
  • Complex data types interoperability.

47
Agenda
  • Web Services
  • Definition
  • Advantages and reservations
  • Classification SOAP vs REST
  • SOAP-based WS
  • XML, XSL, XPath, XSLT
  • WSDL/ UDDI
  • SOAP
  • SOA (Service Oriented Architecture)
  • SOA Benefits
  • Demo Creating and consuming a SOAP-based WS

48
Demo Creating and consuming a SOAP-based WS
49
Agenda (contd)
  • RESTful WS
  • AJAX
  • The XmlHttpRequest object
  • The HttpRequest object
  • JSON
  • JSON data structures
  • JSON vs XML
  • Benefits and lowlights of JSON
  • Generating and Consuming JSON
  • Demo JSON and REST-WS

50
Need for AJAX
  • Their ease of deployment allows a site to have
    millions of users with minimal cost
  • Traditional Web UI are not responsive to users
  • Websites forced users into submit/wait/redisplay
  • Ajax allows to build more dynamic and responsive
    Web applications
  • ability to communicate with the server
    asynchronously
  • use JS and DHTML to immediately update the UI
  • spawn an asynchronous request to the server to
    perform an update or query a database

51
AJAX
  • AJAX stands for Asynchronous JavaScript And XML
  • AJAX incorporates several technologies
  • Standards-based presentation using XHTML and CSS
  • Dynamic display and interaction using the
    Document Object Model
  • Asynchronous server communication using
    XMLHttpRequest
  • Supported by most modern browsers
  • Allows to perform HTTP requests which returns
    some form of response.
  • Can automatically parse an XML document sent in
    response to a request.
  • JavaScript binding everything together
  • AJAX allows to communicate with the web server to
    send and retrieve data without
  • loading a new page
  • reloading the current page

52
HTTP Quick Overview
  • When loading http//www.example.net/index.html
  • The browser opens a connection to the host
    www.example.net
  • It then sends the server an HTTP request which
    consists of several lines of plain text
  • The server sends back an HTTP response which
    also consists of several lines of plain text

53
HTTP Request
  • Contains
  • HTTP method
  • Path to document to retrieve
  • HTTP version
  • Request header

GET /index.html HTTP/1.1 Host www.example.net
User-Agent Mozilla/5.0 (Windows U Windows NT
5.1 en-US rv1.7.12)... Accept
text/xml,application/xml,application/xhtmlxml,tex
t/htmlq0.9,... Accept-Language en-us,enq0.5
Accept-Encoding gzip,deflate Accept-Charset
ISO-8859-1,utf-8q0.7,q0.7 Keep-Alive 300
Proxy-Connection keep-alive Pragma no-cache
Cache-Control no-cache
54
HTTP Response
  • The web server will return a response
  • The response consists of several lines of plain
    text.

HTTP/1.x 200 OK Server Microsoft-IIS/5.1 Date
Fri, 20 Jan 2006 192947 GMT Content-Length
534 Content-Type text/html Cache-Control
private lthtmlgt ltheadgt lttitlegtAbout
Uslt/titlegt lt/headgt ltbodygt lth1gtAbout
uslt/h1gt ltpgt...lt/pgt lt/bodygt lt/htmlgt
HTTP version and status
Response Header
Response Data
55
Passing Data in an HTTP Request
  • Append a query string to the URL
  • http//www.example.net/signup.asp?nameJaneDoeem
    ailjane40myhost.com
  • Each field is represented as namevalue
  • Fields are separated by a '' character
  • Each name and value is url-encoded
  • non-alphanumeric characters are replaced by a hex
    value "xx
  • Use the POST method.
  • Often used with forms on web pages.

POST /signup.asp HTTP/1.1 Host
www.example.net User-Agent Mozilla/5.0 (Windows
U Windows NT 5.1 en-US rv1.7.12)... Accept
text/xml,application/xml,application/xhtmlxml,tex
t/htmlq0.9,... Accept-Language
en-us,enq0.5 Accept-Encoding
gzip,deflate Accept-Charset ISO-8859-1,utf-8q0.
7,q0.7 Keep-Alive 300 Connection
keep-alive Content-Type application/x-www-form-ur
lencoded Content-Length 38 nameJaneDoeemailj
ane40myhost.com
56
How does AJAX work?
  • The kernel of Ajax is the XmlHttpRequest
    JavaScript object.
  • XmlHttpRequest was originally introduced in IE5
  • It is the enabling technology that allows
    asynchronous requests
  • XmlHttpRequest lets use JS to make a request to
    the server and process the response without
    blocking the user.
  • Before using the XMLHttpRequest object,
  • create an instance of it (no standard way for
    doing this)
  • XMLHttpRequest is supported natively by most
    browsers
  • IE is an exception, MS introduced the idea, but
    as an ActiveX object.

57
XMLHttpRequest Object Properties
readyState A number representing the current state of the request
status The numeric HTTP status code returned by the web server.
statusText The text associated with the above HTTP status code. For example, 200 means "OK" and 404 means "Not found".
responseText A string containing the response data returned from the web server.
responseXML If the web server returns an XML document, this will be a DOM document object representing the parsed XML.
58
XMLHttpRequest Object Methods
open(method, url, asynch, username, password) Initializes a new request. method is usually GET or POST.
setRequestHeader(name, value) Sets a the named request header.
send(data) Makes the request, optionally passing data.
abort() Aborts an active request.
getResponseHeader(name) Returns the value of the named response header.
getAllResponseHeaders() Returns a string containing all the response headers.
59
Examples of AJAX uses
  • Dynamically update totals on your shopping cart
    without forcing the user to click Update and wait
    for the server to resend the entire page.
  • Increase site performance by reducing the amount
    of data downloaded from the server.
  • When updating the quantity of an item in a
    basket, if the entire page is reloaded, forces
    several KB of data to be downloaded.
  • Using Ajax to calculate the new total, the server
    can respond with just the new total value,
    thereby reducing the required bandwidth
  • Eliminate page refreshes every time there is user
    input.
  • If the user clicks Next on a paginated list, Ajax
    allows you to just refresh the list with the
    server data, instead of redrawing the entire
    page.
  • Edit table data directly in place, without
    requiring the user to navigate to a new page to
    edit the data.
  • When the user clicks Edit, you can redraw the
    static table into a table with editable contents.
  • Once the user clicks Done, you can spawn an Ajax
    request to update the server, and redraw the
    table to have static, display-only data.

60
The HttpRequest object
  • Wrapper for XMLHttpRequest
  • Hides the browser differences in instantiating
    the object
  • Simplifies the process of making a request and
    obtaining the response.
  • Defined in HttpRequest.js library
  • Constructor

HttpRequest() Creates a new instance of the HttpRequest object.
61
The HttpRequest object (Properties)
successCallback A function to be called when a GET or POST request completes successfully
failureCallback A function to be called when a GET or POST request completes unsuccessfully
url The URL to send the request to
queryString A query string to append to the URL
username Username for authentication, if required
password Password for authentication, if required
status, statusText, responseText, responseXML These are equivalent to the XMLHttpRequest properties of the same name
62
The HttpRequest object (Methods)
clearRequestHeaders() Removes all request headers.
get() Performs an asynchronous GET request.
post(data) Performs an asynchronous POST request, passing the given data
abort(),setRequestHeader(name, value),getResponseHeader(name),getAllResponseHeaders() These are equivalent to the XMLHttpRequest methods of the same name.
63
The HttpRequest JS library
  • Need HttpRequest.js library
  • Create HttpRequest object
  • var postRequest new HttpRequest()
  • Define failure callback
  • postRequest.failureCallback requestFailed
  • function requestFailed(httpRequest)
  • Perform an asynchronous request
  • postRequest.url address of service
  • postRequest.queryString
  • postRequest.successCallback responseOK
  • postRequest.get()

64
RESTful WS
  • Web services are practically synonymous with XML
  • The application architecture imposed by Ajax and
    REST techniques has forced many to contemplate
    alternatives like JSON
  • JSON is lighter and more friendly format for Web
    services clients in the form of a browser
    (Ajax-enabled application)

65
AJAX and XML
  • Ajax establishes a separate channel on which to
    send and receive information from remote WS
  • If response is an XML
  • DOM used for manipulating and processing text
  • simple access to a data tree requires numerous
    method calls
  • DOM differing implementation details among
    various browsers
  • complex programming scheme for cross-browser
    compatibility
  • Need to accommodate WS response to AJAX
  • leverage a common component in all mainstream
    browsers the JavaScript engine
  • JSON fits natively to the JS engine

66
Agenda (contd)
  • RESTful WS
  • AJAX
  • The XmlHttpRequest object
  • The HttpRequest object
  • JSON
  • JSON data structures
  • JSON vs XML
  • Benefits and lowlights of JSON
  • Generating and Consuming JSON
  • Demo JSON and REST-WS

67
JSON
  • JSON stands for JavaScript Object Notation
  • Lightweight data-interchange format
  • Text Format easy for humans to read and write
  • Trivial for JS engine to parse and generate
  • Based on a subset of the JavaScript Programming
    Language
  • JSON is a text format that is completely language
    independent
  • uses conventions familiar to programmers of the
    C-family of programming languages

68
JSON data structures
  • JSON is built on two structures
  • A collection of name/value pairs.
  • In various languages, this is realized as an
    object, record, struct, dictionary, hash table,
    keyed list, or associative array.
  • An ordered list of values.
  • In most languages, this is realized as an array,
    vector, list, or sequence.
  • These are universal data structures.
  • Virtually all modern programming languages
    support them

69
JSON vs XML
"addressbook" "name" "Mary Lebow",
"address" "street" "5 Main Street,
"city" "San Diego, CA", "zip"
91912 , "phoneNumbers" "619
332-3452", "664 223-4667"
ltaddressbookgt ltnamegtMary Lebowlt/namegt ltaddressgt
ltstreetgt5 Main Streetlt/streetgt ltcity
zip"91912"gt San Diego, CA lt/citygt
ltphoneNumbersgt ltphonegt619 332-3452lt/phonegt
ltphonegt664 223-4667lt/phonegt
lt/phoneNumbersgt lt/addressgt lt/addressbookgt
70
JSON Object
  • An object is an unordered set of name/value pairs
  • An object begins with  and ends with  
  • Each name is followed by and the name/value
    pairs are separated by , 
  • Example firstname Juan, lastname Lucero

71
JSON Array
  • An array is an ordered collection of values
  • An array begins with  and ends with
  • Values are separated by , 
  • Example firstnameJuan, lastnameLucero ,
    firstnameJose, lastnamePerez

72
JSON Value
  • A value can be
  • Examples 34, Joseph, true, price32.2

73
JSON String
  • A string is a collection of zero or more Unicode
    characters, wrapped in double quotes
  • A character is represented as a single character
    string.

74
JSON Number
  • A number is very much like a C or Java number
  • Octal and hexadecimal formats are not used

75
Benefits of JSON
"addressbook" "name" "Mary Lebow",
"address" "street" "5 Main Street,
"city" "San Diego, CA", "zip"
91912 , "phoneNumbers" "619
332-3452", "664 223-4667"
  • Easier data access
  • Same internal representation used by JS engines
    for data structures like strings, arrays, and
    objects
  • Name access from JSON addressbook.name
  • Street address access from JSON
    addressbook.address.street
  • First phone number access from JSON
    addressbook.address.phoneNumbers0

76
Benefits of JSON (contd)
  • JSON has a less verbose nature
  • XML requires closing tags for markup compliance
  • JSON only needs a
  • In data exchanges comprising a hundred or more
    fields, this additional XML markup can add to
    transit times
  • JSON libraries produced for many languages
  • C, Java, PHP, Haskell, Lisp

77
Lowlights of JSON
  • Namespaces are missing in JSON
  • JSON lacks of attributes
  • Creation and validation of JSON may be more
    complex
  • XML has several developing tools for its
    processing

78
Generating JSON
public class Person region Member fields
int id - 1 string name "" endregion
region Properties public int ID
getreturn this.id setthis.id value
public string Name getreturn
this.name setthis.name value
endregion region Constructors public
Person() this( - 1, "") public Person(int
id, string name) this.id id
this.name name endregion
  • Use a StringBuilder (or similar) class to
    serialize object
  • Use existing DLLs or libraries that perform this
    task for different languages

public string ToJSON() StringBuilder sb new
StringBuilder() sb.Append("")
sb.AppendFormat("\"0\" \"1\"",
this.ID, this.Name)
sb.Append("") return sb.ToString()
Add
79
Consuming JSON
function ReadyStateChangeHandler() if
(xmlHttpRequest.readyState 4) // Completed
if (xmlHttpRequest.status 200) //
Response OK // Process
data var jsonStringObj
xmlHttpRequest.responseText //
Parse the JSON string object to a real JSON
object var jsonObj
jsonStringObj.parseJSON() //
display some data alert("Person Name
" jsonObj.Name) else
alert("Error HTTP "
xmlHttpRequest.status " "
xmlHttpRequest.statusText)
  • On JS, use json.js from json.org to convert a
    json-formatted string into a json object
  • http//www.json.org/json.js

80
JSON and REST-WS demo
81
Agenda (contd)
  • Mashups
  • Example of mashups
  • Mashing up a yahoo map object
  • Hands On
  • Consuming a REST-WS
  • Creating/Adding a mashup
  • Wrap up

82
Mashups
  • Web application that combines data from more than
    one source into a single integrated tool

83
Mashup Yahoo! Maps API
  • Obtain an application ID
  • https//developer.yahoo.com/wsregapp/index.php

lthtmlgt ltheadgt ltscript type"text/javascript" src"
http//api.maps.yahoo.com/ajaxymap?v3.7appidYah
ooDemo"gt lt/scriptgt lt/headgt ltbodygt ... ... lt/bodygt
lt/htmlgt
84
Mashup Yahoo! Maps API
  • Add a div container in which to place the map
  • Create a map object and use the
    drawZoomAndCenter() method to draw the map

ltscript type"text/javascript"gt // Create a
map object var map new YMap(document.getEleme
ntById('map')) // Set map type to either of
YAHOO_MAP_SAT, YAHOO_MAP_HYB, YAHOO_MAP_REG
map.setMapType(YAHOO_MAP_SAT) // create
geopoint var geopoint new YGeoPoint(latitude,l
ongitude) // Display the map centered on a
geocoded location map.drawZoomAndCenter(geopoint
, 3) lt/scriptgt
ltdiv id"map"gtlt/divgt
85
Agenda (contd)
  • Mashups
  • Example of mashups
  • Mashing up a yahoo map object
  • Hands On
  • Consuming a REST-WS
  • Creating/Adding a mashup
  • Wrap up

86
JSON / RESTful WS Client
  • WS is located in
  • http//ltserveripgt3655/getLocation_WS.aspx
  • Parameters
  • Lat // latitude, use -31.422419
  • Long // longitude, use -64.188183
  • Within // range of interest in meters, e.g.
    Within500
  • An html template file is in ltserveripgt
  • Use a ftp client to download it locally, modify
    it, rename it, and uploaded to the server. Then
    opening it using IE
  • JS Scripts are also located there
  • Your job
  • Consume the WS, convert the response to a JSON
    object, and display the answer in the html page
  • Play a bit. Resources have url pictures, you can
    retrieve these pictures from the server too

87
JSON Object
objects
id
name
desc
type
resource
object
images
img_thumb
elements
res
latitude
longitude
distance
88
Mashing up with Yahoo! Maps
  • A reference card for the API is located in
    ltserveripgt
  • Your job
  • Place a map centered in (-31.422419, -64.188183)
  • Place markers for each resource on the map using
  • YMarker(geopoint)
  • addOverlay(marker)
  • Play with addAutoExpand() method

89
Agenda (contd)
  • Mashups
  • Example of mashups
  • Mashing up a yahoo map object
  • Hands On
  • Consuming a REST-WS
  • Creating/Adding a mashup
  • Wrap up

90
SOA and WEB 2.0 Convergence
91
XML vs JSON considerations
  • Which one to use depends mainly on the WS
    consumer
  • Thick WS clients (Java , .NET , PHP, ) should
    use XML.
  • Most programming language environments provide
    custom libraries, parsers, or helper classes, ...
  • Thin WS clients (web-based, AJAX) should consider
    JSON.
  • Processing XML can be tough in this environment
  • Programming the DOM is a difficult undertaking
    when compared to accessing a JSON tree.

92
References
  • SOAP-based Web Services
  • Service-Oriented Architecture A Field Guide to
    Integrating XML and Web Services, by Thomas Erl,
    Prentice Hall
  • RESTful Web Services
  • RESTful Web Services, Richardson et al, OReilly
  • JSON
  • http//www.json.org/
  • http//dev2dev.bea.com/pub/a/2007/02/introduction-
    json.html
  • Yahoo! Maps AJAX API
  • http//developer.yahoo.com/maps/ajax/index.html

93
Questions ?
94
Backup
95
(No Transcript)
96
Similarities
Write a Comment
User Comments (0)
About PowerShow.com