• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Rest – representational state transfer
 

Rest – representational state transfer

on

  • 262 views

 

Statistics

Views

Total Views
262
Views on SlideShare
262
Embed Views
0

Actions

Likes
0
Downloads
6
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Rest – representational state transfer Rest – representational state transfer Presentation Transcript

    • REST – REPRESENTATIONALSTATE TRANSFER & JAX-RSRamesh 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 theweb 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 TransferProtocol●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. VERBSHTTPMethodCRUDActionDescription Status CodesPOST CREATECreate a resource andother operations, as ithas no definedsemantics201, 400, 422GET RETRIEVERetrieve arepresentation of aresource200, 301, 410PUT UPDATECreate or update aresource200, 301, 400, 410DELETE DELETE Delete a resource 200, 204
    • Standardized HTTP ResponseCodesHTTP Status Code Meaning1xx Informational2xxSuccess3xxRedirection4xxClient Error5xxServer Error200 - OK 301 - Moved Permanently 400 - Bad Request201 - Created 410 - Gone204 - No Content 422 - Unprocessable Entity
    • GET●GET ExampleHTTP/1.1 200 OKDate: …Server:...Content-Length: 1456Content-Type:application/html<html></html>GET /artists/shakiraHost: sonybmg.comAccept:application/xml
    • POST●POST ExampleHTTP/1.1 201 CreatedDate: …Content-Length: 0Location: http://sonybmg.com/artists/shakiraPOST /artists/Host: sonybmg.com<html>…</html>
    • PUT●PUT ExampleHTTP/1.1 201 CreatedDate: …Content-Length: 0PUT /artists/shakiraHost: sonybmg.com<html></html>
    • DELETE●DELETE ExampleHTTP/1.1 204 No ContentDate: …Content-Length: 0DELETE/artists/shakiraHost: sonybmg.com<html></html>
    • HTTP Architectural Strength●Replication of stateless content is low-cost& easy.●The GET and HEAD methods SHOULDNOT have the significance of taking anyaction, other than retrieval.●We can cache the GET responses●The HTTP GET, PUT and DELETEmethods are idempotent, but the POSTmethod creates new resources
    • REST - “RepresentationalState Transfer”
    • REST - “Representational StateTransfer”●“REST” was introduced in 2000 in thedoctoral dissertation of Roy Fieldinghttp://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm●Imposes some architectural constraintsthat are applicable to the architecture of adistributed system●Architectural style of the web & not astandard
    • REST Principles●Application state and functionality areabstracted into resources●Every resource is uniquely addressableusing a universal syntax used inhypermedia links. Resource is anaddressable spaceCourtesy: http://en.wikipedia.org/wiki/Representational_State_Transfer
    • REST Principles cont…●All resources share a uniform interface forthe transfer of state between client andresource, consisting of○A constrained set of well-defined operations○A constrained set of content types, optionallysupporting 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 codesCourtesy: 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 passinformation from client to server○What type of content will be passed back tothe client●Identify method semantics (GET, POST,…)○Resources methods are mapped to HTTP
    • Domain Example●Artist information systemArtistInformationService+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=shakiraTraditional 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/shakiraREST Approach
    • JSR 311:JAX-RS: The Java™ APIfor Restful Web Services
    • JAX-RS: JSR-311●Java™ API for RESTful Web Serviceshttp://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 returntypes○MIME type information(@Produces, @Consumes)
    • Main packages●javax.ws.rs○ High-level interfaces and annotations used to createRESTful service resources.●javax.ws.rs.core○ Low-level interfaces and annotations used to createRESTful service resources.●javax.ws.rs.ext○ APIs that provide extensions to the types supported by theJAX-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") StringartistAlbumName) {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 XMLn").type("text/plain").build();}}}
    • URI Template●URI Templates define URI strings withembedded variables(are denoted by curlybraces).●The URI template http://sonybmg.com/cps/artists/{name}Maps to Shakira URL from previousexample http://sonybmg.com/cps/artists/shakira
    • @Path●The @Path can be annotated on a classor on a method.●@Path annotation on a class○Maps class to a URI space, relative to a baseURI○Base URI http://sonybmg.com/cps will beresolved 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 beresolved to http://sonybmg.com/cps/artists/shakira
    • @Path●Template Parameters can be validatedusing regular expressionsE.g. @Path(“/artists/{name: [a-zA-Z][a-zA-Z_0-9]}")Note: Failure of validation causes a 404 asthe request cannot be mapped to a resource
    • @Path●An @Path value may or may not, begin orend with a forward slash (/).●The request URLs that end or do not endwith a forward slash will both be matched.●Jersey has a redirection mechanism,which, if enabled, automatically performsredirection to a request URL ending in a /if a request URL does not end in a / andthe matching @Path does end in a /.
    • @PathParam●Binds the value of a URI templateparameter or a path segment containingthe 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 annotatedwhose arguments are annotatedwith @PathParam(“name").
    • @QueryParam●Binds the value(s) of a HTTP queryparameter to a resource method parameter,resource class field, or resource class beanproperty.@GET@Produces(MediaType.APPLICATION_XML)public String getAllArtists (@QueryParam(“fromIdx”) long fromIdx,@DefaultValue(“1000”)@QueryParam(“totalCount”) longtotalCount) {
    • Restrictions of QueryParam &PathParam●@QueryParam and @PathParam can only beused on the following Java types:○All primitive types except char○All wrapper classes of primitive types exceptCharacter○Have a constructor that accepts a single Stringargument○Any class with the static method named valueOf(String) that accepts a single String argument○Any class with a constructor that takes a single Stringas a parameter○List<T>, Set<T>, or SortedSet<T>, where T matchesthe already listed criteria. Sometimes parameters maycontain more than one value for the same name. Ifthis is the case, these types may be used to obtain all
    • @FormParam, @CookieParam &@HeaderParam●@FormParam – This annotation is used toextract parameters from a formsubmission. It is used in conjunction withHTTP POST method.●@CookieParam – CookieParam is used toextract values form a cookie.●@HeaderParam – This annotation is usedto extract parameters from HTTP header
    • @MatrixParam●@MatrixParam - This annotation is usedto extract parameters from matrix URI.Note:● By default QueryParam, PathParam, FormParam or MatrixParamvalues will be decoded. e.g., Bryan%20Adams will be converted toBryan Adams.● If you want to disable this automatic decoding of parameter valuesuse javax.ws.rs.Encoded annotation in conjunction to QueryParam,PathParam, FormParam or MatrixParam annotations● Using this annotation on a method will disable decoding for allparameters. Using this annotation on a class will disable decodingfor all parameters of all methods.
    • Request Method DesignatorAnnotations●@HEAD - Indicates that the annotated methodresponds to HTTP HEAD requests●@GET - Indicates that the annotated methodresponds to HTTP GET requests●@PUT - Indicates that the annotated methodresponds to HTTP PUT requests●@DELETE - Indicates that the annotatedmethod responds to HTTP DELETE requests●@POST - Indicates that the annotated methodresponds to HTTP POST requestsNote:● The @HttpMethod(“GET”) and @GET or synonymous.● See javax.ws.rs.core.Response.Status.Family for HTTP status code
    • Configuring the Resource with theRuntime●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 youto abort your JAX-RS service method.●It can take an HTTP status code or even aResponse object as one of its constructorparameters.
    • 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 XMLn"</h3>");throw new WebApplicationException(builder.build());throw new WebApplicationException(Response.status(400).entity("Please send well-formed XMLn").type("text/plain").build());return Response.status(400).entity("Please send well-formed XMLn").type("text/plain").build();}}
    • Other Frameworks●Restlet●JBoss RESTEasy●Apache CXF●Jersey
    • Tools of Trade●Below are the tools that to test RESTapplications.http://code.google.com/p/rest-client/●Mozilla Plug-inhttps://addons.mozilla.org/en-US/firefox/addon/2691