77
BeJUG JAX-RS Representational State Transfer theory and JAX-RS

BeJUG JAX-RS Event

Embed Size (px)

Citation preview

Page 1: BeJUG JAX-RS Event

BeJUG JAX-RSRepresentational State Transfer

theory and JAX-RS

Page 2: BeJUG JAX-RS Event

Me, Me, Me…

• Alex Van Boxel– R&D Engineer : Progress Software

• DataDirect : All sorts of middleware stuff ( database,xml, xquery, data virtualization )

• Low-level stuff• Low-level stuff– So the Enterprise stack is a hobby project

– To keep track of what happens in the real world

• So don’t kill me if I can’t answer all yourquestions about this topic.

Page 3: BeJUG JAX-RS Event

BeJUG JAX-RS Agenda

• REST theory– Core principles

– Anti-Patterns

– Patterns

• JAX-RS• JAX-RS– Introduction

– The Code• JAX-RS (1) : Life cycle en Path matching

• JAX-RS (2) : Content and Update

• JAX-RS (3) : Providers

Page 4: BeJUG JAX-RS Event

RESTRepresentational State Transfer, Core

principles and (Anti)patterns.

Page 5: BeJUG JAX-RS Event

BeJUG JAX-RS Agenda

• REST theory– Core principles

– Anti-Patterns

– Patterns

• JAX-RS• JAX-RS– Introduction

– The Code• JAX-RS (1) : Life cycle en Path matching

• JAX-RS (2) : Content and Update

• JAX-RS (3) : Providers

Page 6: BeJUG JAX-RS Event

RESTRepresentational State Transfer

Page 7: BeJUG JAX-RS Event

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

Page 8: BeJUG JAX-RS Event

(1) Addressability

• All resources should have an ID

• In RESTful web services: URI representation

• Everything should be a resource• The more, the better• The more, the better

• Process step: ex. salery increase should be a resource

• Actually violated by a lot of framework, whereeverything is tunneled though POST

Page 9: BeJUG JAX-RS Event

(1) Addressability (cont.)

• Nice example: Amazon• Everything has an ID

• You can send link• http://www.amazon.com/gp/product/B002JCSV8A/

• More framework SHOULD supportaddressability

• First step to being RESTful

Page 10: BeJUG JAX-RS Event

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

Page 11: BeJUG JAX-RS Event

(2) Connectedness

• Link everything together<member id=“/../members/me”>

<membership ref=“/../memberships/0042”/>

<link ref=“delete” method=“DELETE” ref=“..”/>

</member></member>

• Provide as much as possible• Relations

• Actions

• This will help the client discover the actions

Page 12: BeJUG JAX-RS Event

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

Page 13: BeJUG JAX-RS Event

(3) Uniform Interface

• You limit yourself to a Uniform interface forALL resources

• HTTP methods• GET/PUT/POST/DELETE• GET/PUT/POST/DELETE

• HTTP:GET safe get representation

– 80% reading (web optimized)

– If your don’t make it safe, it your fault if googledeletes your record, by following a link

Page 14: BeJUG JAX-RS Event

(3) Uniform Interface

• HTTP:PUT

– Create a new resource (app manager id)

– Modify an existing resource

• HTTP:POST• HTTP:POST

– Create a new resource (server manager id)

• Create subordinate resources

• HTTP:DELETE

– Delete a resource

Page 15: BeJUG JAX-RS Event

Interlude (1+2+3)

• /memberships/• GET: list all events (ref= to real entities)

• POST: create a membership (id is container managed)

• PUT: not used (405: Method not allowed, Accept=GET,POST)

• DELETE: not used (idem)• DELETE: not used (idem)

• /memberships/00042• GET: get a membership with ID 00042

• POST: not used (405, Accept=GET,PUT,DELETE)

• PUT: update a membership

• DELETE: delete a membership

Page 16: BeJUG JAX-RS Event

Interlude (1+2+3)

• /events/• GET: list all events

• POST: not used (id is client managed 405, Accept=GET)

• PUT: t(405, Accept=GET )

• DELETE: not used (405, Accept=GET )• DELETE: not used (405, Accept=GET )

• /events/2010jaxrs• GET: get an event with ID 2010jaxrs

• POST: not used (405, Accept=GET,PUT,DELETE)

• PUT: create/update an event

• DELETE: delete an event

Page 17: BeJUG JAX-RS Event

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

Page 18: BeJUG JAX-RS Event

(4) Representations

• You interact with the resource through arepresentation

• Representation : ANY usefull information aboutthe state of a resource

• Accept: header• Accept: header– Tell the server what the client understands

• Supply machine readable formats– Even different formats (xml, json)– Or different formats– Supply human readable formats (XHTML)

Page 19: BeJUG JAX-RS Event

(4) Representations

• Example: a person– Browser: Accept: application/xml

• Send xml+ref=“xslt”

– Old browser: Accept: text/html• Send transformed xml+xslt > html

– Outlook• Import text/x-vcard

– Internal business app (old and new)• application/vnd.bejug.v1.member+xml

• application/vnd.bejug.v2.member+xml

Page 20: BeJUG JAX-RS Event

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

Page 21: BeJUG JAX-RS Event

(5) Statelessness

• Your communication with the server isstateless

• Server doesn’t keep state

– HTTP Request happens in complete isolation– HTTP Request happens in complete isolation

– HTTP Request includes all information to full therequest

– The server never relies on information from aprevious request

Page 22: BeJUG JAX-RS Event

(5) Statelessness (cont.)

• Possible states of the server are resources

– The client should not trick the server into a stateto listen to a certain request

• Application- versus Resource state?• Application- versus Resource state?

– Application state should only live on the client

Page 23: BeJUG JAX-RS Event

(5) Statelessness (cont.)

• Example: Search Engine

• Stateless– Application state (on client) current query and page

• search?query=jaxrs&page=2

• search?query=jaxrs&page=3• search?query=jaxrs&page=3

• Statefull (not REST)• search?query=jaxrs

• search?page=2

– State would make individual HTTP request simpler, butwould make the protocal more complex

Page 24: BeJUG JAX-RS Event

(5) Statelessness (cont.)

• Example: Shopping card

– Classic implementation: Memory state

– Make it a resource… persist it…

– Accept as an URL– Accept as an URL

Page 25: BeJUG JAX-RS Event

(5) Statelessness (cont.)

• Stateless brings a few benefits

– Scalability

• No 2 request depend on each other

• Load-balancing ( Cluster )• Load-balancing ( Cluster )

– Cacheable

• Again not depended on a previous state

• So easier to cache

• HTTP is stateless by default• You have to do some work to break it

Page 26: BeJUG JAX-RS Event

So is REST simple?

• Need a shift in thinking

• Identifying resources

• Externalizing the state

• But if done right, it can be a useful tool• Consumption oriented

• Inversion of Control

Page 27: BeJUG JAX-RS Event

REST ANTI-PATTERNSDon’t do this, Don’t do that

Page 28: BeJUG JAX-RS Event

REST ANTI-PATTERNS

1. Tunneling over GET

2. Tunneling over POST

3. Ignore cache

4. Ignore status code4. Ignore status code

5. Hypermedia & MIME

6. Break self descriptiveness

Page 29: BeJUG JAX-RS Event

Anti-Pattern (1): Tunneling over GET

• Tunneling thought GET

– http://ex.org/endpoint?method=delete&id=666

• Resources are not identified by URI

• HTTP method doesn’t match semantics• HTTP method doesn’t match semantics

• Not bookmarkable

Page 30: BeJUG JAX-RS Event

Anti-Pattern (1): Tunneling over GET

• Is this a RESTful URI:some-app/method-findEvent?id=2010jax-rs

• Accidently RESTful

• -> read only API. OK, but what if it’s extended• -> read only API. OK, but what if it’s extendedwith a update API using the same URI scheme.Better:/events/2010jax-rs

Page 31: BeJUG JAX-RS Event

Anti-Pattern (2): Tunneling over POST

• Tunneling though POST• Is actually what SOAP does

• Not cacheable for reads

• Again not bookmarkable• Again not bookmarkable

• A lot of other framework violate this as well

Page 32: BeJUG JAX-RS Event

Anti-Pattern (2): Tunneling over POST

• <soap:Env>

• Endpoint -> dead end

• WSDL -> generate client specifically written forthat endpointthat endpoint

• In defense: SOAP-WS not be meant to be onthe web, but generic

Page 33: BeJUG JAX-RS Event

Anti-Pattern (3) : Ignore caching

• Ignoring caching• ETag support

• If-Modified-Since

• Don’t ignore on server, and don’t forget the client• Don’t ignore on server, and don’t forget the client

Page 34: BeJUG JAX-RS Event

Anti-Pattern (3) : Ignore caching

• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…• Is the stock qoute updates? NO … waiting 2s…

• 80% requests : GET• Provide an expires value• After the expire time, check the E-TAG• You don’t need to check it every 2 seconds when you know

in advance it has a 15 minutes delay.

Page 35: BeJUG JAX-RS Event

Anti-Pattern (3) : Ignore caching

• E-Tag : A HASH value

• If-not-monified: 404 not modified

Page 36: BeJUG JAX-RS Event

Anti-Pattern (4): Ignore status codes

• Ignoring status codes• HTTP has a rich set of application level error codes

– 200: OK

– 201: Created

– 404: Not found (resource not found)– 404: Not found (resource not found)

– 409: Conflict (concurrent update?)

– 410: Gone (it was here but is now gone?)

• Accepts: What methods are allowed

Page 37: BeJUG JAX-RS Event

Anti-Pattern (4): Ignore status codes

• Did the operation succeed?

• Everything created as intended?

• Can we continue?

• Did you accept the request?• Did you accept the request?

Page 38: BeJUG JAX-RS Event

Small sample

• 100 Continue• 101 Switch Protocols• 200 OK• 201 Created• 202 Accepted• 203 Non-Authoritative• 204 No Content• 205 Reset Content• 206 Partial Content• 300 Multiple Choices

• 404 Not Found• 304 Method Not Allowed• 406 Not Acceptable• 407 Proxy Authentication Required• 408 Request Timeout• 409 Conflict• 410 Gone• 411 Length Required• 412 Precondition Failed• 413 Request Entity Too Lange• 300 Multiple Choices

• 301 Moved Permanently• 302 Found• 303 See Oher• 304 Not Modified• 305 Use Proxy• 307 Temporary Redirect• 400 Bad Request• 401 Unauthorized• 402 Payment Required• 403 Forbidden

• 413 Request Entity Too Lange• 414 Request-URI Too Long• 415 Unsupported Media Type• 416 Requested Range Not Satisfiable• 417 Expectation Failed• 500 Internal Server Error• 501 Not Implemented• 502 Bad Gateway• 503 Service Unavailable• 504 Gateway Timeout• 505 HTTP Version Not Supported

Page 39: BeJUG JAX-RS Event

Anti-Pattern (5): Hypermedia & MIME

• Link everything together• Ideally a client should get everywhere from one URI

• Even know what actions are available

• No dead ends (what are the relations?)

• Ignore MIME types• Ignore MIME types• HTTP allows content negotiation

• Ex: Machine readable (XML) vs Human Readable (PDF)

• Ex: Language binding: XML, JSON, YAML

• vnd.mytype (but look for a standard one)

• XHTML (with micro-formats?)

Page 40: BeJUG JAX-RS Event

Break self descriptiveness

• URI: good, but do you need a manual to toknow how to constuct the URI?

• You should discover the URI’s

– <link ref=“update” …/>– <link ref=“update” …/>

Page 41: BeJUG JAX-RS Event

PATTERNSThe good

Page 42: BeJUG JAX-RS Event

URI design

• WARNING: Don’t worry too much about URIdesign

• But it’s good practice

• Linking is important, you should think about• Linking is important, you should think aboutthat, more than having a nice URI design

• Make them self descriptive

Page 43: BeJUG JAX-RS Event

Named Link

• Standard method of giving a meaning to a link

– alternate representations• <link rel=“alternate” type=“application/atom+xml”href=“self”/>

– actions– actions• <link ref=“delete” method=“DELETE” href=“self”/>

– navigation• <link ref=“next” type=“application/xml”method=“GET” href=“self?page=2”/>

Page 44: BeJUG JAX-RS Event

Collection Resource

• Related resources grouped• /events/

• /memberships/0042/invoices/

• /members/• /members/

• Collections are resources (accessable by URI)

• Collection representation should can containusefull information

• point to other resources

• contain summary information n

Page 45: BeJUG JAX-RS Event

Read only views

• Multiviews of the same collection/events/ < all

/events/?tag=REST

/events/?limit=10

/events/2009/10//events/2009/10/

/memberships/0042/invoices/?outstanding=true

Page 46: BeJUG JAX-RS Event

Resource Creation

• POST to an entity to a collection resource

• You receive a 201: location• If you do it again you create yet another resource

• After POST you can update with the URI using PUT• After POST you can update with the URI using PUT

• Alternative: Client UUID: PUT it

Page 47: BeJUG JAX-RS Event

Paging

Return subset

Embed links to the next/prev chunks<link rel=“self” type=“” ref=“”/>

<link rel=“next” type=“” ref=“”/><link rel=“next” type=“” ref=“”/>

<link rel=“prev” type=“” ref=“”/>

/events/?page=2

Page 48: BeJUG JAX-RS Event

Notification Polling

• Polling: Not for real time update (for real timeextensions look@PubSubHubbub)

• Expose a view as RSS/Atom

• BUT: ensure cache control headers• BUT: ensure cache control headers• ETag

• Last-Modified

• Atom views: Loose coupling: better thentraditional SOA

Page 49: BeJUG JAX-RS Event

Conflict

• Protect against concurrent modification– Lost update problem

• HTTP solutions– Provide Etag– Provide Etag

– Last-Modified Headers

– Pre-conditions

• HTTP response codes– 409 Conflict

– 412 Pre-Condition Failed

Page 50: BeJUG JAX-RS Event

Extensions

• Supports linking to different representations

• It’s not one of my favorites, but…

• Increases testability/members/r2d2/members/r2d2

/members/r2d2.xhtml

/members/r2d2.json

/members/r2d2.vcard

Page 51: BeJUG JAX-RS Event

Canonical Representation

• Similar like implementing .toString() in Java

– It helps debugging

• HTML presentation

• HTML forms for input• HTML forms for input

Page 52: BeJUG JAX-RS Event

Deep ETags

• Hash calculated on limited set of data (notcomplete response)

Page 53: BeJUG JAX-RS Event

Externalize Caching

• Server: Concentrate on the correct headers• E-tag

• Last Modified

• Deep E-tags• Deep E-tags

• Simplified

Page 54: BeJUG JAX-RS Event

Putting theory into practice

Page 55: BeJUG JAX-RS Event

BeJUG JAX-RS Agenda

• REST theory– Core principles

– Anti-Patterns

– Patterns

• JAX-RS• JAX-RS– Introduction

– The Code• JAX-RS (1) : Life cycle en Path matching

• JAX-RS (2) : Content and Update

• JAX-RS (3) : Providers

Page 56: BeJUG JAX-RS Event

JAX-RS INTRO

Java™ API for RESTful

Web Services

Page 57: BeJUG JAX-RS Event

JSR311 : JAX-RS

• Annotation driven API

• Help developers build RESTful Web Services

– Guides novice developers

– Intuitive for advanced developers– Intuitive for advanced developers

• J2EE6 integration

Page 58: BeJUG JAX-RS Event

JSR311 : JAX-RS

• Remember: This is a tool

• You still need to learn the core REST principles

• You can still abuse the API to build non-RESTfull applicationRESTfull application

• It’s not the API that should be RESTfull

• It’s the application that you build that need to beRESTfull

Page 59: BeJUG JAX-RS Event

JAX-RS implementations

• CXF

• Jersey• The reference implementation. Bundled with GlassFish

• RESTEasy• RESTEasy• JBoss implementation. Seems to have some nice

extensions

• RESTlet• REST api pioneers, now support JAX-RS as a plus

• Seems to have a good client api (have a look…)

Page 60: BeJUG JAX-RS Event

JAX-RS (1): LIFE CYCLE AND PATHMATCHING

The Code

Page 61: BeJUG JAX-RS Event

JAX-RS (1): Life cycle and Pathmatching

• The Resource Classes

– Lifecycle

• Default is per request (makes sense in REST)

1. Constructor is called (with params if available)1. Constructor is called (with params if available)

2. Dependencies are injected (don’t use thedependencies in the constructor!

3. Appropriate method is called

4. Resource is GC’ed

Page 62: BeJUG JAX-RS Event

JAX-RS (1): Life cycle and Pathmatching

• Annotations– Path matching

• @Path

– Parameter matching• @PathParam, @QueryParam, @CookieParam,• @PathParam, @QueryParam, @CookieParam,

@HeaderParam, @MatrixParam

• @DefaultValue

– Injection• @Context

• Request, UriInfo, Application, SecurityContext, <T>

– Method (@GET, …)

Page 63: BeJUG JAX-RS Event

JAX-RS (1) CODE SESSIONLife cycle and Path matching

Page 64: BeJUG JAX-RS Event

JAX-RS (2) : CONTENT AND UPDATEThe Code

Page 65: BeJUG JAX-RS Event

JAX-RS (2) : Content and Update

• HTTP verbs (methods)• @GET, @POST, @PUT, @DELETE

• Content Negotiation• @Consumes and @Produces• @Consumes and @Produces

• Response Utilities• UriBuilder and Response

• Standard Entity Providers• What JavaType <> Content Type

Page 66: BeJUG JAX-RS Event

JAX-RS (2) : Content and Update

• Content Negotiation

– Incoming:

• @Consumes(mime-type)

– Outgoing:– Outgoing:

• @Produces(mime-type)

• Mime

– type (text, application, …)

– subtype ( plain, html, … , xml, json, …)

Page 67: BeJUG JAX-RS Event

JAX-RS (2) : Content and Update

• Response

– Helps to create a proper response

• Errors

• Headers• Headers

• Redirect

• UriBuilder

– Helps to create URI’s

Page 68: BeJUG JAX-RS Event

JAX-RS (2) : Content and Update

• Standard Entity Providers• Byte[] : mime ( */* )

• String : mime ( */* )

• InputStream : mime ( */* )

• Reader : mime ( */* )• Reader : mime ( */* )

• File : mime ( */* )

• DataSource : mime ( */* )

• Source : mime ( */*xml )

• JAXB : mime ( */*xml )

• MulticalueMap<String,String> : mime (application/x-www-form-urlencoded )

Page 69: BeJUG JAX-RS Event

JAX-RS (2) CODE SESSIONContent and Update

Page 70: BeJUG JAX-RS Event

JAX-RS (3) : PROVIDERSThe Code

Page 71: BeJUG JAX-RS Event

JAX-RS (3) Providers

• 3 types of providers

– Context Provider

– Entity Provider

• MessageBody(Writer/Reader)• MessageBody(Writer/Reader)

– Exception Mapping Provider

• All annotated with @Provider

Page 72: BeJUG JAX-RS Event

JAX-RS (3) CODE SESSIONProviders

Page 73: BeJUG JAX-RS Event

JAX-RS : The Code

• URL mapping• @Path, @GET, @PathParam, @QueryParam,…

• Consuming requests• @POST, @FormParam

• JAXB integration• JAXB integration• Producing/Consument

• Content Negotiation• @Consumes and @Produces

• Building URI and Response• UriBuilder and Response

Page 74: BeJUG JAX-RS Event

JAX-RS : The advanced

• Advanced, but oh so useful

• MessageBodyWriter/Reader

– @Provider: VCard example

– @Provider: XStream integration– @Provider: XStream integration

Page 75: BeJUG JAX-RS Event

REFERENCES

Java™ API for RESTful

Web Services

Page 76: BeJUG JAX-RS Event

References

• Video

– Parleys: Stefan Tilkov (RESTful Design)

– Parleys: JAX-RS: The Java API for RESTful Web s.

• Audio• Audio

– Episode 98: Stefan Tilkov on REST

• Web

– JAX-RS spec ( quite readable )

Page 77: BeJUG JAX-RS Event

References

• Book

– RESTful Web Services

• Me again• Me again• http://alex.vanboxel.be

• email:[email protected]

• http://twitter.com/alexvb

+