BeJUG JAX-RS Event
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
3,529
On Slideshare
3,443
From Embeds
86
Number of Embeds
4

Actions

Shares
Downloads
21
Comments
0
Likes
0

Embeds 86

http://www.bejug.org 71
http://www.slideshare.net 12
http://www.bejug.be 2
http://www.linkedin.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. BeJUG JAX-RS Representational State Transfer theory and JAX-RS
  • 2. 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 – 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 your questions about this topic.
  • 3. BeJUG JAX-RS Agenda • REST theory – Core principles – Anti-Patterns – Patterns • JAX-RS – Introduction – The Code • JAX-RS (1) : Life cycle en Path matching • JAX-RS (2) : Content and Update • JAX-RS (3) : Providers
  • 4. REST Representational State Transfer, Core principles and (Anti)patterns.
  • 5. BeJUG JAX-RS Agenda • REST theory – Core principles – Anti-Patterns – Patterns • JAX-RS – Introduction – The Code • JAX-RS (1) : Life cycle en Path matching • JAX-RS (2) : Content and Update • JAX-RS (3) : Providers
  • 6. Representational State Transfer REST
  • 7. Core REST principles 1. Addressability 2. Connectedness 3. Uniform Interface 4. Representations 5. Statelessness
  • 8. (1) Addressability • All resources should have an ID • In RESTful web services: URI representation • Everything should be a resource • The more, the better • Process step: ex. salery increase should be a resource • Actually violated by a lot of framework, where everything is tunneled though POST
  • 9. (1) Addressability (cont.) • Nice example: Amazon • Everything has an ID • You can send link • http://www.amazon.com/gp/product/B002JCSV8A/ • More framework SHOULD support addressability • First step to being RESTful
  • 10. Core REST principles 1. Addressability 2. Connectedness 3. Uniform Interface 4. Representations 5. Statelessness
  • 11. (2) Connectedness • Link everything together <member id=“/../members/me”> <membership ref=“/../memberships/0042”/> <link ref=“delete” method=“DELETE” ref=“..”/> </member> • Provide as much as possible • Relations • Actions • This will help the client discover the actions
  • 12. Core REST principles 1. Addressability 2. Connectedness 3. Uniform Interface 4. Representations 5. Statelessness
  • 13. (3) Uniform Interface • You limit yourself to a Uniform interface for ALL resources • HTTP methods • GET/PUT/POST/DELETE • HTTP:GET safe get representation – 80% reading (web optimized) – If your don’t make it safe, it your fault if google deletes your record, by following a link
  • 14. (3) Uniform Interface • HTTP:PUT – Create a new resource (app manager id) – Modify an existing resource • HTTP:POST – Create a new resource (server manager id) • Create subordinate resources • HTTP:DELETE – Delete a resource
  • 15. 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) • /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
  • 16. 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 ) • /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
  • 17. Core REST principles 1. Addressability 2. Connectedness 3. Uniform Interface 4. Representations 5. Statelessness
  • 18. (4) Representations • You interact with the resource through a representation • Representation : ANY usefull information about the state of a resource • 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)
  • 19. (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
  • 20. Core REST principles 1. Addressability 2. Connectedness 3. Uniform Interface 4. Representations 5. Statelessness
  • 21. (5) Statelessness • Your communication with the server is stateless • Server doesn’t keep state – HTTP Request happens in complete isolation – HTTP Request includes all information to full the request – The server never relies on information from a previous request
  • 22. (5) Statelessness (cont.) • Possible states of the server are resources – The client should not trick the server into a state to listen to a certain request • Application- versus Resource state? – Application state should only live on the client
  • 23. (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 • Statefull (not REST) • search?query=jaxrs • search?page=2 – State would make individual HTTP request simpler, but would make the protocal more complex
  • 24. (5) Statelessness (cont.) • Example: Shopping card – Classic implementation: Memory state – Make it a resource… persist it… – Accept as an URL
  • 25. (5) Statelessness (cont.) • Stateless brings a few benefits – Scalability • No 2 request depend on each other • 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
  • 26. 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
  • 27. Don’t do this, Don’t do that REST ANTI-PATTERNS
  • 28. REST ANTI-PATTERNS 1. Tunneling over GET 2. Tunneling over POST 3. Ignore cache 4. Ignore status code 5. Hypermedia & MIME 6. Break self descriptiveness
  • 29. 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 • Not bookmarkable
  • 30. 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 with a update API using the same URI scheme. Better: /events/2010jax-rs
  • 31. Anti-Pattern (2): Tunneling over POST • Tunneling though POST • Is actually what SOAP does • Not cacheable for reads • Again not bookmarkable • A lot of other framework violate this as well
  • 32. Anti-Pattern (2): Tunneling over POST • <soap:Env> • Endpoint -> dead end • WSDL -> generate client specifically written for that endpoint • In defense: SOAP-WS not be meant to be on the web, but generic
  • 33. Anti-Pattern (3) : Ignore caching • Ignoring caching • ETag support • If-Modified-Since • Don’t ignore on server, and don’t forget the client
  • 34. 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… • 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.
  • 35. Anti-Pattern (3) : Ignore caching • E-Tag : A HASH value • If-not-monified: 404 not modified
  • 36. 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) – 409: Conflict (concurrent update?) – 410: Gone (it was here but is now gone?) • Accepts: What methods are allowed
  • 37. Anti-Pattern (4): Ignore status codes • Did the operation succeed? • Everything created as intended? • Can we continue? • Did you accept the request?
  • 38. Small sample • 100 Continue • 404 Not Found • 101 Switch Protocols • 304 Method Not Allowed • 200 OK • 406 Not Acceptable • 201 Created • 407 Proxy Authentication Required • 202 Accepted • 408 Request Timeout • 203 Non-Authoritative • 409 Conflict • 204 No Content • 410 Gone • 205 Reset Content • 411 Length Required • 206 Partial Content • 412 Precondition Failed • 300 Multiple Choices • 413 Request Entity Too Lange • 301 Moved Permanently • 414 Request-URI Too Long • 302 Found • 415 Unsupported Media Type • 303 See Oher • 416 Requested Range Not Satisfiable • 304 Not Modified • 417 Expectation Failed • 305 Use Proxy • 500 Internal Server Error • 307 Temporary Redirect • 501 Not Implemented • 400 Bad Request • 502 Bad Gateway • 401 Unauthorized • 503 Service Unavailable • 402 Payment Required • 504 Gateway Timeout • 403 Forbidden • 505 HTTP Version Not Supported
  • 39. 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 • 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?)
  • 40. Break self descriptiveness • URI: good, but do you need a manual to to know how to constuct the URI? • You should discover the URI’s – <link ref=“update” …/>
  • 41. The good PATTERNS
  • 42. URI design • WARNING: Don’t worry too much about URI design • But it’s good practice • Linking is important, you should think about that, more than having a nice URI design • Make them self descriptive
  • 43. Named Link • Standard method of giving a meaning to a link – alternate representations • <link rel=“alternate” type=“application/atom+xml” href=“self”/> – actions • <link ref=“delete” method=“DELETE” href=“self”/> – navigation • <link ref=“next” type=“application/xml” method=“GET” href=“self?page=2”/>
  • 44. Collection Resource • Related resources grouped • /events/ • /memberships/0042/invoices/ • /members/ • Collections are resources (accessable by URI) • Collection representation should can contain usefull information • point to other resources • contain summary information n
  • 45. Read only views • Multiviews of the same collection /events/ < all /events/?tag=REST /events/?limit=10 /events/2009/10/ /memberships/0042/invoices/?outstanding=true
  • 46. 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 • Alternative: Client UUID: PUT it
  • 47. Paging Return subset Embed links to the next/prev chunks <link rel=“self” type=“” ref=“”/> <link rel=“next” type=“” ref=“”/> <link rel=“prev” type=“” ref=“”/> /events/?page=2
  • 48. Notification Polling • Polling: Not for real time update (for real time extensions look@PubSubHubbub) • Expose a view as RSS/Atom • BUT: ensure cache control headers • ETag • Last-Modified • Atom views: Loose coupling: better then traditional SOA
  • 49. Conflict • Protect against concurrent modification – Lost update problem • HTTP solutions – Provide Etag – Last-Modified Headers – Pre-conditions • HTTP response codes – 409 Conflict – 412 Pre-Condition Failed
  • 50. Extensions • Supports linking to different representations • It’s not one of my favorites, but… • Increases testability /members/r2d2 /members/r2d2.xhtml /members/r2d2.json /members/r2d2.vcard
  • 51. Canonical Representation • Similar like implementing .toString() in Java – It helps debugging • HTML presentation • HTML forms for input
  • 52. Deep ETags • Hash calculated on limited set of data (not complete response)
  • 53. Externalize Caching • Server: Concentrate on the correct headers • E-tag • Last Modified • Deep E-tags • Simplified
  • 54. Putting theory into practice
  • 55. BeJUG JAX-RS Agenda • REST theory – Core principles – Anti-Patterns – Patterns • JAX-RS – Introduction – The Code • JAX-RS (1) : Life cycle en Path matching • JAX-RS (2) : Content and Update • JAX-RS (3) : Providers
  • 56. Java™ API for RESTful Web Services JAX-RS INTRO
  • 57. JSR311 : JAX-RS • Annotation driven API • Help developers build RESTful Web Services – Guides novice developers – Intuitive for advanced developers • J2EE6 integration
  • 58. 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 application • It’s not the API that should be RESTfull • It’s the application that you build that need to be RESTfull
  • 59. JAX-RS implementations • CXF • Jersey • The reference implementation. Bundled with GlassFish • 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…)
  • 60. The Code JAX-RS (1): LIFE CYCLE AND PATH MATCHING
  • 61. JAX-RS (1): Life cycle and Path matching • The Resource Classes – Lifecycle • Default is per request (makes sense in REST) 1. Constructor is called (with params if available) 2. Dependencies are injected (don’t use the dependencies in the constructor! 3. Appropriate method is called 4. Resource is GC’ed
  • 62. JAX-RS (1): Life cycle and Path matching • Annotations – Path matching • @Path – Parameter matching • @PathParam, @QueryParam, @CookieParam, @HeaderParam, @MatrixParam • @DefaultValue – Injection • @Context • Request, UriInfo, Application, SecurityContext, <T> – Method (@GET, …)
  • 63. Life cycle and Path matching JAX-RS (1) CODE SESSION
  • 64. The Code JAX-RS (2) : CONTENT AND UPDATE
  • 65. JAX-RS (2) : Content and Update • HTTP verbs (methods) • @GET, @POST, @PUT, @DELETE • Content Negotiation • @Consumes and @Produces • Response Utilities • UriBuilder and Response • Standard Entity Providers • What JavaType <> Content Type
  • 66. JAX-RS (2) : Content and Update • Content Negotiation – Incoming: • @Consumes(mime-type) – Outgoing: • @Produces(mime-type) • Mime – type (text, application, …) – subtype ( plain, html, … , xml, json, …)
  • 67. JAX-RS (2) : Content and Update • Response – Helps to create a proper response • Errors • Headers • Redirect • UriBuilder – Helps to create URI’s
  • 68. JAX-RS (2) : Content and Update • Standard Entity Providers • Byte[] : mime ( */* ) • String : mime ( */* ) • InputStream : mime ( */* ) • Reader : mime ( */* ) • File : mime ( */* ) • DataSource : mime ( */* ) • Source : mime ( */*xml ) • JAXB : mime ( */*xml ) • MulticalueMap<String,String> : mime (application/x- www-form-urlencoded )
  • 69. Content and Update JAX-RS (2) CODE SESSION
  • 70. The Code JAX-RS (3) : PROVIDERS
  • 71. JAX-RS (3) Providers • 3 types of providers – Context Provider – Entity Provider • MessageBody(Writer/Reader) – Exception Mapping Provider • All annotated with @Provider
  • 72. Providers JAX-RS (3) CODE SESSION
  • 73. JAX-RS : The Code • URL mapping • @Path, @GET, @PathParam, @QueryParam,… • Consuming requests • @POST, @FormParam • JAXB integration • Producing/Consument • Content Negotiation • @Consumes and @Produces • Building URI and Response • UriBuilder and Response
  • 74. JAX-RS : The advanced • Advanced, but oh so useful • MessageBodyWriter/Reader – @Provider: VCard example – @Provider: XStream integration
  • 75. Java™ API for RESTful Web Services REFERENCES
  • 76. References • Video – Parleys: Stefan Tilkov (RESTful Design) – Parleys: JAX-RS: The Java API for RESTful Web s. • Audio – Episode 98: Stefan Tilkov on REST • Web – JAX-RS spec ( quite readable )
  • 77. References • Book – RESTful Web Services • Me again • http://alex.vanboxel.be • email:alex@vanboxel.be • http://twitter.com/alexvb +