Transcript

REST – REPRESENTATIONAL STATE TRANSFER & JAX-RS

Ramesh Mandaleeka

Agenda●Prerequisites

○URI/URL○HTTP

●What is REST?●REST based services●Java based implementations

○JAX-WS (JSR 311)

Prerequisites

URI/URL●URI – Uniform Resource Identifier●URL – Uniform Resource Locator●Location or address of the resource on the

web http://sonybmg.com/cps/artists/shakira#bio ●Uniform approach to represent a resource[scheme:][//authority][path][?query][#fragment]

●Resource○ shakira

●Representation○ XML, HTML, RSS, JSON, ATOM …

HTTP – Hyper Text Transfer Protocol●RFC - http://ietf.org/rfc/rfc2616.txt

●HTTP is a stateless protocol●HTTP methods (in order of popularity):‣ GET, POST‣ PUT, DELETE‣ HEAD, OPTIONS, TRACE

HTTP Methods vs. VERBSHTTP Method

CRUD Action

Description Status Codes

POST CREATE

Create a resource and other operations, as it has no defined semantics

201, 400, 422

GET RETRIEVERetrieve a representation of a resource

200, 301, 410

PUT UPDATECreate or update a resource

200, 301, 400, 410

DELETE DELETE Delete a resource 200, 204

Standardized HTTP Response CodesHTTP Status Code Meaning

1xx Informational

2xxSuccess

3xxRedirection

4xxClient Error

5xxServer Error

200 - OK 301 - Moved Permanently 400 - Bad Request 201 - Created 410 - Gone 204 - No Content 422 - Unprocessable Entity

GET●GET Example

HTTP/1.1 200 OKDate: …Server:...Content-Length: 1456Content-Type:application/html<html></html>

GET /artists/shakiraHost: sonybmg.comAccept: application/xml

POST●POST Example

HTTP/1.1 201 CreatedDate: …Content-Length: 0Location: http://sonybmg.com/artists/shakira

POST /artists/Host: sonybmg.com<html>…</html>

PUT●PUT Example

HTTP/1.1 201 CreatedDate: …Content-Length: 0

PUT /artists/shakiraHost: sonybmg.com<html></html>

DELETE●DELETE Example

HTTP/1.1 204 No ContentDate: …Content-Length: 0

DELETE/artists/shakiraHost: sonybmg.com<html></html>

HTTP Architectural Strength●Replication of stateless content is low-cost

& easy.●The GET and HEAD methods SHOULD

NOT have the significance of taking any action, other than retrieval.

●We can cache the GET responses ●The HTTP GET, PUT and DELETE

methods are idempotent, but the POST method creates new resources

REST - “Representational State Transfer”

REST - “Representational State Transfer”

●“REST” was introduced in 2000 in the doctoral dissertation of Roy Fielding

http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

●Imposes some architectural constraints that are applicable to the architecture of a distributed system

●Architectural style of the web & not a standard

REST Principles●Application state and functionality are

abstracted into resources●Every resource is uniquely addressable

using a universal syntax used in hypermedia links. Resource is an addressable space

Courtesy: http://en.wikipedia.org/wiki/Representational_State_Transfer

REST Principles cont…●All resources share a uniform interface for

the transfer of state between client and resource, consisting of○A constrained set of well-defined operations○A constrained set of content types, optionally

supporting code on demand●A protocol which is:

○Client-server○Stateless○Cacheable○Layered

Designing a RESTful application●Identify resources●Design URIs (URLs)●Content Negotiation●Identify method semantics●Select response codes

Courtesy: http://bitworking.org/news/How_to_create_a_REST_Protocol

Designing a RESTful application●Identify resources - Artists●Design URL’s http://sonybmg.

com/cps/artists●Content Negotiation

○What type of content will be used to pass information from client to server

○What type of content will be passed back to the client

●Identify method semantics (GET, POST, …)○Resources methods are mapped to HTTP

methods●Select response codes (200, 204…)

Domain Example●Artist information system

ArtistInformationService+getArtistsList()+getArtistInfoByName(String name)+addArtistInfo(Artist)+updateArtistInfo(Artist)+deleteArtistInfo(id)

●+getArtistsList()○ GET http://sonybmg.com/cps/getartistlist

●+getArtistInfoByName(String name)○ GET http://sonybmg.com/cps/getartist?name=shakria

●+addArtistInfo(Artist)○ POST form data to http://sonybmg.com/cps/createartist

●+updateArtistInfo(Artist)○ POST form data to http://sonybmg.com/cps/updateartist

●+deleteArtistInfo(id)○ POST http://sonybmg.com/cps/deleteartist?name=shakira

Traditional Approach

●+getArtistsList()○ GET http://sonybmg.com/cps/artists

●+getArtistInfoByName(String name)○ GET http://sonybmg.com/cps/artists/shakria

●+addArtistInfo(Artist)○ POST the artist data to http://sonybmg.com/cps/artists

●+updateArtistInfo(Artist)○ PUT the artist data at http://sonybmg.com/cps/artists

●+deleteArtistInfo(id)○ DELETE http://sonybmg.com/cps/artists/shakira

REST Approach

JSR 311:JAX-RS: The Java™ APIfor Restful Web Services

JAX-RS: JSR-311● Java™ API for RESTful Web Services

http://jcp.org/aboutJava/communityprocess/edr/jsr311/index.html

● POJO as a Web resources● HTTP-centric● Format & Container independent● Can be hosted in a Java EE container

JSR-311 Approach●One class per resource “type”●Methods to handle HTTP requests●Use of Java 5 Annotations to specify

○URI Mapping (@Path, @Encoded)○Mapping to HTTP methods(@GET, @POST,

@PUT,@DELETE, @HEAD or @HttpMethod )○Mapping of URI components(@QueryParam,

@PathParam, @CookieParam, @FormParam, @MatrixParam, @DefaultValue)

○HTTP headers(@HeaderParam)○HTTP entities to method parameters and return

types○MIME type information(@Produces, @Consumes)

Main packages● javax.ws.rs

○ High-level interfaces and annotations used to create RESTful service resources.

● javax.ws.rs.core○ Low-level interfaces and annotations used to create

RESTful service resources. ● javax.ws.rs.ext

○ APIs that provide extensions to the types supported by the JAX-RS API.

Example@Path("/cps/artists/{name}")public class ArtistResource {private ArtstService artistService = …; @GET @Produces(MediaType.APPLICATION_XML)public String getArtistByNameAsXML(@PathParam("name") String artistName) {return artistService.getArtistAsXML(artistName) ;}@GET @Produces(MediaType.APPLICATION_XHTML_XML)public String getArtistByNameAsXHML(@PathParam("name") String artistName) {return artistService.getArtistAsXHML(artistName) ;}@GET @Path("#{albumName}")@Produces(MediaType.APPLICATION_XML)public String getArtistAlbumAsXML(@PathParam("name") String artistName, @PathParam("albumName") String artistAlbumName) {return artistService.getArtistAlbumAsXML(artistName, artistAlbumName) ;}@POST @Consumes(MediaType. APPLICATION_XML)public String createArtist(String artistXml) {try { artistService.createArtist(artistXml);return Response.ok().build();} catch (Exception e) {e.printStackTrace();return Response.status(400).entity("Please send well-formed XML\n").type("text/plain").build();}}}Note: javax.ws.rs.core.MediaType abstracts content types.

URI Template●URI Templates define URI strings with

embedded variables(are denoted by curly braces).

●The URI template http://sonybmg.com/cps/artists/{name}

Maps to Shakira URL from previous example http://sonybmg.com/cps/artists/shakira

@Path●The @Path can be annotated on a class

or on a method.●@Path annotation on a class

○Maps class to a URI space, relative to a base URI

○Base URI http://sonybmg.com/cps will be resolved to http://sonybmg.com/cps/artists

●@Path annotation on a method ○Maps method relative to the class URI○URI http://sonybmg.com/cps/artists will be

resolved to http://sonybmg.com/cps/artists/shakira

@Path●Template Parameters can be validated

using regular expressions E.g. @Path(“/artists/{name: [a-zA-Z][a-zA-Z_0-

9]}")

Note: Failure of validation causes a 404 as the request cannot be mapped to a resource

@Path●An @Path value may or may not, begin or

end with a forward slash (/). ●The request URLs that end or do not end

with a forward slash will both be matched. ●Jersey has a redirection mechanism,

which, if enabled, automatically performs redirection to a request URL ending in a / if a request URL does not end in a / and the matching @Path does end in a /.

@PathParam●Binds the value of a URI template

parameter or a path segment containing the template parameter to ○a resource method parameter○a resource class field○a resource class bean property.

●A class annotated with: @Path(“artists/{name}") can have methods annotated whose arguments are annotated with @PathParam(“name").

@QueryParam●Binds the value(s) of a HTTP query

parameter to a resource method parameter, resource class field, or resource class bean property.

@GET @Produces(MediaType.APPLICATION_XML)public String getAllArtists (@QueryParam(“fromIdx”) long fromIdx, @DefaultValue(“1000”)@QueryParam(“totalCount”) long totalCount) {return artistService. getAll(fromIdx, totalCount);}●Note: If DefaultValue cannot be transformed

to enclosing data type, then an HTTP 400 (Client Error) response is returned.

Restrictions of QueryParam & PathParam●@QueryParam and @PathParam can only be

used on the following Java types:○ All primitive types except char○ All wrapper classes of primitive types except

Character○ Have a constructor that accepts a single String

argument○ Any class with the static method named valueOf

(String) that accepts a single String argument○ Any class with a constructor that takes a single String

as a parameter○ List<T>, Set<T>, or SortedSet<T>, where T matches

the already listed criteria. Sometimes parameters may contain more than one value for the same name. If this is the case, these types may be used to obtain all values

@FormParam, @CookieParam & @HeaderParam

●@FormParam – This annotation is used to extract parameters from a form submission. It is used in conjunction with HTTP POST method.

●@CookieParam – CookieParam is used to extract values form a cookie.

●@HeaderParam – This annotation is used to extract parameters from HTTP header

@MatrixParam

●@MatrixParam - This annotation is used to extract parameters from matrix URI.

Note: ● By default QueryParam, PathParam, FormParam or MatrixParam

values will be decoded. e.g., Bryan%20Adams will be converted to Bryan Adams.

● If you want to disable this automatic decoding of parameter values use javax.ws.rs.Encoded annotation in conjunction to QueryParam, PathParam, FormParam or MatrixParam annotations

● Using this annotation on a method will disable decoding for all parameters. Using this annotation on a class will disable decoding for all parameters of all methods.

Request Method Designator Annotations●@HEAD - Indicates that the annotated method

responds to HTTP HEAD requests ●@GET - Indicates that the annotated method

responds to HTTP GET requests●@PUT - Indicates that the annotated method

responds to HTTP PUT requests ●@DELETE - Indicates that the annotated

method responds to HTTP DELETE requests ●@POST - Indicates that the annotated method

responds to HTTP POST requestsNote:

● The @HttpMethod(“GET”) and @GET or synonymous.● See javax.ws.rs.core.Response.Status.Family for HTTP status code

categories.

Configuring the Resource with the Runtime●web.xml

<servlet><servlet-name>Jersey Web Application</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class><init-param><param-name>com.sun.jersey.config.property.packages</param-name><param-value>com.sonybmg.cps.resources</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>Jersey Web Application</servlet-name><url-pattern>/*</url-pattern></servlet-mapping>

Exception Handling

●JAX-RS has a RuntimeException class, WebApplicationException, that allows you to abort your JAX-RS service method.

●It can take an HTTP status code or even a Response object as one of its constructor parameters.

Exception Handling@POST @Consumes(MediaType. APPLICATION_XML)

public String createArtist(String artistXml) {

try {

artistService.createArtist(artistXml);

return Response.ok().build();

} catch (XMLFormatException e) {

logger.error(“Invalid XML {}”, e);

ResponseBuilder builder = Response.status(Status.NOT_FOUND);

builder.type("text/html");

builder.entity("<h3>"Please send well-formed XML\n"</h3>");

throw new WebApplicationException(builder.build());

throw new WebApplicationException(

Response.status(400).entity("Please send well-formed XML\n").type("text/plain").build());

return Response.status(400)

.entity("Please send well-formed XML\n").type("text/plain").build();

}

}

Other Frameworks

●Restlet●JBoss RESTEasy●Apache CXF●Jersey

Tools of Trade

●Below are the tools that to test REST applications.

http://code.google.com/p/rest-client/

●Mozilla Plug-inhttps://addons.mozilla.org/en-US/firefox/addon/2691

top related