BeJUG JAX-RS Event

Preview:

Citation preview

BeJUG JAX-RSRepresentational State Transfer

theory and JAX-RS

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.

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

RESTRepresentational State Transfer, Core

principles and (Anti)patterns.

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

RESTRepresentational State Transfer

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

(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

(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

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

(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

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

(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

(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

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

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

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

(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)

(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

Core REST principles

1. Addressability

2. Connectedness

3. Uniform Interface

4. Representations4. Representations

5. Statelessness

(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

(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

(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

(5) Statelessness (cont.)

• Example: Shopping card

– Classic implementation: Memory state

– Make it a resource… persist it…

– Accept as an URL– Accept as an URL

(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

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

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

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

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

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

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

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

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

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.

Anti-Pattern (3) : Ignore caching

• E-Tag : A HASH value

• If-not-monified: 404 not modified

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

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?

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

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?)

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” …/>

PATTERNSThe good

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

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”/>

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

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

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

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

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

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

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

Canonical Representation

• Similar like implementing .toString() in Java

– It helps debugging

• HTML presentation

• HTML forms for input• HTML forms for input

Deep ETags

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

Externalize Caching

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

• Last Modified

• Deep E-tags• Deep E-tags

• Simplified

Putting theory into practice

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

JAX-RS INTRO

Java™ API for RESTful

Web Services

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

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

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…)

JAX-RS (1): LIFE CYCLE AND PATHMATCHING

The Code

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

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, …)

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

JAX-RS (2) : CONTENT AND UPDATEThe Code

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

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, …)

JAX-RS (2) : Content and Update

• Response

– Helps to create a proper response

• Errors

• Headers• Headers

• Redirect

• UriBuilder

– Helps to create URI’s

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 )

JAX-RS (2) CODE SESSIONContent and Update

JAX-RS (3) : PROVIDERSThe Code

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

JAX-RS (3) CODE SESSIONProviders

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

JAX-RS : The advanced

• Advanced, but oh so useful

• MessageBodyWriter/Reader

– @Provider: VCard example

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

REFERENCES

Java™ API for RESTful

Web Services

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 )

References

• Book

– RESTful Web Services

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

• email:alex@vanboxel.be

• http://twitter.com/alexvb

+