writing rest services · collections, grouped into workspaces. • category document: a document...

24
Writing REST services Create REST services with Java technology and the Atom Publishing Protocol Skill Level: Intermediate J. Jeffrey Hanson ([email protected]) CTO Max International 30 Oct 2007 Updated 20 Dec 2007 This tutorial discusses the concepts of REST and the Atom Publishing Protocol (APP) and shows how they apply to services. It also shows how to use Java™ technology to implement REST/APP-based services. Section 1. Before you start Learn what to expect from this tutorial and how to get the most out of it. About this tutorial This tutorial discusses the concepts of Representation State Transfer (REST) and the Atom Publishing Protocol (APP) and shows how they apply to services. In addition, you learn to implement REST/APP-based services with Java technology. Objectives Writing REST services © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 24

Upload: others

Post on 04-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Writing REST servicesCreate REST services with Java technology and the AtomPublishing Protocol

Skill Level: Intermediate

J. Jeffrey Hanson ([email protected])CTOMax International

30 Oct 2007

Updated 20 Dec 2007

This tutorial discusses the concepts of REST and the Atom Publishing Protocol (APP)and shows how they apply to services. It also shows how to use Java™ technology toimplement REST/APP-based services.

Section 1. Before you start

Learn what to expect from this tutorial and how to get the most out of it.

About this tutorial

This tutorial discusses the concepts of Representation State Transfer (REST) andthe Atom Publishing Protocol (APP) and shows how they apply to services. Inaddition, you learn to implement REST/APP-based services with Java technology.

Objectives

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 24

Page 2: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

In this tutorial, you:

• Learn the basics of REST and the basic concepts behind APP

• Apply these technologies within any organization to send and receiveHTTP requests and responses through a Java servlet-based system

• Enable access and modification of resource data for podcasts, blogentries, image storage, calendar entries, and so on.

Prerequisites

This tutorial is written for Java programmers whose skills and experience are at anintermediate to expert level. You should have a general familiarity with using Javaservlets and a working knowledge of the Java programming language. To downloadall the source code for this tutorial, see Download.

System requirements

To run the examples in this tutorial, you need a Java servlet container.

Section 2. Representational State Transfer

REST is a collection of architecture principles and a software architecture style tobuild network-enabled systems based on mechanisms that define and accessresources, such as the World Wide Web. The term REST, defined by Roy Fielding'sdissertation (see Resources), is often used rather loosely to describe a framework totransmit data over a protocol such as HTTP without adding additional semanticlayers or session management.

REST defines a strict separation of concerns between components that participate ina client-server system that simplifies the implementation of actors involved. RESTalso strives to simplify communication semantics in a networked system to increasescalability and improve performance. REST relies on autonomous requests,between participants in a message exchange which implies that requests mustinclude all information that a client or server requires to understand the context ofthe request. In a REST-based system, you use minimal sets of possible requests toexchange standard media types.

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 2 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

The REST principle uses uniform resource identifiers (URIs) to locate and access agiven representation of a resource. The resource representation, known asrepresentational state, can be created, retrieved, modified, and deleted. Forexample, you can apply REST to document publishing to make documents availableto readers. At any given time, the publisher can present Web URLs so that readerscan access information (representational state) about the publisher's documents.Document readers need only know the URLs to read the document information and,if authorized, modify the information.

As Roy Fielding described, one of the defining principles of REST is that it canexploit existing technologies, standards, and protocols pertaining to the Web, suchas HTTP. This reliance on existing technologies and protocols makes REST easierto learn and simpler to use than most other Web-based messaging standards,because little additional overhead is required to enable effective informationexchange.

A REST-based conversation, according to Fielding, operates within statelessconversations, thereby making it a prime facilitator for subscription-basedtechnologies, such as RSS, RDF, OWL, and Atom, in which content is delivered topre-subscribed clients.

Fundamental entities of REST

REST defines the following fundamental entities:

• Data elements: Data, identifiers (URIs and URLs), and representations ofdata such as HTML documents, XML documents, and images

• Components: Origin servers such as Apache httpd and Microsoft®Internet Information Services (IIS), gateways such as Squid and CGI,proxies such as Gauntlet and Netscape proxy, and user agents such asWeb browsers or mobile devices

• Connectors: Client connectors such as libwww, server connectors suchas NSAPI, caches such as a browser cache, and others

Figure 1 illustrates some of the fundamental REST entities and how they caninteract within a typical networked system. Notice that requests are transmitted andreceived by connectors that are tied to a given entity, such as a server or database.Connectors handle transmission duties for a given protocol, thereby allowing anentity to transmit or receive requests in the same manner over any protocol, as longas a connector is present for the desired protocol.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 24

Page 4: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Figure 1. Interaction among REST entities

As you can see, connectors for such a system are embodied as protocol ports thatenable communication among the components. Note that any component in a RESTsystem can have multiple client and/or server connectors to handle communicationbetween other components and itself.

REST and HTTP

According to Fielding's dissertation, in an HTTP-based REST system, you shoulduse standard HTTP methods—namely, GET, PUT, POST, and DELETE —to accessthe representational state for a resource:

• GET : Use this method to transfer the current representational state of aresource from publisher to consumer.

• PUT : Use this method to transfer the modified representational state of aresource from consumer to publisher.

• POST : Use this method to transfer the new representational state of a

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 4 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

resource from consumer to publisher.

• DELETE : Use this method to transfer information needed to change therepresentational state of a resource to deleted .

Java server technologies, such as servlets and JavaServer Pages (JSP™), supportthe standard HTTP methods. The following sections discuss how to extend thesetechnologies to support the APP from a REST-based system using Java technology.

Section 3. The Atom Publishing Protocol

The APP is an HTTP-based protocol for publishing, deleting, and updatingresources. APP stresses the concept of using the fundamental operations that theHTTP protocol provides (such as GET, PUT, POST, and DELETE) to transferinstances of introspection documents and collection documents that contain thekinds of resources and feeds available for publish, updates, and so on. After theresources and feeds are discovered, their associated URIs are used for publicationand modification. Member feeds contain things like blog entries, podcasts, wikidocuments, and calendar events. The APP is also being investigated and used as afront-end API for a wide array of data-storage services, such as database servers,document and content management services, and software repositories.

The APP builds upon the popular Atom Syndication Format to formalize many of themechanisms used in the exchange of semantically rich content using RESTconcepts and technologies. The protocol operates on containers of Web resourcesknown as collections. Collections are presented for discovery in introspectiondocuments. All collections contain member resources, which are the ultimate targetsfor creation, access, modification, and deletion. Interactions with a collection and itsmember resources are based on the common HTTP verbs:

• GET: Used to retrieve a representation of a collection or member resource

• POST: Used to create a new member resource

• PUT: Used to update a member resource

• DELETE: Used to remove a member resource

Fundamental entities of APP

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 24

Page 6: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

The APP defines the following fundamental entities:

• Introspection document: The introspection document has a media-typeapplication/atomserv+xml and describes workspaces, which are arbitraryserver-defined groupings of collections. A collection can appear in morethan one workspace. Listing 1 is an example of a typical introspectiondocument.Listing 1. A typical introspection document

<?xml version="1.0" encoding="utf-8" ?><service xmlns="http://www.w3.org/2007/app" xmlns:atom="http://www.w3.org/2005/Atom">- <workspace>

<atom:title>Main Site</atom:title>- <collection href="http://localhost:8080/atompub/services/collections/main">

<atom:title>My Main Page</atom:title><accept>application/atom+xml;type=entry</accept><categories fixed="yes" />

</collection><collection href="http://localhost:8080/atompub/services/collections/pics">

<atom:title>My Pictures</atom:title><accept>*/*</accept><categories fixed="yes" />

</collection></workspace>

- <workspace><atom:title>Documents</atom:title>- <collection href="http://localhost:8080/atompub/services/collections/docs">

<atom:title>My Documents</atom:title><accept>application/atom+xml;type=entry</accept><categories fixed="yes" />

</collection></workspace>

</service>

The introspection document illustrated above defines a service with twoworkspaces. The first workspace, called "Main Site", defines twocollections called "My Main Page" and "My Pictures". The "My Main Page"collection is found athttp://localhost:8080/atompub/services/collections/main and the "MyPictures" collection is found athttp://localhost:8080/atompub/services/collections/pics. The secondworkspace, "Documents", contains one collection named "My Documents"and is found at http://localhost:8080/atompub/services/collections/docs.

• URI: A Uniform Resource Identifier.

• IRI: An Internationalized Resource Identifier (See Resources).

• Member resource: A data object or service known as an entry resourceor a media resource that an IRI or URI locates. Entry resources are

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 6 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

represented as Atom entry documents. Media resources can haverepresentations in any media type. A media resource is described within acollection using a media link entry.

• Representation: The state of a given resource transmitted by a requestor a response.

• Collection: A container of member resources identified by a unique URI.Collections are represented as Atom feeds. To create new entries in acollection, clients send HTTP POST requests to the collection's URI. Newentries are assigned a unique URI to be used as location references. Tomodify entries in a collection, a client retrieves the resource using its URI,makes modifications, then uses PUT to move the modified representationof the resource to the server. To remove the member resource from acollection, issue an HTTP DELETE request to the URI of the memberresource. All members of a collection must have an updated property bywhich a collection document is ordered.

• Workspace: A named group of collections.

• Service document/element: The top-level element of an introspectiondocument that describes the location and capabilities of one or morecollections, grouped into workspaces.

• Category document: A document that describes the categories allowedin a collection.

The following sections discuss how to extend Java technologies to support the APPfrom a REST-based system.

Section 4. Diving in

You can use the Java programming language to apply REST principles to a systemthat transmits resources across the HTTP protocol. You can use the APP to extendsuch a system to facilitate resource access and manipulation using blog entries,podcasts, wiki pages, calendar entries, and the like. This tutorial shows how you canapply the basics of REST and APP within a Web application to transmit resourcesacross HTTP requests and responses using a Java servlet-based system.

The Atom protocol specification defines an XML document that a client can use tointrospect an APP endpoint. An introspection document contains a list of allcollections available at a given endpoint's URI. Therefore, the first step to using any

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 24

Page 8: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

APP-enabled service is to determine the collections available at the serviceendpoint's URI and what types of member resources each collection can contain. Toretrieve the introspection document, a client sends a GET request to the server. Theserver then responds to the client with an introspection document that contains thelocation URIs of collections that the service provides.

Each collection element in an introspection document represents a container withinwhich information about each member resource that the collection contains isstored. Each collection in an introspection document has a unique URI. Issuing anHTTP GET request to that URI should return an Atom feed document that containsinformation about the member resources contained in the collection.

To create new member resource entries in the collection, clients send HTTP POSTrequests to the collection URI along with a representational state of the memberresources to be added to the collection. New member resource entries are giventheir own unique URI that you can query to retrieve the representational state ofeach member resource entry. To modify a member resource entry, a client retrievesthe resource by issuing an HTTP GET request to the member resource's URI, makesthe desired modifications to the representational state of the resource that the GETrequest returns, then sends the modified representational state back to the collectionusing an HTTP PUT request. Deletion of the member resource entry from thecollection is facilitated when the client issues an HTTP DELETE request to theappropriate member resource URI.

A simple Atom publishing protocol application using REST

The example application for this tutorial is designed to use a controller servlet tohandle incoming requests and issue resulting responses. Incoming requests aredispatched to a REST-based service framework that can handle operations on APPintrospection documents, collections, and member resources.

The REST-based APP framework contains the classes and interfaces shown inFigure 2.

Figure 2. Components of the REST/APP application framework

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 8 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

As this class diagram illustrates, a FrontController servlet is the central point ofreference for most of the primary REST entities. As the FrontController servletreceives requests, it interacts with connectors to retrieve ServerComponent objectswhich are used to locate BusinessService objects that will handle the businesslogic for each request. Resources are defined by Representation interface whichis implemented using classes found in the javax.activation package.

The following sections discuss how each of the primary REST entities and APPentities interact in the sample framework along with the specific Java componentsthat represent each entity.

REST components

REST components are defined by the role they play in a given system. To reiterate,typical components in a REST system are:

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 24

Page 10: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

• User agents: Components that initiate requests to some form of servercomponent that responds back to the user agent. A user agent can be amobile device, a Web browser, and so on.

• Origin servers: An origin server encompasses a given namespace for acollection of resources. An origin server manages the representationalstate of resources that it contains. It receives requests from user agentsand performs the necessary actions on the targeted collections ormember resources. The origin server then responds to the user agentwith a collection document or representational state for a resource.

In the Java language, you might represent a REST component using a markerinterface:

public interface Component{}

A server component in the Java language will expose methods and properties bywhich resource contexts are referred. This is shown in Listing 2.

Listing 2. REST ServerComponent interface (Java language)

public abstract class ServerComponentimplements Component

{private java.util.HashMap<String, Context> contexts =new java.util.HashMap<String, Context>();

abstract public Context addContext(String contextRootPath,String contextPath);

public java.util.Iterator<String> getContextPaths(){return contexts.keySet().iterator();

}

public Context getContext(String contextPath){return contexts.get(contextPath);

}

protected java.util.HashMap<String, Context> getContexts(){return contexts;

}}

Notice how the ServerComponent class maps a given context to a root/documentpath. Each specific server component uses the root/document path as it needs inorder to map to a given context. For example, an HTTP-specific server component

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 10 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

will manage HTTP-specific contexts, as shown in Listing 3.

Listing 3. REST ServerComponent interface (HTTP)

;public Context addContext(String contextRootPath, String contextPath){

Context context = getContexts().get(contextPath);if (context == null){context = new HTTPContext(contextRootPath, contextPath);getContexts().put(contextPath, context);

}

return context;}

An HTTP-specific context will implement an interface defining each primary HTTPmethod and provide the means for dispatching operation requests targetingcollections and member resource representations. Listing 4 provides an example ofan HTTP GET method implementation. The details of the business logic for aparticular vertical domain service or member resource feed are encapsulated withinspecific business service implementations.

Listing 4. REST HTTP-Context example

public Representation handleGet(Request request)throws ContextRequestException

{String uri = ((HTTPRequest)request).getRequest().getRequestURI();if (uri.startsWith(contextPath)){uri = reqURI.substring(contextPath.length());

}

BusinessService businessService =ServiceLocator.locateService(contextRootPath, contextPath, uri);

Representation representation = null;

try{representation = businessService.read(request);

}catch (ServiceExecutionException e){e.printStackTrace();throw new ContextRequestException(e);

}

return representation;}

In Listing 4, a GET request is handled by first extracting the URI from the request andthen using the URI to locate the desired business service. The business service is

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 24

Page 12: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

then invoked to handle the request.

REST components are loosely coupled and interact with each other throughconnector objects.

REST connectors

A connector in REST exposes a generic interface that defines properties andmethods to enable communication among REST components. A connectorrepresents one port or endpoint of a communication protocol. A connectorimplementation can represent a client connection or a server connection. Useragents use client connectors to initiate requests to an origin server. Origin serversrely on server connectors to handle incoming requests from user agents and torespond with representational state for collections or member resources.

The interface shown in Listing 5 illustrates a connector defining one method foradding a server component at a given port.

Listing 5. REST connector interface

public interface Connector{

public ServerComponent addServer(int port);}

A factory class might prove useful for managing protocol-specific connectors. Thefactory class can pool the factory connector as the situation dictates. Listing 6provides an example of a connector factory class.

Listing 6. REST connector factory example

;public static Connector getConnector(Protocol protocol)

throws ConnectorException{String key = protocol.getScheme();Connector instance = instances.get(key);

if (instance == null){

if (key.equalsIgnoreCase(Protocol.HTTP.getScheme())){

instance = new HTTPConnector();instances.put(key, instance);

}else{

throw new ConnectorException("Invalid protocol: "+ protocol.getScheme());

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 12 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

}}

return instance;}

A connector interface for an HTTP-specific server connector defines properties andmethods for adding HTTP-specific server components for specific ports, as shown inListing 7.

Listing 7. REST server connector example

public ServerComponent addServer(int port){return new HTTPServerComponent(port);

}

Connectors enable communications between user agents and origin servers. Originservers, represented by server components, contain and manage memberresources and are discussed in the next section.

Section 5. REST resource representations

When a user agent makes a request, a URI is passed to the origin server thatidentifies the targeted collection or member resource of the request. When a servercomponent representing the origin server receives a request, it extracts the URI fromthe request and performs any operations needed to handle the request. Requeststargeting member resources create, read, modify, or delete representational state forthe resource, and then return the resulting representational state of the resource, ifappropriate.

Create components to handle HTTP requests

To create and access components needed to handle an HTTP request from a useragent to an origin server and back, complete the following steps:

1. Create a server connector, and then add to it the appropriate HTTPserver component.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 24

Page 14: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

2. Add or access the HTTP context for a given server context.

3. Dispatch the incoming user agent request that the server componentreceives to the targeted business service.

4. Create and populate any data model representing a resource generatedby the business service and encapsulate it as the representational stateof the targeted resource.

5. Pass the representational state of the resource back to the user agent.

Figure 3 shows this procedure.

Figure 3. REST framework flow-of-control

Extend the DataHandler class

The JavaBean Activation Framework (JAF) provides a component—thejavax.activation.DataHander class—that can effectively represent the stateof member resources. Using the DataHandler component to represent resourcesallows heterogeneous resources with arbitrary content types to be presented withthe same generic interface.

The abstract class shown in Listing 8 extends the DataHandler class to provide ageneric base class for objects that represent member resources.

Listing 8. The abstract Representation class

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 14 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

public abstract class Representation extends javax.activation.DataHandler{

public Representation(DataSource dataSource){super(dataSource);

}}

For purposes of this tutorial, a specific implementation of the Representationinterface, which encapsulates Atom feed resources, is created and shown in Listing9.

Listing 9. The Representation class

public class FeedRepresentation extends Representation{

public static final String MEDIA_TYPE = "application/atom+xml";public static final String CONTENT_TYPE = MEDIA_TYPE + "; charset=utf-8";

public FeedRepresentation(File file){super(new FeedDataSource(file, CONTENT_TYPE));

}

public String getContentType(){return CONTENT_TYPE;

}}

In Listing 9, a feed resource is encapsulated within the FeedRepresentationclass. This class uses a FeedDataSource class to handle I/O operations for a fileresource.

Define properties and methods for implementation

The JAF also provides an interface— javax.activation.DataSource —thatdefines properties and methods to be implemented by resources that representarbitrary collections data. The interface provides methods to expose the content typeof the resource and input and output streams that act on the data for the resource.The DataHandler objects use objects to implement the DataSource interface toaccess an underlying resource through the same generic interface.

Each implementation of FeedDataSource relies on an underlying resource storagemechanism (for example, a database, a file system) to store and retrieve the feeddata. As Listing 10 shows, the FeedDataSource implementation relies on filesystem storage.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 24

Page 16: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Listing 10. File-based FeedDataSource class

public class FeedDataSourceimplements DataSource

{private File file = null;private String contentType = "";

public FeedDataSource(File file, String contentType){this.file = file;this.contentType = contentType;

}

public String getContentType(){return contentType;

}

public InputStream getInputStream()throws IOException

{return new FileInputStream(file);

}

public String getName(){return file.getName();

}

public OutputStream getOutputStream()throws IOException

{return new FileOutputStream(file);

}

}

In Listing 10, a file resource is encapsulated within the FeedDataSource class.This class performs I/O operations for a given file resource.

Implement the FrontController servlet

You implement a FrontController servlet to interact with various components,connectors, and context classes to dispatch incoming requests from user agents.The servlet then responds to user agents with the representational state forresources generated from business services, if appropriate for the request, that theservlet represents.

Listing 11 provides an example of handling the standard HttpServlet doGet()method. The context that the request targets is extracted and used to retrieve theserver component to which the request data is dispatched.

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 16 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Listing 11. The doGet() method for the FrontController servlet class

protected void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException

{HTTPConnector connector =

(HTTPConnector)Connectors.getConnector(Protocol.HTTP);HTTPServerComponent serverComponent =

(HTTPServerComponent)connector.addServer(request.getServerPort());

String contextRootPath = this.getServletContext().getRealPath("/");String contextPath = request.getContextPath() + "/"

+ this.getServletName();serverComponent.addContext(contextRootPath, contextPath);

Representation representation = null;

try{

representation =serverComponent.getContext(request,

this).handleGet(new HTTPRequest(request));}catch (Exception e){

e.printStackTrace();throw new ServletException("Error: " + e);

}

new HTTPResponse(response).write(representation.getContentType(),representation.getInputStream());

}

In Listing 11, the doGet method of the FrontController class illustrates how arequest is received and processed. A connector for the HTTP protocol is retrievedand used to add/retrieve a server component. The targeted resource context objectis retrieved from the server component. The resource context object is then used toprocess the GET request. A Resource representation object is returned by theresource context object. The representation object is then transmitted back to therequestor using the HTTPResponse class.

Implement the business logic

You employ a BusinessService class to implement business logic that will returnmodel data representing member resources of specific APP collections. TheBusinessService classes embody the logic that acts on specific collections andresource representations with an implementation of thejavax.activation.DataHandler class and thejavax.activation.DataSource interface appropriate for the collection ormember resource's Atom feed.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 24

Page 18: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Listing 12 provides an example of a business service that encapsulates a collectionof Atom feed resources.

Listing 12. Feed collection business-service class

public class CollectionServiceimplements BusinessService

{// todo: read RESOURCES_DIR from config or system property//private static final String RESOURCES_DIR = "resources";

private String contextRootPath = "";

private String contextPath = "";

public CollectionService(String contextRootPath,String contextPath)

{this.contextRootPath = contextRootPath;this.contextPath = contextPath;

}

protected String getContextPath(){return contextPath;

}

protected String filePathFromRequest(Request httpReq){return contextRootPath + RESOURCES_DIR

+ ((HTTPRequest) httpReq).getRequest().getPathInfo();}

protected void writeToFile(Request request,File file,boolean append)

throws IOException,FileNotFoundException

{System.out.println("writeToFile called");

InputStream inStream = ((HTTPRequest) request).getInputStream();byte[] dataBuf = new byte[4096];

FileOutputStream outStream = new FileOutputStream(file, append);int bytesRead = 0;while ((bytesRead = inStream.read(dataBuf)) > 0){

System.out.println("Writing [" + bytesRead + " bytes]");outStream.write(dataBuf, 0, bytesRead);

}

outStream.flush();outStream.close();

}

public Representation create(Request request)throws ServiceExecutionException

{System.out.println("CollectionService.create()");

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 18 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

// todo: create feed from structured storage with DAO//String filePath = filePathFromRequest(request);File file = new File(filePath);

try{

boolean append = false;writeToFile(request, file, append);

}catch (Exception e){

e.printStackTrace();throw new ServiceExecutionException(e);

}

FeedRepresentation representation = new FeedRepresentation(file);

return representation;}

public Representation read(Request request)throws ServiceExecutionException

{System.out.println("CollectionService.read()");

// todo: read feed from structured storage with DAO//String filePath = filePathFromRequest(request);File file = new File(filePath);if (file.exists() == false){

throw new ServiceExecutionException("Feed file ["+ filePath + "] does not exist.");

}

FeedRepresentation representation = new FeedRepresentation(file);

return representation;}

public Representation update(Request request)throws ServiceExecutionException

{System.out.println("CollectionService.update()");

// todo: update feed from structured storage with DAO//String filePath = filePathFromRequest(request);File file = new File(filePath);FeedRepresentation representation = new FeedRepresentation(file);

try{

boolean append = (file.exists() ? true : false);writeToFile(request, file, append);

}catch (Exception e){

e.printStackTrace();throw new ServiceExecutionException(e);

}

return representation;}

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 24

Page 20: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

public void delete(Request request)throws ServiceExecutionException

{System.out.println("CollectionService.delete()");

// todo: delete feed from structured storage with DAO//String filePath = filePathFromRequest(request);System.out.println("CollectionService.delete() - resolving feed file ["

+ filePath + "]");File file = new File(filePath);System.out.println("CollectionService.delete() - feed file resolved");if (file.exists()){

System.out.println("CollectionService.delete() - deleting feed file");

if (file.delete() == false){

System.out.println("CollectionService.delete() - feed deletion failed");throw new ServiceExecutionException("Error deleting feed ["

+ filePath + "]");}System.out.println("CollectionService.delete() - feed deletion succeeded");

}else{

System.out.println("CollectionService.delete() - feed file ["+ filePath + "] does not exist");

}}

}

Listing 12 provides an example of a business service class that encapsulates acollection of Atom feed resources. This class uses physical files as the source ofeach feed resource. Operations on each feed resource are defined by "CRUD"methods (create, read, update, and delete). This common abstraction of operationsallows the underlying physical source to change without affecting the methodsignatures or the service interface.

With the business services representing collections of specific feed resources inplace, user agents can now send requests to the FrontController of the originserver, which dispatches the request to the appropriate business service. Thebusiness service performs the necessary business logic, acting upon any targetedresources. The targeted resources are created, accessed, updated, and deleted asthe logic dictates. Representational state for the targeted member resourcesgenerated from the request is passed back to the FrontController servlet, whichis then relayed back to the user agent, if required, in the form of an HTTP response.

Section 6. Summary

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 20 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Wrap up

REST is a software architecture style and collection of principles for buildingdistributed systems using existing protocols and standards to act on resourcesrepresenting data or services. REST has evolved (or devolved) to describe anyframework that transmits data over a protocol such as HTTP without relying onadditional semantic layers or session management.

The APP is an HTTP-based protocol that accesses, publishes, and modifiesresources representing data or services. The APP is designed around the idea ofusing the standard operations that the HTTP protocol provides (GET, PUT, POST,and DELETE) to introspect collections of member resources and to manipulatemember resources representing things like blog entries, images, documents, andcalendar entries.

In this tutorial, you learned the basics of REST and the APP. You also learned howto apply REST within an enterprise system to send and receive HTTP requests andresponses through a Java servlet-based system using the APP to facilitateaccessing and manipulating the representational state of member resources andcontainers of member resources.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 24

Page 22: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Downloads

Description Name Size Download method

Source code for this article x-restatompp.zip 27KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 22 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

Resources

Learn

• Create and edit Web resources with the Atom Publishing Protocol (James Snell,developerWorks, October 2006): Get a high-level overview of the protocol and itsbasic operation and capabilities. Continue with other articles in the Getting toknow the Atom Publishing Protocol series.

• Architectural Styles and the Design of Network-based Software Architectures:Read Roy Fielding's PhD dissertation on REST.

• The Atom Publishing Protocol: Read the IETF working draft of this standard forcontent publishing and management.

• The Atom Syndication Format (RFC 4287): Get the details on this XML-baseddocument format that describes feeds that syndicate Web content such asweblogs and news headlines to Web sites and directly to user agents.

• Internationalized Resource Identifiers (IRIs): Learn more about this new protocolelement which is a sequence of characters from the Universal Character Set anda complement to URIs [RFC2396].

• developerWorks XML zone: Learn all about XML at the developerWorks XMLzone with articles, tutorials, forums, and more.

• The technology bookstore: Browse for books on these and other technical topics.

• IBM XML certification: Find out how you can become an IBM-Certified Developerin XML and related technologies.

• XML technical library: See the developerWorks XML Zone for a wide range oftechnical articles and tips, tutorials, standards, and IBM Redbooks.

• developerWorks technical events and webcasts: Stay current with technology inthese sessions.

Get products and technologies

• IBM trial software: Build your next development project with trial softwareavailable for download directly from developerWorks.

Discuss

• XML zone discussion forums: Participate in any of several XML-centered forums.

• developerWorks blogs: Check out these blogs and get involved in thedeveloperWorks community.

ibm.com/developerWorks developerWorks®

Writing REST services© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 24

Page 24: Writing REST services · collections, grouped into workspaces. • Category document: A document that describes the categories allowed in a collection. The following sections discuss

• XML zone discussion forums: Participate in any of several XML-centered forums.

• developerWorks XML zone: Share your thoughts: After you read this article, postyour comments and thoughts in this forum. The XML zone editors moderate theforum and welcome your input.

About the author

J. Jeffrey HansonJeff Hanson has more than 20 years of experience in the software industry, includingwork as senior engineer for the Windows OpenDoc project and lead architect for theRoute 66 framework at Novell. Jeff is currently the CTO for Max International, Inc.,where he is responsible for architecting and building systems using Web services,micro-formats, XML, Java/J2EE, PHP, mobile technologies, and Windows APIs. Jeff isthe author of numerous articles and books, including .NET versus J2EE Web Services:A Comparison of Approaches, Pro JMX: Java Management Extensions, and WebServices Business Strategies and Architectures.

Trademarks

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Microsoft, Windows, and the Windows logo are trademarks of Microsoft Corporation inthe United States, other countries, or both.Other company, product, or service names may be trademarks or service marks ofothers.

developerWorks® ibm.com/developerWorks

Writing REST servicesPage 24 of 24 © Copyright IBM Corporation 1994, 2008. All rights reserved.