Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Devoxx 2010 | LAB : ReST in Java

2,117 views

Published on

Introduction to rest-full development with Java. Focussing on jax-rs (and kauriproject.org)

Slides presented at devoxx-2010.
See http://devoxx.com/display/Devoxx2K10/RESTful+development+with+Java for abstract.

Published in: Technology
  • Be the first to comment

Devoxx 2010 | LAB : ReST in Java

  1. 1. 1IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org DEVOXX LAB :: REST Development
  2. 2. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Lab Preparation • You need – JDK (1.5+) – MAVEN (2.2.1) – Editor/IDE • Download and Install (unpack) – http://kauriproject.org/files/devoxx2010/ – or grab stick/CD-R passed around
  3. 3. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Speaker Context Marc Portier, ±14 years of Java, XML based web development. Co-founder of Outerthought. • Outerthought? – Innovative Content Management system that follows ReST principles: “DaisyCMS” – New ReST supporting development framework: “Kauri project” – Scalable Search and Store: “Lily Project” • Outerthought is an early ReST adopter
  4. 4. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Looking for You! • User, Contributor of our Open Source Projects • Teacher, University, School • Student • Talented worker – Job openings!
  5. 5. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Wonderful Web Machine
  6. 6. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Amazing Web Supercalifragilisticexpialidocious ! FRANTIC COMPLEX UNMANAGEABLE CHAOTIC Heterogenous Layered Decentralized Elegant Just Works Extensible Simple Usable Functional Entertaining Scalable
  7. 7. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org How does it keep up? • Diversity / Compatibility • Amount of Servers • Amount of Users • Amount of resources • Response Times / Latency
  8. 8. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Core Principles & Well kept secrets • Browsing Pages (Getting Views / Renditions) (aka Resource, URI, Representations) • Simple and Good Enough Protocols • Stale and Scale • Links
  9. 9. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Software developers should expect that sharing URIs across applications will be useful, even if that utility is not initially evident. Architecture of the World Wide Web, Volume One http://www.w3.org/TR/2004/REC-webarch-20041215/#p39
  10. 10. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Request – HTTP – Response POST /some/path?qp HTTP/1.1 Host: www.example.com:80 User-Agent: … Accept-Language: … Accept: … Accept-Charset: … Content-Type: … X-My-Header: … … bytes of data in entity body … 200 OK Content-type: … Content-Length: … Server: … Set-Cookie: … Date: … … bytes of data in http://example.com/more entity body … method path request headers empty line “nn” response headers response code entity bodyentity body empty line “nn”
  11. 11. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Stale And Scale • Caching fights – Latency and network traffic. • Critical success factor of the web. – And of your personal website! – Don't fight it for 'control' of your website. – Don't see it as a danger or problem. (hits/logs) – Design to help caches do what you think is best • The opportunity in “stale” Allowing “stale” responses Enhances “scalability”
  12. 12. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The killer Link
  13. 13. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Killer Link • Protocol-hypertext combination – HTML (not the first Hypertext system) – HTTP (not the first Internet protocol) • Web of URI's was first to combine both. And went on to cannibalize the rest. – Hardly any left: gopher? ftp? wais? – Forums vs. usenet? – Version control (svn) and CMS's shifting – Even email is moving up!
  14. 14. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org REST • Representational State Transfer – Historic back-thinking on the web-success. – Guidance in transition from HTTP/1.0 to HTTP/1.1 • No session layer • Instead: enhanced and clarified caching • Roy Fielding Dissertation • An architectural style for large scale distributed computing. • Theoretical Model, limited practice, debate-fuel
  15. 15. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The “RWS” Book • Proposes ROA • Practical and Pragmatic • Includes “annotated essential HTTP Reference” • Positions RPC style
  16. 16. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Web Service Debate? Not: SOAP vs. ReST But: RPC-style nature
  17. 17. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Classification of Web Services • Q1: Method Information – How does the client convey its intentions to the server? • HTTP method: GET, PUT, POST, DELETE • URI: e.g. GET /path?method=removeThat • Entity Body: Envelope with certain format (e.g. SOAP) • Q2: Scope Information – How does the client tell the server which (part of the) data to operate on • URI (path or request params) • Entity Body: Envelope with certain format (e.g. SOAP)
  18. 18. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Types of Web Services • I. ReSTFull/Resource Oriented • Method info in HTTP Method. • Scoping info in URI. • II. RPC Style • Entity Body holds Method and Scoping info. • Single URI: the 'end-point' | Single Method: POST • III. Hybrid • Method info in the URI, next to the scope info. • Difficult to spot, only visible when not read-only. • Often grown out of classic websites.
  19. 19. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Pitfalls of the RPC-style • Single endpoint: not cache-able. • Standard web-intermediaries make no sense. • Full method variation possible embedded in the envelope: No Uniform interface. Specific clients. • No Representations that make the client learn new paths in the application. (responses purely conform prior expectation)
  20. 20. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org In woodworking it's important to work with the grain of the wood. The Web, too, has a grain, and a RESTful web service is one that works with it. - Leonard Richardson and Sam Ruby RestFull Web Services
  21. 21. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org REST in practice • Understand how the web really works • How to put that into your advantage – Reduce complexity – Enhance transparency – Leverage Linking/Connectdnesss • Matches the fuzz – Web 2.0, RIA, mash-ups – Available libs and tools • firebug and poster • restlet.org
  22. 22. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Meeting high expectations • Current web-experiences are spoiling us – Google Maps – Mash-ups – Atom – Amazon S3 • It all looks so simple (and mostly works) • General customer feeling: “How hard could it be?””
  23. 23. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org What To Expect from “REST”- APIs/LIBs/Frameworks? • No magic • And a lot to learn & discover Actually, I'd be a lot happier if, as a class, these were called "HTTP Frameworks" because otherwise, there's an implication that REST is achieved by using the framework. Without implying anything about any framework, RESTlet does indeed directly map REST terminology into configuration. But in reality, a RESTful outcome is the least likely for beginners, regardless of framework. You just can't abstract away having to learn REST; once you have learned, you'll find most frameworks working against you unless their assumptions are congruous with your Own. – Eric J. Bowman on rest-discuss (http://tech.groups.yahoo.com/group/rest-discuss/message/16824)
  24. 24. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org What To Expect from “REST”- APIs/LIBs/Frameworks? • New API view on HTTP – Access to HTTP message details – Semantics mapping the REST tereminology • Implementing more HTTP semantics – e.g. Content negotiation • Some Guidance & Luring into new techniques – Modified instance and thread management – Supporting the #steps in typical REST design • Using More modern Java techniques (e.g. annotations)
  25. 25. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Terminology
  26. 26. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org ROA • Resource Oriented Architecture • Coined in the RWS Book • More practical advise and groundwork • For: – A ReST-style architecture – For building services – Tied to the Web • And it's main HTTP protocol
  27. 27. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Resource Oriented Architecture * (1) Resources (2) URI's (3) Representations (4) Links Between them The four Concepts (1) Addressability (2) Statelessness (3) Connectedness (4) Uniform Interface The four Properties * as proposed by the RWS Book
  28. 28. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [C1] A Resource • Something. • Anything. • Idea, Concept • Data record, Result, Answer, File, • Physical item, Real world object. • As soon as it is important enough to • Reference it by itself. • Talk about it. • Get representations from it. • Perform operations on it.
  29. 29. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Resource Samples • The pictures of my last trip to Mexico. • The pictures of my daughter during our last trip... • The coffee machine. • The current weather at my weather station. • The max-temperature curve over the last 14 days • The Sales Results for this 3rd quarter • The first blog entry for September 23rd 2008 • The next five prime numbers after 1024 • Some Information about ReST • A directory of resources about ReST • A map of Zwijnaarde, Ghent • The 50 most recent monetary transactions between two account numbers
  30. 30. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [C2] URI / Reference • Universal Resource Identifier • It is the name • And the address of a resource • The existential property of the resource – If it doesn't have a URI, it isn't a resource – All resources have (at least) one • http://www.w3.org/DesignIssues/Axioms (TBL)
  31. 31. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI Samples http://pics.org/mpo/sets/2007Mexico/ http://pics.org/mpo/sets/2007Mexico/?tag=Fien http://intranet/machines/floor­4/coffee http://home/weather/current/all http://home/weather/hist/tempmax?start=20080909 http://intranet/sales/2008/Q3 http://myblog.com/mpo/2008/09/23/0 http://math.org/next­5­primes/1024 http://library.org/wiki/ReST http://library.org/search/ReST http://maps.org/roads/Belgium/OVL/Zwijnaarde http://bank.com/transact/737­0000036­79;445­ 1664881­04?limit=50
  32. 32. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Good URI's Are... • Descriptive – Reading the URI gives a good idea what to expect. • No surprise / Natural • Following some pattern / structure (Hackable) – Similar resources have similar URI's, eg • http://library.org/search/{search­term} • http://library.org/articles­about/{topic}  • Long lasting associated to the resource.
  33. 33. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI to Resource Relation • Can two resources be the same? Can two resources share the same URI? – No. Resources are the thing, the whole thing and nothing but the thing. – URI's are UNIVERSAL (one for the resource in the whole universe) – Still at any given time two distinct resources might point to the same data: • http://project.org/releases/1.0.7.tar.gz • http://project.org/releases/latest.tar.gz – Note: two distinct concepts!
  34. 34. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI to Resource Relation II • Can a URI be associated to another resource? – No. The meaning should stick. – Note though: Resources do have a live-cycle. They exist/don't-exist at any given time. • Can one resource have more then one URI? – Yes. Alternatives make resource more accessible. But also dilutes the value of each one. • Relates to: Are my car-keys in my normal spot(s) – Ensure some canonical variant...
  35. 35. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Canonical URI's in Practice • Advised when 2 or more URI's for one resource • Solution 1: • All URI's return 200 OK, and representation in body • Together with special header: Content­Location: canonical URI • Solution 2: • Only one URI serves the content (with 200 OK) • All others return 303 See Also • Together with the header: Location: canonical URI
  36. 36. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [P1] Addressability • Question: How many URIs should you foresee? • Answer: more! – Increase the surface area of your application. – Compare to description (email) • Goto homepage, then query for..., take 3rd option... • Start FTP client, cd to folder, get – Random Access Coordinates To All Resources • URI's to resources are no accidents, but part of the design. (Else it's no resource) • Other samples of addressable architectures: – Cells in a spreadsheet, Files on disk, – Nodes in an XML document ...
  37. 37. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Addressability Matters • URIs can be published anywhere – e.g. also Email and Old media (HUMO!) • Addresses can be talked about – Bookmark- and tagging services. – Link love! • True Resources (with designed URIs) benefits: – Caching – Chaining & Aggregation – Translation & Validation Services – Scraping and Mash-up
  38. 38. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Addressability Woes • Do I want Scraping and Mash-ups? – My Data? My Service? My Brand? My Business? – Do you really want to control all possible usage? • Learn to see the benefits: Exposure (brand) – Without service liability. – Without bandwidth usage. – Without the building effort. • Syndication with Encryption and Security is still an option. (If the data really is the value.)
  39. 39. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [P2] Statelessness • Every HTTP request for a resource should happen in complete isolation. – Server never relies on information from previous messages. • Logic Premises: – Resources are pieces of info on a server – Addressability says they all should have URI's • Then Statelessness means all server states have a distinct URI. – e.g. page 2 from Google results about 'ReST'
  40. 40. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Good, Bad & Ugly Kinds of State • The bad kind: “Conversational State” – Builds up a conversation/session. – Introduces dependency across requests. • The good kind: “Application State” – Cleanly kept up in the client, the process, the end- user interaction – Grown by user interaction and received links. • The ugly kind: “Resource State” – Server side. Conform the resource life-cycle. – Why ugly (anyone?)
  41. 41. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Statelessness Matters • Superlative of Addressability – The 'boemboemboem' without the 'blablabla' (At least the 2nd time) – Bookmark-able hooks into earlier conversations • All benefits of addressability, Now for intermediate states: – Caching, mash-up, aggregation, translation, direct referencing, ... • Most importantly: positive effect on scalability – Easier distribution across load-balanced servers.
  42. 42. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org A matter of Control
  43. 43. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Who controls the state? • Client is in charge! – Statelessness puts control at the client – The client decides on the path through the application. • The server serves – Humble responses to requests – Offers options (links) – Lists available next states
  44. 44. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [C3] Representations • Platonic view on things • Resource = the concept, idea, or principle • Representation = what you really get – The data, The bytes – a COPY – Physical resources often have disappointing representations (often status info or metadata) • Note: representations can travel upstream. – Write operations via PUT
  45. 45. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Representation Variants • Representations have specific format and language (the resource often has not) • Clients can 'negotiate' preferred variant: • Request headers: Accept: (mime­types) Accept­language: (iso codes) • Server can describe in which ways representations can vary: • Response header: Vary: Accept, Accept­language • Important for caches! Vary: *    //can not be cached
  46. 46. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Practical Content Negotiation • 1 URI per resource is Good™ • 1 URI per representation is practical • More visible and clear • Still a canonical negotiating URI is possible • Increased “Addressability” – Passing URI to translation and validation services • Options • Through request parameter (@google: ?hl=nl ) • In the /path/resource-name.nl.html
  47. 47. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [C4] Links • Ehrm? Not URI's? • Link = fact that the URI gets encoded in the representation • Wow. WOW! (Let it sip through!) • Note: soft-referencing by nature. Imagine being 12 and getting an SMS with the number of a new buddy to be SMS-ing with...
  48. 48. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org HATEOAS • Hypertext as engine of application state (Remember: the Killer Link... and Mary Poppins) • The 'quantum phenomena' of browser state: With each page-rendition arriving in the browser, new accessible application-states pop into existence! • Semantics of link are important – Implicit from context / AI or end-user – Explicit through: <link@rel>, and the suggested Link-Header (http://tools.ietf.org/html/draft-nottingham-http-link- header-10)
  49. 49. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Application State Landscape
  50. 50. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The App-State Landscape
  51. 51. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org HATEOAS Matters • Generic (unaware) client – At run-time surprisingly 'smart' (at least helpful) • Towards the semantic web – Links/relations annotated with semantics • Allows for independent Progress – New URI spaces introduced • != contradiction to “cool URI's” • Old links still serviced / redirected – Server has to handle all, – Client stays in control
  52. 52. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Links – Spaces - Maps • Public address-space is using the URI scheme • Inside the domain there are however various kinds of 'local' scoped links – e.g. foreign-key relations – Unaware of their 'universal' notation • i.e. potential notationS in various contexts • Applications will need to map cross-references between entities both ways – Directing incoming request to entity – Translating local reference to (context) URI
  53. 53. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [P3] Connectedness • URI = name-addressing scheme – Then designing to use them is to ensure Addressability • Links = having representations hold URIs – Then designing to use them wisely is to ensure Connectedness. • The end-goal is to achieve some self-learning behaviour upon the clients – Publish only one entry URI
  54. 54. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [P4] The uniform interface • Limited set of resource interactions – GET, PUT, DELETE (allow for crud-like operations) – POST • The escape for the pragmatics • The Danger zone (breaking ROA properties) – HEAD: same as GET without the payload – OPTIONS: self-description of the resource • Underused. • Answer in response header: Allow: GET HEAD PUT DELETE
  55. 55. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org And some special ones: • The special ones – TRACE (diagnostics: loopback and route) – CONNECT (proxies acting as SSL tunnel) • WebDAV (http://www.webdav.org/specs/rfc2518.html) – PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK, • New suggestion (from gdata: http://code.google.com/apis/gdata/docs/2.0/refer ence.html#PartialUpdate) – PATCH (http://tools.ietf.org/html/rfc5789)
  56. 56. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Properties of the uniform Interface • The various methods are expected to work in a certain way (Reason: resilience to unreliable networks) – GET (and HEAD) should be SAFE • No changes to server-state. • No side-effects intended by the client. • Mild side-effects accepted (log, counters, ...) – PUT and DELETE should be IDEMPOTENT • Replay/Duplicate of the message does not change the server-state again. – POST, no restrictions. The Sky is the limit • Design and document for safety and idempotence! • e.g. uuid for operation, optimistic locking, ...
  57. 57. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org More Uniform Interfacing! • NOT only about the request-method – Response Code! (no error-tunnelling please!) – Request Headers (e.g. content negotiation) – Response Headers • Mainly Location, Content-Location • Don't overdo it though: stay away of subtle nuances and unused/unknown concepts • Essence: Principle of least surprise. – So avoid custom X-Headers and cookies
  58. 58. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Recap: The ROA (1) Resources (2) URI's (3) Representations (4) Links Between them The four Concepts (1) Addressability (2) Statelessness (3) Connectedness (4) Uniform Interface The four Properties
  59. 59. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Concepts
  60. 60. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Practical Design and Hacker Tips
  61. 61. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Resource Oriented Design • Steps to take 1. Define the data-set. 2. Split the data-set into resources. For each resource: 3. Name the resource (URI) 4. Decide on the supported request methods. 5. Design exchanged representations from/to clients. 1. Integrate (link) the resource with existing ones. 2. Consider typical/normal flow and interaction. 6. Handle error-conditions and decide upon error-codes.
  62. 62. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Sample
  63. 63. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI Design Techniques • Hierarchy and relative links • Don't overdo hierarchy (compare to OO composition) – Changes faster then you expect! – Should be based upon intrinsic/identifying properties of the resource – Devaluates the 'subordinate' resources • Useful where it maps the link-spaces • Useful where it maps boundaries of functional blocks that could be out-sourced! (linked/mashed up) • In house conventions avoid endless discussions • e.g. common request parameters (language, chunks...) • Plural forms, ... • Typical landing pages (search/ login/ index/ ...)
  64. 64. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI Design Techniques • Service interface versioning! • Easy as first part of path //v1/whatever • Paths vs. request parameters • Prefer the path to 'name' resources • Request Parameters – Have a more 'optional' ring – Are easily consistently used across URI's and Services – For arguments to algorithms • Typical Notations • / # ? & = % have their known use • Proposed Value-list separators – (colon) , for ordered. (e.g. {latitude},{longitude} ) – (semi-colon) ; for unordered (e.g. {-listjoin|;|friends} )
  65. 65. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org URI-Templates • Draft specification – http://tools.ietf.org/html/draft-gregorio-uritemplate-04 – http://code.google.com/p/uri-templates/wiki/Implementations • Templates for generating URIs based on parameters in some 'context' (client-side) – Simple variants used in server-platforms for 'parsing' requests as well • Some samples http://www.google.com/search?{­join|&|q,num} http://bitworking.org/news/{­listjoin|/|entrypath} http://example.com/search? q={searchTerms}&num={count}
  66. 66. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Matrix URIs • Status “Personal View” (TBL, since 1996) – http://www.w3.org/DesignIssues/MatrixURIs.html • Brings relative linking without hierarchy • Unordered attribute sets in URI paths • Sample base= //some/mapX;scale=5;roads=y Relative links: href=”;” //some/mapX;scale=5;roads=y href=”;scale=2”   //some/mapX;scale=2;roads=y href=”;roads” //some/mapX;scale=5 href=”;roads=”  //some/mapX;scale=5;roads= href=”;rivers=all” //some/mapX;scale=5;roads=y;rivers=all
  67. 67. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Decide on Supported Request Methods • GET (HEAD), PUT, DELETE – Obviously map the crud operations – Don't forget safety and idempotence though • The hard job is dealing with flexible POST – When/How to use it?
  68. 68. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Appropriate Use of POST • Creating subordinate resources • When Resource location is under client control: – Request: PUT + representation – Response: 200 OK • When Server decides on URI: – Request: POST + representation – Response: 201 Created + Location header • Appending resource state • Avoiding full write of complete resource,e.g. add to log • Just Pragmatics • Handle/Tunnel for Browser Client (PUT/DELETE) • PUT can't handle relative state change • Other, e.g. Batch of PUTs
  69. 69. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Border case Use of POST • To be avoided: Anything that will introduce the RPC style. – Don't tunnel everything to one endpoint URI – Don't let it overtake the resource oriented design • But pragmatics rule. – Sometimes unavoidable – Sometimes just helpful • Operations spanning multiple resources • Incremental/Relative Updates
  70. 70. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Design exchanged representations • LINKS! LINKS! LINKS! • The adagium of Jon Postel – Be liberal in what you expect and conservative in what you send. • Practical trade-offs – Content negotiation is possible, sometimes recommended, not required. – One variant will often do. (Off-line negotiation.) – Server still decides and sets Content-type header. – Representation formats are part of your service versioning!
  71. 71. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Candidate formats • Data structures – XML – json (js object notation) – Your own • End-user Facing – HTML – PDF • Microformats – Nice trade-off between end-user / program Consumption
  72. 72. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Decide on Response Codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) • 200 “OK” - 201 “CREATED” - 202 “ACCEPTED” • 400 “Bad Request” • Issue at client side, try harder. Check message to fix. • 500 “Internal Server error” • Issue at server side, try later. Message informational. • 301 “Moved Permanently” • 404 “Not Found” - 410 “Gone” • URI can't be mapped to the resource. • 409 “Conflict” • Request would make server-state inconsistent • e.g. foreign key relation, locking, ...
  73. 73. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Lab
  74. 74. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org The Lab • [0] Java REST-Lib Listing – What is out there • [1] Service Implementation – Practical techniques – JAXRS • [2] Client Development (if time permits) – Transition from web-service to web-application (UI) – Demo Kauri
  75. 75. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [0] Java and REST • Servlets? (mindset: Request-Response model) • Specs and API's – Jax-RS (jsr 311) • Implementations @ – RESTlet restlet.org • Adds own API with annotations – Apache CFX cfx.apache.org – Oracle/Sun Glassfish (Jersey) jersey.java.net • Frameworks – ###
  76. 76. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Jax-RS • JSR 311 https://jsr311.dev.java.net/ • Clear and readable spec (±50 pages) • Helps out with common REST tasks – URI Design and Handling • URI templates notation (@parse and @format) • Parameters in URIs – Response Codes and Headers – Representations up- and down-stream • Remember: no REST guarantee/enforcement • Modern & Elegant HTTP API (unlike servlets)
  77. 77. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [1] ReST Service Implementation • Exercise – Use Jax-RS (API & annotations) – Build Resty webservice for a simple blog – Limit ourselves to json Representations – No persistence / mock service • No exceptional smart or compelling design • Only Basic ReST principles in use. • Focus: 1st experience with Jax-RS use. • Explain Jax-RS constructs as we go.
  78. 78. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org ResourceList & URI design ● Resource “Blog-Entry” /data/entry – GET: list of entries – POST: factory for new entry (in body) – 201! /data/entry/{id} – GET, PUT, DELETE • Representation (json) {"title":"...","summary":"...","content":"...", "id":"2010-06-30T12:13:00", "tags": ["test"]}
  79. 79. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org ResourceList & URI design II ● Resource “Tags” /data/tag – GET: list of tags (cloud) – No explicit creation: implicit through entries! /data/tag/{name} – GET: list of entries with that tag • Representation (json) {"entries":[{...}, {...}],"id":"go"}
  80. 80. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org JaxRS::Application • Entry-point, deployment-unit, configuration. • Subclass javax.ws.rs.core.Application – Configure there which classes should be loaded. new javax.ws.rs.core.Application() { @Override public Set<Class<?>> getClasses() { Set<Class<?>> rrcs = new HashSet<Class<?>>(); rrcs.add(MyPojoResourceClass.class); return rrcs; } }
  81. 81. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Deploy Your Application Check docs of your deployment-platform – e.g. restlet uses a wrapper: JaxRsApplication jaxRsApp = new JaxRsApplication(context); jaxRsApp.add(new javax.ws.rs.core.Application(){ ... }); defaultHost.attach("/data", jaxRsApp); – e.g. kauri uses groovy router & springframework DI: builder.router { jaxRs(uri: "/data", passThrough: true) { jaxRsResource(scanPackages: "*") jaxRsProvider(scanPackages: "*") jaxRsGroovyScripts(path: "groovy-jax-rs") } }
  82. 82. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Kauri Setup $ cd /to/where/kauri-unpacked $ export KAURI_HOME=$(pwd) $ ls ${KAURI_HOME}/bin/*sh • kauri-deploy-repo.sh : update mvn repo • kauri-project-template.sh : new project • kauri.sh : runtime $ ${KAURI_HOME}/bin/kauri-deploy-repo.sh $ cd ~/projects; $ ${KAURI_HOME}/bin/kauri-project-template.sh • Type 1 • ID: com.example.devoxx10:rslab:1.0-SNAPSHOT
  83. 83. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Jax-RS Hello-world (in Kauri) $ cd rslab $ mvn install $ ${KAURI_HOME}/bin/kauri.sh run • http://localhost:8888/helloworld-from-java – src/main/kauri/*.groovy – src/main/java/com/example/devoxx10/jaxrs/ HelloWorldResource.java
  84. 84. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Jax-RS:Resources • Any POJO + Jax-RS Annotations, mainl – @Path to trigger this resource – Request Method Designator (e.g. @GET) • Lifecycle – Per request instance will be created – Requires Public constructor – As much as possible arguments will be passed – DI framework can be used.
  85. 85. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Parameters from Request context • Applied to: – Constructor arguments – Fields & Properties – Method Arguments • Various types: – @PathParam – @QueryParam – @MatrixParam, @CookieParam, @HeaderParam, – @Context (matches API types: Request, Application, UriInfo, HttpHeaders,, SecurityContext, Providers, <YOUROWN>)
  86. 86. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org JaxRS:Resource Methods • public • Injects annotated arguments • Returns – Void, null >> “204” No Content – Response (from ResponseBuilder) – GenericEntity – <YOUROWN>
  87. 87. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org @Path(“uritemplate-{name:regex}”) • URI-template for parsing (not generating) – Resembles a path enhanced with named placeholders between { } – Translated into a regexp to match the request-path • On: – Resource Class (Root-class) – Methods: declares so-called subresources that the method will (@Path is added to the class's) • Locate (if Request-Method-Designator is absent) • Handle (if it is specified) Exercise: Update sample to also handle hello-from-java/{name}
  88. 88. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Result package com.example.devoxx10.jaxrs; @Path("helloworld-from-java") public class HelloWorldResource { @GET @Produces("text/html") public KauriRepresentation foo() { return foo("Hello World!"); } @Path("{name}") @GET @Produces("text/html") public KauriRepresentation foo(@PathParam("name") String name) { Map<String, Object> data = new HashMap<String, Object>(); data.put("message", name); return new KauriRepresentation("helloworld", data); } }
  89. 89. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Content-Negotiation • @Produces(mime/type) //GET @Consumes(mime/type) //POST, PUT • Extra test in selecting the resource-method to call • Also on @Provider that transform byte-streams into actual Java object entities – MessageBodyWriter<T> – MessageBodyReader<T>
  90. 90. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org @Providers • Recurring extension mechanism for custom extensions. • MessageBodyWriter, MessageBodyReader – Automagic entity-to-representation conversion • ContextResolver – Request-context parameter mapping (@Context)
  91. 91. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org ResponseBuilder • See API • Builder Pattern for controlling details of the HTTP-Response • Sample: @POST @Produces("text/plain") public Response hello( @PathParam("world") String world ) { final URI link = UriBuilder.fromResource( this.getClass()).build(world); final Response resp = Response.created(link) .entity(“create at ” + link) .build(); return resp; }
  92. 92. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org [2] Rest Service Consumption • Transition from Web Service to Web App • Wiring • Client To Perforn Web-Service Calls • Client UI Elements: – (server-side) templates and – (client-side) forms • Demo KauriProject.org – Read data & pack into templates
  93. 93. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Transition from Web-Service to Web-Appliction
  94. 94. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Web Resources in a Web App
  95. 95. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Kinds Of Web Resources • End-User Data – or 'library resources' • Content (CMS like) • Binary Downloads and 'attachments' • Full Text Search-result-lists, linking to the above • Almost directly consumed by End-Users • “Faceless” - or 'service resources' • Manageable Data (json or XML) Items (CRUD) • Query results – Algorithm results (GET only) • Predefined one-off views/indexes (GET only) • Consumed by Custom Applications
  96. 96. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Kinds Of Web Resources II • Browser-Technology-Feeds – or 'site resources' – Pages/Page Impressions • Aggregations of data (microformat), functions and/or links (navigation, menu, help, ...) – Styling/Skinning (CSS / Images) – Functional Applications • Forms • JavaScript logic (or other RIA approach) – Mashing up the data – Consumed by web-browsers, supporting the end-user experience.
  97. 97. IIC » TECHNOLOGIEPARK 3 » B-9052 ZWIJNAARDE (GENT) » www.outerthought.org Time to take a ReST Questions?

×