of 84 /84
REST Carol McDonald, Java Architect

RESTful Web Services with JAX-RS

Embed Size (px)

Citation preview

Page 1: RESTful Web Services with JAX-RS

REST

Carol McDonald, Java Architect

Page 2: RESTful Web Services with JAX-RS

2

Agenda

• REST Primer• RESTful Design and API Elements• Building a Simple Service• Status• Q & A

Page 3: RESTful Web Services with JAX-RS

3

REpresentational State Transfer

Client State1 Client State2

REST Web ServiceGet http://www.depot.com/parts

Response XML data =REpresentational State

Transfer

● The URL identifies the resource● HTTP GET method operates on the resource● html page is transferred to the browser

– REpresentational State transferThe page (application state) is stored on the client (browser)Click on the link (resource) in page (hypermedia)

New state transfer occurs

Page 4: RESTful Web Services with JAX-RS

4

REST architecture for the Web

Ad d r e s s ab le

R e s o u r c es

We bC o n t a in e r

Ad d r e s s ab le

R e s o u r c es

We bC o n t a in e r

We bp la t f o rm s

Page 5: RESTful Web Services with JAX-RS

5

REST Tenets

• Resources (nouns)> Identified by a URI, For example:

●http://www.parts-depot.com/parts

• Methods (verbs) to manipulate the nouns> Small fixed set:

●GET, PUT, POST, DELETE– Read, Update, Create, Delete

• Representation of the Resource > data and state transferred between client and server> XML, JSON...

• Use verbs to exchange application state and representation

Page 6: RESTful Web Services with JAX-RS

6

HTTP ExampleRequestGET /music/artists/beatles/recordings HTTP/1.1Host: media.example.comAccept: application/xml

ResponseHTTP/1.1 200 OKDate: Tue, 08 May 2007 16:41:58 GMTServer: Apache/1.3.6Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?><recordings xmlns="…"> <recording>…</recording> …</recordings>

Method Resource

Representation

Statetransfer

Page 7: RESTful Web Services with JAX-RS

7

REST in Five Steps*

• Give everything an ID• Use standard methods• Link things together• Multiple representations• Stateless communications

http://www.infoq.com/articles/rest-introduction

Uniform Interface

Page 8: RESTful Web Services with JAX-RS

8

Give Every Thing an Id

http://company.com/customers/123456

Resource Collection name

Primary key

http://company.com/customers/123456/orders/12

http://example.com/orders/2007/11http://example.com/products?color=green

URI is the id, Every resource has a URI

• URIs identify :> items, collections of items, virtual and physical objects, or

computation results.

Page 9: RESTful Web Services with JAX-RS

9

REST in Five Steps*

• Give everything an ID• Use standard methods• Link things together• Multiple representations• Stateless communications

http://www.infoq.com/articles/rest-introduction

Uniform Interface

Page 10: RESTful Web Services with JAX-RS

10

Use Standard HTTP Methods: GET = Read

• GET to retrieve information> Should not modify anything > Cacheable> Example

●GET /store/customers/123456

“Give me the XML data for this customer”

Page 11: RESTful Web Services with JAX-RS

11

Use Standard HTTP Methods: POST = Create

• POST to add new information• add the entity , append to the container resource

●POST /store/customers<customer>

<name>carol</name>

</customer>

Response

HTTP/1.1 201 Created

Location: http://store/customers/789

Add the customer specified in the POSTDATA to the list of customers. return URI

Page 12: RESTful Web Services with JAX-RS

12

Use Standard HTTP Methods: PUT = Update

• PUT to update information• Full entity create/replace used when you know

the “id”> Example

●PUT /store/customers/123456<customer>

<name>jane</name>

</customer>

Replaces the representation of the customer with an

updated version.

Page 13: RESTful Web Services with JAX-RS

13

Use Standard HTTP Methods: DELETE

• Remove (logical) an entity> Example

●DELETE /store/customers/123456

Deletes the customer '123456” from the system

Page 14: RESTful Web Services with JAX-RS

14

Use Standard Methods:

http://www.infoq.com/articles/rest-introduction

Order CustomerMgmt Example

Page 15: RESTful Web Services with JAX-RS

15

Use Standard Methods:• /orders

– GET - list all orders– POST - submit a new order

/orders/{order-id}> GET - get an order representation> PUT - update an order> DELETE - cancel an order

/orders/average-sale– GET - calculate average sale

• /customers– GET - list all customers– POST - create a new customer

/customers/{cust-id}> GET - get a customer representation> DELETE- remove a customer

/customers/{cust-id}/orders– GET - get the orders of a customer

Order CustomerMgmt Example

http://www.infoq.com/articles/rest-introduction

Page 16: RESTful Web Services with JAX-RS

16

Use Standard HTTP Methods

• HTTP Get, Head> Should not modify anything > Cache-able

●With Correct use of Last-Modified and ETag• Idempotency:

> PUT, DELETE, GET, HEAD can be repeated and the results are the same

Page 17: RESTful Web Services with JAX-RS

17

REST in Five Steps*

• Give everything an ID• Use standard methods• Link things together• Multiple representations• Stateless communications

* Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf

Page 18: RESTful Web Services with JAX-RS

18

Link Things Together

<prop self="http://example.com/orders/101230">

<customer ref="http://example.com/customers/bar">

<product ref="http://example.com/products/21034"/>

<amount value="1"/>

</order>

• Representations contain links to other resources

• Service provides links in response to the Client > Enables client to move the application from one

state to the next by following a link

Representations contain links to other resources:

Page 19: RESTful Web Services with JAX-RS

19

Link Things Together

• Representations contain links to other resources

• Put a service in different states by following links and filling in forms> “Hypermedia as the engine of application state”> HTML, XML, JSON, N3 can all be Hypermedia

• Client is in charge> Service offers potential states> Service does not impose state transition order

Page 20: RESTful Web Services with JAX-RS

20

REST in Five Steps*

• Give everything an ID• Use standard methods• Link things together• Multiple representations• Stateless communications

* Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf

Page 21: RESTful Web Services with JAX-RS

21

Multiple Representations

• Offer data in a variety of formats, for different needs> XML> JSON> (X)HTML

• Support content negotiation> Accept headerGET /fooAccept: application/json

> URI-basedGET /foo.json

Page 22: RESTful Web Services with JAX-RS

22

content negotiationRequestGET /music/artists/beatles/recordings HTTP/1.1Host: media.example.comAccept: application/xml

ResponseHTTP/1.1 200 OKDate: Tue, 08 May 2007 16:41:58 GMTServer: Apache/1.3.6Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?><recordings xmlns="…"> <recording>…</recording> …</recordings>

Format

Representation

Multiple Representations

Content-type HTTP

header

Accept HTTP header

Page 23: RESTful Web Services with JAX-RS

23

REST in Five Steps*

• Give everything an ID• Use standard methods• Link things together• Multiple representations• Stateless communications

* Inspired by Stefan Tilkov: http://www.innoq.com/blog/st/presentations/2008/2008-03-13-REST-Intro--QCon-London.pdf

Page 24: RESTful Web Services with JAX-RS

24

Stateless Communications

• HTTP protocol is stateless• Everything required to process a request

contained in the request> No client session on the server> Eliminates many failure conditions

• application state kept on Client • Service responsible for resource state

Page 25: RESTful Web Services with JAX-RS

25

Common Patterns: Container, ItemServer in control of URI • Container – a collection of items• List catalog items: GET /catalog/items• Add item to container: POST /catalog/items

> with item in request> URI of item returned in HTTP response header> e.g. http://host/catalog/items/1

• Update item: PUT /catalog/items/1 > with updated item in request

Good example: Atom Publishing Protocol

Page 26: RESTful Web Services with JAX-RS

26

Common Patterns: Map, Key, ValueClient in control of URI

• List key-value pairs: GET /map• Put new value to map: PUT /map/{key}

> with entry in request> e.g. PUT /map/dir/contents.xml

• Read value: GET /map/{key}• Update value: PUT /map/{key}

> with updated value in request• Remove value: DELETE /map/{key}

• Good example: Amazon S3

Page 27: RESTful Web Services with JAX-RS

27

Key Benefits

• Server side> Uniform Interface> Cacheable> Scalable> Easy failover

• Client side> Easy to experiment in browser> Broad programming language support> Choice of data formats> bookmarkable

Page 28: RESTful Web Services with JAX-RS

28

Agenda

• REST Primer• RESTful Design and API Elements with JAX-RS• Building a Simple Service• Status• Q & A

Page 29: RESTful Web Services with JAX-RS

29

JAX-RS: Clear mapping to REST concepts

• High level, Declarative> Uses @ annotation in POJOs

• Jersey – reference implementation of JSR 311●Download it from http://jersey.dev.java.net●Comes with Glassfish, Java EE 6●Tools support in NetBeans

> Four other open source implementations:●Apache CXF●JBoss RESTEasy●Restlet●Triaxrs

Page 30: RESTful Web Services with JAX-RS

30

Give Everything an ID

• “Thing” == resource class> POJO, No required interfaces

• ID provided by @Path annotation> Relative to deployment context> Annotate class or “sub-resource locator” method

@Path("orders/{id}")

public class OrderResource {

@Path("customer")

CustomerResource getCustomer(...) {...}

}

http://host/ctx/orders/12

http://host/ctx/orders/12/customer

Page 31: RESTful Web Services with JAX-RS

31

Use Standard Methods• Annotate resource class methods with standard

method> @GET, @PUT, @POST, @DELETE, @HEAD

• annotations on parameters specify mapping from request data

• Return value mapped to http response

@Path("orders/{order_id}")

public class OrderResource {

@GET

Order getOrder(@PathParam("order_id") String id) {

...

}

}

Page 32: RESTful Web Services with JAX-RS

32

Multiple RepresentationsStatic and dynamic content negotiation

• Annotate methods or classes > @Produces matches Accepts header> @Consumes matches Content-Type header

@GET@Consumes("application/json")@Produces({"application/xml","application/json"})String getOrder(@PathParam("order_id") String id) { ...}

Page 33: RESTful Web Services with JAX-RS

33

Multiple Representations: JAX-RS consuming

• Annotated method parameters extract client request information> @PathParam extracts information from the request

URI●

> @QueryParam extracts information from the request URI query parameters●

http://host/catalog/items/123

http://host/catalog/items/?start=0

Page 34: RESTful Web Services with JAX-RS

34

Multiple Representations: JAX-RS consuming

@Path("/items/")@ConsumeMime(“application/xml”)public class ItemsResource {

@GET ItemsConverter get(@QueryParam("start")

int start) {...

}

@Path("{id}/") ItemResource getItemResource(@PathParam("id")Long id){ ... }

}

http://host/catalog/items/?start=0

http://host/catalog/items/123

Page 35: RESTful Web Services with JAX-RS

35

Multiple Representations:Supported Types

• JAX-RS can automatically (un)-marshall between HTTP request/response and Java types

• “Out-of-the-box” support for the following> text/xml, application/xml, application/json – JAXB

class> */* – byte[]> text/* – String> application/x-www-form-urlencoded

-MultivaluedMap<String, String>

request

response

Page 36: RESTful Web Services with JAX-RS

36

Multiple Representations

@Post@ConsumeMime(“application/x­www­form­urlencoded”)@ProduceMime(“application/xml”)

public JAXBClass updateEmployee(MultivalueMap<String, String> form) {

...

Converted to a map for accessing form's field

converted to XML

Page 37: RESTful Web Services with JAX-RS

37

Multiple Representations: producing a response

@Path(“/items”)class Items {

@POST @ProduceMime(“application/xml”) Response create(Ent e) { // persist the new entry, create URI return Response.created(

uriInfo.getAbsolutePath(). resolve(uri+"/")).build();

}}

Use Response classto build “created”response

Page 38: RESTful Web Services with JAX-RS

38

Uniform interface: HTTP request and response

C: POST /items HTTP/1.1C: Host: host.comC: Content-Type: application/xmlC: Content-Length: 35C: C: <item><name>dog</name></item>

S: HTTP/1.1 201 CreatedS: Location: http://host.com/employees/1234S: Content-Length: 0

Page 39: RESTful Web Services with JAX-RS

39

Response Codes and Custom Responses

• JAX-RS returns default response codes> GET returns 200 OK > PUT returns 201 CREATED

• See > http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

200 OK

201 Created

202 Accepted

203 Non-Authoritative Information

204 No Content

205 Reset Content

206 Partial Content

207 Multi-Status

226 IM Used

. . .

Page 40: RESTful Web Services with JAX-RS

40

JAX-RS provides Response class

@PUTpublic Response putUser(

@PathParam(“id”) int id) {

if (!id.equals(userid) )            return Response.status(409).entity(                       "userids differ").build();

● can construct more sophisticated return result

● Can build responses for redirects, errors, ok, setting headers, etc

JAX-RS provides Response class:to specify response codes, to add onto the response

Page 41: RESTful Web Services with JAX-RS

41

WebApplicationException Example

@GETpublic Employee getEmployee(

@PathParam(“id”) int id) {if (!doesEmployeeExist(id))

 throw new WebApplicationException(              new Throwable("Resource for " +              uriInfo.getAbsolutePath() +               " does not exist."), 404);

● Use it when the method has a return type

● Simple error indicator

Response:HTTP Status 404 -

Page 42: RESTful Web Services with JAX-RS

42

Link Things Together

• UriInfo provides information about the request URI and the route to the resource

• UriBuilder provides facilities to easily build URIs for resources

@Context UriInfo info;

OrderResource r = ...

UriBuilder b = info.getBaseUriBuilder();

URI u = b.path(OrderResource.class).build(r.id);

Page 43: RESTful Web Services with JAX-RS

43

Statelessness: JAX-RS

• The default component lifecycle is per-request> A new instance created for every request> Reduces concurrency issues

• HTTP session life-cycle is not supported> On server side Developer must model state

●As resource state in the representations

Page 44: RESTful Web Services with JAX-RS

44

Agenda

• REST Primer• RESTful Design and API Elements• Building a Simple Service • Deployment Options• Status

Page 45: RESTful Web Services with JAX-RS

45

Example RESTful Catalog

Page 46: RESTful Web Services with JAX-RS

46

Example RESTful Cataloghttp://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html

Page 47: RESTful Web Services with JAX-RS

47

Example RESTful Catalog Service

CatalogDatabase

TestClient

dojoClient

Web container(GlassFish™)

+REST API

Browser(Firefox)

Resource Classes

Convertor Classes

Entity Classes

HTTP

Page 48: RESTful Web Services with JAX-RS

48

URIs and Methods:

● /items– GET - list all items– POST – add item to catalog

/items/{id}> GET - get an item representation> PUT - update an item> DELETE – remove an item

Item Catalog Example

http://www.infoq.com/articles/rest-introduction

Page 49: RESTful Web Services with JAX-RS

49

Methods @Path(“/items”)class ItemsResource { @GET Items get() { ... } @POST Response create(Item) { ... }}

class ItemResource { @GET Item get(...) { ... } @PUT void update(...) { ... } @DELETE void delete(...) { ... }} Java method name is not significant

The @HTTP method is the method

Page 50: RESTful Web Services with JAX-RS

50

RESTful Catalog

DB

Registration Application

JAX-RS class

Dojo clientJAXB class

Entity Class

ItemsConverter

Item

ItemsResource

● Dojo client, JAX-RS, JAXB, JPA

Page 51: RESTful Web Services with JAX-RS

51

Entity Classes• Use JPA to map/retrieve data from the database as

entities• expose entities as RESTful resources

> entity = resource identified by URL

public class Item {

int id; String name; String descr; String url;

}

@Entity

@Id

ItemID NAME DESC URL

http://host/catalog/items/123

Page 52: RESTful Web Services with JAX-RS

52

Converter Classes

• JAXB to convert the domain objects (JPA entities) into XML and/or JSON.

DB

JAX-RS class

Dojo clientJAXB class

Entity Class

ItemsConverter

Item

ItemsResource

Page 53: RESTful Web Services with JAX-RS

53

ItemConverter JAXB annotated @XmlRootElement(name = "item")public class ItemConverter { private Item entity; private URI uri;

@XmlAttribute public URI getUri() { return uri; } @XmlElement public Long getId() { return (expandLevel > 0) ? entity.getId() : null; } ... }

Page 54: RESTful Web Services with JAX-RS

54

XML

<item uri="http://localhost/Web/resources/items/1/"> <description> black cat is nice</description> <id>1</id> <imagethumburl>/images/anth.jpg</imagethumburl> <name>not Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item>

Page 55: RESTful Web Services with JAX-RS

55

JSON

{ "@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.", "id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg" }

Page 56: RESTful Web Services with JAX-RS

56

ItemsConverter JAXB annotated @XmlRootElement(name = "items")public class ItemsConverter { private Collection<ItemConverter> items; private URI uri;

@XmlAttribute public URI getUri() { return uri; } @XmlElement public Collection<ItemConverter> getItem() { ... return items; }}

Page 57: RESTful Web Services with JAX-RS

57

XML<?xml version="1.0" encoding="UTF-8"?> <items uri="http://localhost/Web/resources/items/"> <item uri="http://localhost/Web/resources/items/1/"> <description> black cat is nice</description> <id>1</id> <imagethumburl>/images/anth.jpg</imagethumburl> <name>not Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item> <item . . . </item> </items>

Page 58: RESTful Web Services with JAX-RS

58

JSON

{ "@uri":"http://host/catalog/resources/items/", "item":[ {"@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.", "id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"}, {"@uri":"http://host/catalog/resources/items/2/", "name":"Fluffy Cat", "description":"A great pet for a hair stylist! "id":"2", "imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"} ] }

Page 59: RESTful Web Services with JAX-RS

59

Resource Classes> Items Resource retrieves updates a collection of Item entities> /items – URI for a list of Items> Item resource retrieves or updates one Item entity> /item/1 – URI for item 1

DB

JAX-RS class

Dojo clientJAXB class

Entity Class

ItemsConverter

Item

ItemsResource

Page 60: RESTful Web Services with JAX-RS

60

Get Items @Path("/items/")public class ItemsResource { @Context protected UriInfo uriInfo; @GET @Produces("application/json") public ItemsConverter get(){ return new ItemsConverter( getEntities(), uriInfo.getAbsolutePath()); }

Performs JPAQuery, returns listof entities

JAXB class

responds with JSON

responds to the URI http://host/catalog/items/

responds to HTTP GET

Page 61: RESTful Web Services with JAX-RS

61

Get Item@Path("/items/")public class ItemsResource {

@Path("{id}/") public ItemResource getItemResource(@PathParam("id") Long id) { return new ItemResource(id, context); }}

public class ItemResource { @GET @Produces("application/json") public ItemConverter get() { return new ItemConverter(getEntity(), context.getAbsolutePath(), expandLevel); }

JAXB class

http://host/catalog/items/123

Page 62: RESTful Web Services with JAX-RS

62

Dojo Client

• Use dojo.xhrGet to make HTTP method call to catalog service to get JSON items data:

{"items": {"@uri":"http://host/catalog/resources/items/", "item":[ {"@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.", "id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"}, {"@uri":"http://host/catalog/resources/items/2/", "name":"Fluffy Cat", "description":"A great pet for a hair stylist! "id":"2", "imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"} ] } }

Page 63: RESTful Web Services with JAX-RS

63

Example RESTful Catalog

Page 64: RESTful Web Services with JAX-RS

64

Dojo client index.html

<button dojoType="dijit.form.Button" onclick="next"> Next</button>

<div id="grid" dojoType="dojox.Grid" model="model" structure="layout" autoWidth="true" >

http://weblogs.java.net/blog/caroljmcdonald/archive/2008/08/a_restful_pet_c.html

Grid widget model=data to display in grid

structure=layout for Grid

Page 65: RESTful Web Services with JAX-RS

65

Dojo client.js formatImage = function(value) { if (!value) return '&nbsp;'; return "<img src='" + value + "'/>"; };// Data Grid layout// A grid view is a group of columnsvar view1 = { cells: [ [ {name: 'Name', field: "name"}, {name: 'Description', field: "description"}, {name: 'Photo',field: "imagethumburl",

formatter: formatImage, }, {name: 'Price',field: "price"} ] ]};// a grid layout is an array of views.var layout = [ view1 ];// the model= collection of objects to be displayed in the gridmodel = new dojox.grid.data.Objects(null,null);

model=data to display in grid

layout for Grid

Page 66: RESTful Web Services with JAX-RS

66

RESTful Pet Catalog Web Service

Ad d r e s s ab le

R e s o u r c es

We b C o n t a in e r

Server

Client

http://petstore/catalog/resources/items/

HTTP GET

{"url":"http://store/catalog/item1",{"url":"http://store/catalog/item2"}

Response JSON slide urls

Page 67: RESTful Web Services with JAX-RS

67

Dojo client.js // make request to the items web servicefunction loadTable(page){ start = page * batchSize; var targetURL = "resources/items/?start="+

encodeURIComponent(start); dojo.xhrGet({ url: targetURL, handleAs: "json", load: handleResponse, error: handleError });}// Process the response from the items web servicefunction handleResponse(responseObject, ioArgs){ // set the model object with the returned items list model.setData(responseObject.items.item); }function next() { page =page + 1; loadTable(page);}

Performs HTTPGET on url catalog/items

Callback puts response data in dojo model

for grid table

Page 68: RESTful Web Services with JAX-RS

68

Client & WADL• NetBeans IDE can generate JavaScript client stubs from a

WADL or projects containing RESTful resources

• NetBeans IDE exposes popular SaaS services using WADLs and can generate Java code to access them•

> Learn more at https://wadl.dev.java.net/> Example:

<application> <resources base="http://localhost:11109/CustomerDB/resources/"> <resource path="/items/"> <method name="GET"> <request> <param default="0" type="xs:int" style="query" name="start"/> <param default="10" type="xs:int" style="query" name="max"/> </request> <response> <representation mediaType="application/xml"/> </response> </method> </resource> </resources> .....

</application>

Page 69: RESTful Web Services with JAX-RS

69

Example RESTful Catalog

Page 70: RESTful Web Services with JAX-RS

70

Page 71: RESTful Web Services with JAX-RS

71

JavaFX Stage Scene

Stage is the top level container window

Scene is a drawing surface container that holds the scene graph nodes.

content holds JavaFX graphical elements which define the graphical content of the application.

Page 72: RESTful Web Services with JAX-RS

72

JavaFX Stage Scene // Application User Interfacevar stageContent: Node[];

stageContent = [bgImage, nextButton, backButton, titleText, thumbImageViewGroup, fullImageView];def stage = Stage { title: "Pet Catalog" width: 201 height: 201 scene: Scene { content: Group { content: bind stageContent } fill: Color.TRANSPARENT }}

top level container window

container holds the scene graph

holds graphical elements

Page 73: RESTful Web Services with JAX-RS

73

JavaFX Stage Scene var stageContent: Node[];

stageContent = [bgImage, nextButton, backButton, titleText, thumbImageViewGroup, fullImageView];def stage = Stage { title: "Pet Catalog" width: 201 height: 201 scene: Scene { content: Group { content: bind stageContent } fill: Color.TRANSPARENT }}

Page 74: RESTful Web Services with JAX-RS

74

RESTful Pet Catalog Web Service

Ad d r e s s ab le

R e s o u r c es

We b C o n t a in e r

Server

Client

http://petstore/catalog/resources/items/

HTTP GET

Response XML items

<item> <imageurl>http://host/catalog/images/anthony.jpg</imageurl> <name>Friendly Cat</name> <price>307.10</price> <productid>feline01</productid> </item>

Page 75: RESTful Web Services with JAX-RS

75

JavaFX HttpRequestfunction loadImageMetadata() { var start=page * 9; var request: HttpRequest = HttpRequest { location: "http://localhost:8080/catalog/resources/items/" method: HttpRequest.GET onInput: function(input: java.io.InputStream) { var parser = PhotoPullParser{}; photos = parser.parse(input); } onDone: function() { updateImages(); } } request.enqueue();}

Performs HTTPGET on url catalog/items

Callback puts response data images

in grid

Parses xml data

Page 76: RESTful Web Services with JAX-RS

76

JavaFX HttpRequestpublic class PhotoPullParser { public function parse(input: InputStream): Photo[] { var photos: Photo[]; var photo: Photo; def parser = PullParser {input: input onEvent: function(event: Event) { if (event.type == PullParser.START_ELEMENT) { if(event.qname.name == "item" and event.level == 1) { photo = Photo { }; } } else if (event.type == PullParser.END_ELEMENT) { if(event.qname.name == "item" and event.level == 1) { insert photo into photos; } else if(event.qname.name == "imagethumburl" and event.level == 2) { photo.imagethumburl = event.text; } ... } } } parser.parse(); return photos;}

<item> <imageurl>http://y.jpg</imageurl> <name>Friendly Cat</name> ... </item>

Page 77: RESTful Web Services with JAX-RS

77

Agenda

• REST Primer• RESTful Design and API Elements• Building a Simple Service• Status• Q & A

Page 78: RESTful Web Services with JAX-RS

78

Java SE• RuntimeDelegate used to create instances of

a desired endpoint class• Application supplies configuration information

> List of resource classes and providers as subclass of ApplicationConfig

• Implementations can support any Java type> Jersey supports Grizzly (see below), LW HTTP server

and JAX-WS Provider

ApplicationConfig config = ...

RuntimeDelegate rd = RuntimeDelegate.getInstance();

Adapter a = rd.createEndpoint(config, Adapter.class);

SelectorThread st = GrizzlyServerFactory.create(

“http://127.0.0.1:8084/”, a);

Page 79: RESTful Web Services with JAX-RS

79

Servlet

• JAX-RS application packaged in WAR like a servlet

• For JAX-RS aware containers> web.xml can point to ApplicationConfig subclass

• For non-JAX-RS aware containers> web.xml points to implementation-specific Servlet;

and > an init-param identifies the ApplicationConfig

subclass• Resource classes and providers can access Servlet request, context, config and response via injection

Page 80: RESTful Web Services with JAX-RS

80

Java EE 6 Plans• JAX-RS is part of Java EE 6• Applications deployed in a Java EE 6 Web container

will have access to additional resources:> Resources @Resources > EJB @EJB> ...

• Stateless session EJBs as resource classes

• More portable deployment with Servlet 3.0

Page 81: RESTful Web Services with JAX-RS

81

Agenda

• REST Primer• RESTful Design and API Elements• Building a Simple Service• Deployment Options• Status

Page 82: RESTful Web Services with JAX-RS

82

Summary

• REST architecture is gaining popularity> Simple, scalable and the infrastructure is already in

place

• JAX-RS (JSR-311) provides a high level declarative programming model> http://jersey.dev.java.net

• Jersey available• 1.0 and 1.0.1: Glassfsh v2/v3 • 1.0: NetBeans 6.5

Page 83: RESTful Web Services with JAX-RS

83

For More Information• Official JSR Page

> http://jcp.org/en/jsr/detail?id=311

• JSR Project> http://jsr311.dev.java.net/

• Reference Implementation> http://jersey.dev.java.net/

• Marc's Blog> http://weblogs.java.net/blog/mhadley/

• Paul's Blog> http://blogs.sun.com/sandoz/

• Jakub's Blog> http://blogs.sun.com/japod/

• Carol's Blog> http://weblogs.java.net/blog/caroljmcdonald/

Page 84: RESTful Web Services with JAX-RS

84

Carol McDonald Java Architect

http://weblogs.java.net/blog/caroljmcdonald/