You are on page 1of 41

Web Services

Introduction

Agenda
● What are Web Services
○ Why Web Services
● Implementations
○ SOA
○ REST
● Example Application
● Links
● Questions

What are Web Services
● System architecture
○ Client - Server
● Web
○ Clients and servers communicate over HTTP protocol
■ Web APIs
● Services
○ Exchange of data and services (operations)
■ Application Services
● Software systems designed to support interoperable
machine to machine interaction over network. -- W3C
● A standardized way of integrating web based applications
using specific technologies
○ XML
○ SOAP
○ WSDL
○ UDDI

Why Web Services
● Connect existing software
○ Solve interoperability problem by giving different
applications a way to link their data and services
■ Integrate legacy applications in new systems
● Reusable design
○ Reusable applications components
○ Modularization
● Low cost of communication
○ HTTP used as protocol for communication so existing
internet infrastructure can be used in WS implementation
● Connect different applications and platforms
○ Allow applications to share data and services among
themselves. For example a .NET client application could
talk with a Java server.

Why Web Services Cont.. ● Loosely coupling ○ Software modules which encapsulates discrete functionality that can be used by applications developed in any technologies ● Standards ○ Web Services protocol stack is using standardized technologies and protocols ● Self description ○ Web Services are self-description applications and this greatly reduces development time ● Automatic discovery ○ Automatic discovery mechanism used to find providers and description for web services ..

The most common styles of use are: ● SOA ○ Service Oriented Architecture ○ Basic unit of communication is the message rather than operation (focus on message) ○ Very well supported by most of the software vendors ● REST ○ REpresentational State Transfer ○ Focus on interacting with resources rather than messages or operations .Implementation (Styles of use) Web Services are a set of tools and design techniques that can be used in a number of ways.

interact with and use capabilities to produce desired effects consistent with measurable preconditions and expectations. Service intercommunication: ● Simple data exchange ● Activity coordination by two or more services ● Focus on message passing between services OASIS = Organization of the Advancement of Structured Information Standards .Service Oriented Architecture A paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains. -. discover.OASIS A group of services (business components) that communicate each other. It provides a uniform means to offer.

SOA Building Blocks Each functional unit can play one or both of two roles: ● Service provider ○ The service provider creates a Web service and publishes its interface and access information to the service registry. how to make trade-offs between security and easy availability. ● Service requestor ○ The service requester or Web service client locates a service in the service registry using various find operations and then binds to the service provider in order to invoke one of its Web service interface operations. . Each provider must decide which services to expose.

SOA Technology Stack SOA is implemented using a number of technologies. ● SOAP ○ Simple Object Access Protocol ○ Specification for exchanging structured information (objects) ○ Uses XML as message format ■ Pack / unpack object data in XML ● WSDL ○ Web Service Description Language ○ XML based language that provides a model to describe Web Services interface (supported operations and message types) ● UDDI ○ Universal Description Discovery and Integration ○ XML based registry to list Web Services ■ WSDL directory .

Architecture .SOA and SOAP .

one of the principal authors of the HTTP specification .REST ● REpresentational State Transfer ○ Resource state transfer between clients and servers ● Collection of network architecture principles which outline how resources are managed ● Simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP ● Software architecture for distributed hypermedia systems such as the WWW ● “REST” term was introduced in 2000 by Roy Fielding.

DELETE . Plain text) ○ JSON = JavaScript Object Notation ■ Lightweight data interchange format ● Each resource has an unique identifier ○ URI ■ Uniform Resource Identifier ● Clients and servers communicate over HTTP to exchange representation of resources ○ Need to understand resource format/representation ● To interact with a resource a client need to things ○ Resource global identifier (URI) ○ Supported operation ■ GET. JSON. XML.Resource concept in REST ● Source of specific information ○ Web document (HTML. PUT.

REST .Architecture .

icio. Edit. ● Similar with del.us. ● Basic functionality ○ Add. Delete bookmarks ● ReST and SOA implementations ● Technologies ○ HTML ○ AJAX ■ jQuery ○ JSON ○ Java Servlets ○ Java Web Services . Google Bookmarks etc.Example Application Simple web application used to manage URL Bookmarks.

Application Architecture .

REST .Bookmarks .Architecture .

JSON ● JavaScript Object Notation ● Lightweight data interchange format ● Easy to convert between JSON and JavaScript objects ○ Easy to populate UI elements with data from server .

*/ public class BookmarkResource extends HttpServlet { private BookmarkDatabase database. } public void doDelete(HttpServletRequest req. HttpServletResponse resp) throws ServletException... IOException { . } public void doPost(HttpServletRequest req.... HttpServletResponse resp) throws ServletException. IOException { . public BookmarkResource() { database = new BookmarkDatabase().. IOException { . IOException { .. HttpServletResponse resp) throws ServletException. } public void doGet(HttpServletRequest req.Bookmark Resource Servlet /** * ReST resource that provides CRUD operations for bookmarks. } public void doPut(HttpServletRequest req. HttpServletResponse resp) throws ServletException.. } } .

IOException { try { Bookmark bookmarkToAdd = parseBookmarkFromRequest(req).POST /** * Add a new bookmark.create(bookmarkToAdd). resp. } } . e).setStatus(HttpServletResponse.Bookmark Resource Servlet . HttpServletResponse resp) throws ServletException. if (isValid(bookmarkToAdd)) { database. */ @Override public void doPost(HttpServletRequest req.SC_CREATED). } } catch (JSONException e) { log("Unable to parse bookmark data".

if (bookmarkFromDatabase != null) { resp. */ @Override public void doGet(HttpServletRequest req. } } else { resp. e). HttpServletResponse resp) throws ServletException. if (bookmarkId >= 0) { // Parse resource id from URL: http://localhost:8080/bookmarks/{id} Bookmark bookmarkFromDatabase = database. } } else { // If there is no resource id in URL the just list all bookmarks } . charset=UTF-8").findById(bookmarkId).write(bookmarkToJson(bookmarkFromDatabase)).Bookmark Resource Servlet .SC_NOT_FOUND). } catch (JSONException e) { log("Unable to send bookmark data".getWriter().setStatus(HttpServletResponse. try { resp.GET /** * Retrieve one or all bookmarks. IOException { long bookmarkId = parseBookmarkIdFromRequestUrl(req).setContentType("application/json.

} else { resp.PUT /** * Update a bookmark. if (database.SC_NOT_FOUND).setStatus(HttpServletResponse.findById(bookmarkFromRequest. resp.SC_ACCEPTED).setStatus(HttpServletResponse. IOException { try { Bookmark bookmarkFromRequest = parseBookmarkFromRequest(req). } } catch (JSONException e) { log("Unable to parse bookmark data".update(bookmarkFromRequest).Bookmark Resource Servlet . } } . HttpServletResponse resp) throws ServletException.getId()) != null) { database. */ @Override public void doPut(HttpServletRequest req. e).

delete(bookmarkFromDatabase). */ @Override public void doDelete(HttpServletRequest req. if (bookmarkFromDatabase != null) { database.findById(bookmarkId).DELETE /** * Delete a bookmark. HttpServletResponse resp) throws ServletException. } } . } } else { resp.setStatus(HttpServletResponse.SC_NOT_FOUND).SC_NOT_FOUND).Bookmark Resource Servlet .setStatus(HttpServletResponse. if (bookmarkId >= 0) { Bookmark bookmarkFromDatabase = database. } else { resp. IOException { long bookmarkId = parseBookmarkIdFromRequestUrl(req).setStatus(HttpServletResponse.SC_ACCEPTED). resp.

JavaScript Client Code . tags: bookmarkTags }). Title.Create & Update // Use jQuery library for easy AJAX calls // $ -> jQuery namespace $. data: JSON.ajax({ type: 'POST'. success: function() { resetBookmarksForm(). // or 'PUT' for update url: "/bookmarks". .stringify( // bookmarkId. title: bookmarkTitle. url: bookmarkUrl. contentType: "application/json". Url and Tags from bookmark form { id: bookmarkId. loadBookmarks(). } }).

success: function(data) { // parse bookmarks from // data JSON and // build bookmark list }). // Get bookmark by id $.Get & Delete // Get all bookmarks // Delete bookmark $.ajax({ url: "/bookmarks/"+bookmarkId.JavaScript Client Code . .ajax({ url: "/bookmarks". $. success: function(data) { // parse bookmark from // data JSON and // populate bookmark form }). type: "GET". type: "DELETE". success: function(data) { loadBookmarks().ajax({ url: "/bookmarks/"+bookmarkId. type: "GET". } }).

POST to update resource data ○ DELETE to delete resource ● Synchronize resource state with web service .REST Wrap Up ● Use URI to locate resource ● Fetch resource ○ GET http://webservice/resourceId ● Perform actions on resource representation ○ PUT.

Bookmarks .Architecture .SOA .

SOAP ● Simple Object Access Protocol ○ Data interchange format based on XML .

Architecture ● JavaScript will not talk directly with Bookmarks Web Service ○ Why ? ■ SOAP is not actually a simple protocol :-) ■ Not easy to implement a SOAP client in JavaScript ○ Solution ? ■ Proxy Servlet between JavaScript and the Web Service ● Web Service ○ Two components ■ Interface ■ Implementation ○ Java API for XML Web Services (JAX-WS) .SOA .Bookmarks .

wsimport Tool ● Generate Java client code for a web service using service WSDL document ● Client code used for Bookmark Service is generated with wsimport tool Usage example: wsimport -d . -p my_package http://localhost:8080/bookmarkService?wsdl .

LITERAL) public interface BookmarkService { void create(@WebParam(name = "bookmark") Bookmark bookmark). void delete(@WebParam(name = "bookmark") Bookmark bookmark). Bookmark getBookmarkById(long id). } . */ @WebService @SOAPBinding(style = SOAPBinding. List<Bookmark> getAllBookmarks().Interface /** * Provides CRUD operations for Bookmark entities.Style.DOCUMENT. use = SOAPBinding. void update(@WebParam(name = "bookmark") Bookmark bookmark).Use.Bookmark Web Service .

soap.Bookmark Web Service Implementation /** * Implementation of {@link BookmarkService} * that uses a simple in-memory data store. */ @WebService(endpointInterface = "bookmarks. public BookmarkServiceImpl() { database = new BookmarkDatabase(). } // Rest of implementation } .BookmarkService") public class BookmarkServiceImpl implements BookmarkService { private BookmarkDatabase database.ws.

Bookmark Web Service Implementation @Override public void create(@WebParam(name = "bookmark") Bookmark bookmark) { database. } @Override public void delete(@WebParam(name = "bookmark") Bookmark bookmark) { database. } @Override public void update(@WebParam(name = "bookmark") Bookmark bookmark) { database. } .update(bookmark).delete(bookmark).create(bookmark).

Bookmark Web Service . } @Override public Bookmark getBookmarkById(long id) { return database.getLastModification()) { return -1. Collections. return allBookmarks.findAll()). Bookmark o2) { if (o1. } else { return 0.sort(allBookmarks.getLastModification()) { return 1.getLastModification() > o2. } . } else if (o1.getLastModification() < o2.Implementation @Override public List<Bookmark> getAllBookmarks() { List<Bookmark> allBookmarks = new ArrayList<Bookmark>(database.findById(id). } } }). new Comparator<Bookmark>() { @Override public int compare(Bookmark o1.

..... IOException {. IOException {.Java Client Code .} @Override public void doPut(HttpServletRequest req.} } . HttpServletResponse resp) throws ServletException. IOException {.} @Override public void doGet(HttpServletRequest req.. HttpServletResponse resp) throws ServletException. @Override public void doPost(HttpServletRequest req. HttpServletResponse resp) throws ServletException.Servlet public class BookmarkServiceClient extends HttpServlet { // Reference to remote web service BookmarkService webservice.

Java Client Code . HttpServletResponse resp) throws ServletException. if (isValid(bookmarkFromRequest)) { webservice. */ @Override public void doPost(HttpServletRequest req.create(bookmarkFromRequest).SC_ACCEPTED).Create /** * Add a new bookmark.setStatus(HttpServletResponse. IOException { Bookmark bookmarkFromRequest = extractBookmarkFromRequest(req). } } . resp.

getParameter("id"). } } catch (NumberFormatException e) { resp. if (bookmarkId != null) { try { long id = Long. IOException { String bookmarkId = req.setStatus(HttpServletResponse. Bookmark bookmarkFromDatabase = webservice.valueOf(bookmarkId). resp.getWriter().SC_NOT_FOUND).setStatus(HttpServletResponse.Java Client Code .Get /** * Get one or all bookmarks. } } . } } else { // If there is no bookmark id in request then just return all List<Bookmark> allBookmarks = webservice.getAllBookmarks().SC_NOT_FOUND). if (bookmarkFromDatabase != null) { resp.setContentType("text/plain"). resp. } else { resp.setContentType("text/plain"). HttpServletResponse resp) throws ServletException.write(bookmarksToCsv(allBookmarks)).write(bookmarkToCsv(bookmarkFromDatabase)).getWriter(). */ @Override public void doGet(HttpServletRequest req. resp.getBookmarkById(id).

equals(action)) { webservice.getId()).Java Client Code . IOException { Bookmark bookmarkFromRequest = extractBookmarkFromRequest(req). */ @Override public void doPut(HttpServletRequest req. } } else { resp.delete(bookmarkFromDatabase).Update & Delete /** * Update or delete a bookmark. Bookmark bookmarkFromDatabase = webservice. } } .getParameter("action").setStatus(HttpServletResponse.update(bookmarkFromRequest). if (bookmarkFromDatabase != null) { if ("delete". } else { webservice. HttpServletResponse resp) throws ServletException. String action = req.getBookmarkById(bookmarkFromRequest.SC_NOT_FOUND).

SOA Wrap Up SOA technology stack overview ● Use HTTP as transport layer ● Use UDDI to locate a specify web service ● Use WSDL to get service interface details ○ Generate support/stub classes in order to implement service clients ● Use SOAP to describe data types ○ Pass XML packed data between clients and services .

Web Services Additional Specifications To extend Web Services capabilities additional specification have been developed: ● Web Services Security ○ Secure messages ■ Use XML Encryption and XML Signature in SOAP messages ○ Secure channel ■ Use HTTPS ● Web Services Reliability ○ Reliable messaging between two web services ● Web Services Transaction ○ Transaction support in web service calls .

com ○ IBM DeveloperWorks Web Services ○ Web Services Tutorial ○ JSON ○ SOAP ○ jQuery .Links ● Articles ○ Service-Architecture.

Questions ? .