REST and JAX-RS

8,774 views

Published on

Review of REST and JAX-RS, as presented by Guy Nir at AlphaCSP's JavaEdge conference, 2009.

Published in: Technology, Travel
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
8,774
On SlideShare
0
From Embeds
0
Number of Embeds
59
Actions
Shares
0
Downloads
268
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

REST and JAX-RS

  1. 1. JAX-RS … and the REST will follow Guy Nir
  2. 2. Agenda » REST – What ? Who ? Why ? » JAX-RS (JSR-311) - Digg’n in » Security » Application-Level Protocol » Summary 2
  3. 3. What ? Who ? Why ? … and how
  4. 4. What ? Who ? Why ? Architectural overview GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ HTTP request Yahoo’s weather HTTP client web-server HTTP response RESPONSE CODE: 200 (OK) + BODY 4
  5. 5. What ? Who ? Why ? Architectural overview GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ Read, The weather in Israel at Tel-Aviv area (Ramat Gan). 5
  6. 6. What ? Who ? Why ? HTTP request overview GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1 Host: weather.yahoo.com Accept: image/gif, application/xaml+xml, */* Accept-Language: en-us User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... ) Accept-Encoding: gzip, deflate Connection: Keep-Alive Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241; GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ HTTP request Yahoo’s weather HTTP client web-server 6
  7. 7. What ? Who ? Why ? HTTP request overview GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1 Host: weather.yahoo.com Accept: image/gif, application/xaml+xml, */* Accept-Language: en-us User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... ) Accept-Encoding: gzip, deflate Connection: Keep-Alive Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241; GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ HTTP request Yahoo’s weather HTTP client web-server 7
  8. 8. What ? Who ? Why ? HTTP request overview GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1 Host: weather.yahoo.com Accept: image/gif, text/plain, application/xml, */* Accept-Language: en-us User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... ) Accept-Encoding: gzip, deflate Connection: Keep-Alive Cookie: BA=ba=2139&ip=82.80.99.106&t=1258874241; GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ HTTP request Yahoo’s weather HTTP client web-server 8
  9. 9. What ? Who ? Why ? HTTP request overview GET /israel/tel-aviv/ramat-gan-1967869/ HTTP/1.1 Host: weather.yahoo.com Accept: image/gif, application/xaml+xml, */* Accept-Language: en-us User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; ... ) Accept-Encoding: gzip, deflate Connection: Keep-Alive Cookie: BA=2139&ip=82.80.99.106&t=1258874241; GET http://weather.yahoo.com/israel/tel-aviv/ramat-gan-1967869/ HTTP request Yahoo’s weather HTTP client web-server 9
  10. 10. What ? Who ? Why ? HTTP request overview HTTP request Yahoo’s weather HTTP client web-server RESPONSE CODE: 200 (OK) + BODY HTTP/1.1 200 OK Connection: close Content-Type: text/html;charset=utf-8 Cache-Control: private Content-Length: 69947 Date: Sun, 22 Nov 2009 07:59:11 GMT Set-Cooie: t=164531234; 10
  11. 11. What ? Who ? Why ? HTTP request overview HTTP request Yahoo’s weather HTTP client web-server RESPONSE CODE: 200 (OK) + BODY HTTP/1.1 200 OK Connection: close Content-Type: text/html;charset=utf-8 Cache-Control: private Content-Length: 69947 Date: Sun, 22 Nov 2009 07:59:11 GMT Set-Cooie: t=164531234; 11
  12. 12. What ? Who ? Why ? HTTP request overview HTTP request Yahoo’s weather HTTP client web-server RESPONSE CODE: 200 (OK) + BODY HTTP/1.1 200 OK Connection: close Content-Type: text/html;charset=utf-8 Cache-Control: private Content-Length: 69947 Date: Sun, 22 Nov 2009 07:59:11 GMT Set-Cooie: t=164531234; 12
  13. 13. What ? Who ? Why ? HTTP request overview HTTP request Yahoo’s weather HTTP client web-server RESPONSE CODE: 200 (OK) + BODY HTTP/1.1 200 OK Connection: close Content-Type: text/html;charset=utf-8 Cache-Control: private Content-Length: 69947 Date: Sun, 22 Nov 2009 07:59:11 GMT Set-Cooie: t=164531234; 13
  14. 14. What ? Who ? Why ? Everything is a resource … » A resource is …  A network-accessible data object or service identified by [1] an URI (IRI ): • Images, • Documents (HTML, PDF, …), • Geo-location, • Weather [1] Section 3, Atom Publishing Protocol 14
  15. 15. What ? Who ? Why ? Resources: » Collections  http://portal/bicycles/ » Members/Items:  http://portal/documents/mydog.doc [1] Section 3, Atom Publishing Protocol 15
  16. 16. What ? Who ? Why ? HTTP defines more than just ‘GET’ and ‘POST’: Method REST Operation Description POST CREATE (INSERT) Create or update GET READ (QUERY) Query about the resource PUT UPDATE (CHANGE) Update DELETE DELETE (DELETE) I want to delete what-ever-it-is …. HEAD I’m something like ‘GET’ [1] OPTIONS JAX-RS mumbles something about me. TRACE CONNECT [1] Unique extension of JAX-RS. 16
  17. 17. What ? Who ? Why ? Roy Fielding defines REST as: » Free of any platform or language, » Free of any schema or protocol (beyond that of HTTP), » No ALP (Application- or Presentation- layer Protocol) coercion [1] » Only a set of recommendations ! [1] Principled Design of the Modern Web Architecture - Roy T. Fielding, Richard N. Taylor - section 4. 17
  18. 18. What ? Who ? Why ? Some important points … » REST recommends using URIs instead of query-based URLs:  Don’t use: http://host.com/service?type=weather&when=today  Use: http://host.com/service/weather/today » Atom Publishing Protocol (APP).  RFC-5023 (text-only) 18
  19. 19. What ? Who ? Why ? REST is … » Architectural style, not technology !  Client/server + Request/response approach. » Everything is a RESOURCE. » CRUD (Create / Read / Update / Delete) … [1] » Stateless by nature (excellent for distributed systems), » Cacheable (naturally supported !) » A great way to web-service ! [1] Reference to other acronyms at Wikipedia 19
  20. 20. JAX-RS JSR-311
  21. 21. JAX-RS (JSR-311) JAX-RS goals[1]: » POJO-based, » HTTP-centric, » Format independent, » Container independent, » Availability as standalone and enterprise platforms. [1] JSR-311, section 1.2 - Goals 21
  22. 22. JAX-RS (JSR-311) HTTP JAX-RS 22
  23. 23. JAX-RS (JSR-311) This page is intentionally left blank Gesture for times when we used to read books …. 23
  24. 24. JAX-RS (JSR-311) http://www.disney.com/muppets/... 24
  25. 25. JAX-RS (JSR-311) POJO + Annotation = JAX-RS resource /** * http://www.disney.com/muppets/catalog Relative context */ @Path("/catalog") public class MuppetCatalogController { } 25
  26. 26. JAX-RS (JSR-311) Reading the catalog GET …/catalog CLIENT SERVER List all items available for sale. /** * http://www.disney.com/muppets/catalog */ @Path("/catalog") public class MuppetCatalogController { @GET public String findAllCatalogItems() { String list = ... // Compile a list of all items. return list; } } 26
  27. 27. JAX-RS (JSR-311) Reading the catalog GET …/catalog?muppetId=650 CLIENT SERVER Properties of Kermit public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ... { int muppetId; String stringId = req.getParameter("muppetId"); if (stringId != null) { // Hoping for no exception to occur! muppetId = Integer.parseInt(stringId); } else { muppetId = ... // Use some default value … } Muppet muppet = findMuppet(muppetId); generateTextualOutput(muppet, resp.getWriter()); } 27
  28. 28. JAX-RS (JSR-311) URI template GET …/catalog?muppetId=650 CLIENT SERVER Properties of Kermit @GET @Path(“/catalog/{muppetId}”) public String findItem(@QueryParam(“muppetId”)int muppedId) { Muppet muppet = findMuppet(muppetId); return ... } 28
  29. 29. JAX-RS (JSR-311) URI template GET …/catalog?muppetId=650 CLIENT SERVER Properties of Kermit @GET @Path(“/catalog/{muppetId}”) public String findItem(@DefaultValue(“0”) @QueryParam(“muppetId”)int muppedId) { Muppet muppet = findMuppet(muppetId); return ... } 29
  30. 30. JAX-RS (JSR-311) URI template GET …/catalog/650 CLIENT SERVER Properties of Kermit @GET @Path(“/catalog/{muppetId}”) public String findItem(@PathParam(“muppetId”)int muppedId) { // ... Do something } 30
  31. 31. JAX-RS (JSR-311) URI template GET …/catalog/650 CLIENT SERVER Properties of Kermit @GET Regular expression @Path(“/catalog/{muppetId:[0-9]+}”) public String findItem(@PathParam(“muppetId”)int muppedId) { // ... Do something } 31
  32. 32. JAX-RS (JSR-311) URI template GET …/catalog/650 CLIENT SERVER Properties of Kermit @GET @Path(“/catalog/{muppetId:[0-9]+}”) public String findItem(@PathParam(“muppetId”)int muppedId) { // ... Do something } // ACCEPT: http://.../catalog/-477 @GET @Path(“/catalog/{muppetId:-[0-9]+}”) public String findItem2(@PathParam(“muppetId”)int muppedId) { // ... Do something } 32
  33. 33. JAX-RS (JSR-311) Cookies, headers and friends … Internet http://www.disney.com Public SERVER client Intranet GET /muppet/catalog HTTP/1.1 host: crm.intranet http://crm.intranet accept: text/plain User-Agent: Mozilla/4.0 (...) Internal CRM Cookie: user-type=ADMIN client Cookie 33
  34. 34. JAX-RS (JSR-311) Cookies, headers and friends … @PUT @Path("/catalog/{muppetId}/{propertyName}") public void updateItem( @HeaderParam("host") String hostname, @CookieParam("user-type") UserType type, ...) { if (!hostname.equals("crm.intranet")) { throw ... } if (!UserType.CUSTOMER_CARE.equals(type)) { throw ... } // ... handle the request. } enum UserType { ADMIN, CUSTOMER_CARE, TECHNICAL; } 34
  35. 35. JAX-RS (JSR-311) @Context » UriInfo » Request » HttpHeaders » SecurityContext public void handleRequest( @Context UriInfo uri, @Context SecurityContext security, @QueryParam ("username") String username) { ... } 35
  36. 36. JAX-RS (JSR-311) Content negotiation (or: cache is always money!) 36
  37. 37. JAX-RS (JSR-311) CLIENT SERVER GET http://..../muppets/muppetOfTheMonth/image + Content negotiation precondition RESPONSE: • 200 (OK) + body • 304 (Not Modified) 37
  38. 38. JAX-RS (JSR-311) Content negotiation @GET @Path("/muppetOfTheMonth/image") public Response findMuppetOfTheMonth( @Context UriInfo uri, @Context Request request) { File file = locateFile(uri.getRequestUri()); EntityTag tag = calculateTag(file); Date modified = new Date(file.lastModified()); ResponseBuilder r = request.evaluatePreconditions(modified, tag); // ... } 38
  39. 39. JAX-RS (JSR-311) The @HEAD method HEAD …/catalog/650/image CLIENT SERVER HTTP/1.1 200 OK Content-type: text/plain Content-length: 1024256 39
  40. 40. JAX-RS (JSR-311) The @HEAD method @GET @Path("/catalog/{muppetId}/image") public Response fetchThumbnailHeadAndBody() { return ...; } @HEAD @Path("/catalog/{muppetId}/image") public Response fetchThumbnailHeadOnly(...) { int size = getThumbnailSize(muppetId); ResponseBuilder builder = Response.noContent(); builder.header("Content-length", size); builder.header(“Is-ReadOnly", true); return builder.build(); { 40
  41. 41. JAX-RS (JSR-311) Bridging between the two worlds …. HTTP Java MessageBodyReader MessageBodyWriter The Millau Viaduct bridge, part E11 highway - connecting Paris and Barcelona. The highest bridge ever constructed. 41
  42. 42. JAX-RS (JSR-311) Providers: » Provides adaptation between the “HTTP world” and our own application domain:  MessageBodyReader,  MessageBodyWriter Java object HTTP Request MessageBodyReader Resource class MessageBodyWriter HTTP Response 42
  43. 43. JAX-RS (JSR-311) @Path("users/{id}/properties") public class UserPropertiesResource { @GET @Produces(“application/json") public User findUser(@PathParam("id") int userId) { return userDao.getUser(userId); { @GET @Produces(“application/atom+xml") public User findUser(@PathParam("id") int userId) { ... } @POST public void findUser(User user) { userDao.persist(user); } { 43
  44. 44. JAX-RS (JSR-311) @Provider @Path("users/{id}/properties") @Produces("application/json") public classclass UserPropertiesResource { public JSONWriter implements MessageBodyWriter<User> { @Override@GET @Produces(“application/json") public long getSize(User user, ...) { public User findUser(@PathParam("id") int userId) { return JSON.toString(user).length(); { // ... { @Override @POST public boolean isWriteable(java.lang.Class<?> type, ...) { return User.class.equals(type);user) { public void findUser(User { // ... } { @Override public void writeTo(User user, ... OutputStream out) { JSON.write(user, out); { 44
  45. 45. 45
  46. 46. JAX-RS (JSR-311) Leading JAX-RS implementations » Glassfish Jersey project (Sun Microsystems),  https://jersey.dev.java.net/ » RESTEasy (JBoss),  http://www.jboss.org/resteasy/ » Apache CXF (Apache Software Foundation),  http://cxf.apache.org/ » Wink (ASF incubation project),  http://incubator.apache.org/wink/ » Restlet (Noelios Technologies).  http://www.restlet.org/ 46
  47. 47. Security (lack of …)
  48. 48. Security Security » Authentication  Who’s calling ? » Authorization  What am I allowed to do ? » Content delivery:  Integrity,  Confidentiality,  Authentication. 48
  49. 49. Security Security » Authentication  Who’s calling ? » Authorization  What am I allowed to do ? » Content delivery:  Integrity,  Confidentiality,  Authentication. 49
  50. 50. Security Security » Authentication  Who’s calling ? » Authorization  What am I allowed to do ? » Content delivery:  Integrity,  Confidentiality,  Authentication. 50
  51. 51. Application-Level Protocols Marshalling REST data
  52. 52. Content deliver Suggestions: » Proprietary (custom made) solution, » Hessian binary web-service protocol (Caucho), » Burlap XML-based web-service protocol (Caucho), » Avro / Buffers protocol, » JSON (JavaScript Object Notion), » Protocol Buffers (by Google) , » Kyro (only for hard-core programmers) 52
  53. 53. Content deliver Proprietary (custom made) solution » When we have a really simple format:  Short-message strings,  Single result objects » Specific binary format,  Multimedia (Images, Movies, etc…),  Proprietary protocol. » Bound to certain technology:  JAXB, DOM-based (JAXP),  Java native (binary) serialization. 53
  54. 54. Content deliver Hessian binary web-service protocol » Binary, compact format. » Very lightweight,  Extremely suitable to mobile or other limited devices.  Provide J2ME libraries. » No external IDL or schema, » Language independent, » Support for compression, encryption, signatures (with partial external support). 54
  55. 55. Content deliver Burlap XML-based web-service protocol » Minimal XML-based format, » Very lightweight (considering XML format),  Provide J2ME libraries. » No external IDL or schema, » Language independent (as XML is !), » Suffice to operate EJB –  Cell phone -> Burlap -> RESTEasy -> EJB ! 55
  56. 56. Content deliver Avro serialization stack » Part of Hadoop stack, » Lightweight, but not as the other protocols. » Requires schema:  Pluggable architecture to support multiple formats (JSON, XML, etc …) » Dynamic typing (very reach with its support), » Untagged data. 56
  57. 57. Summary » REST is a simple WS. » JAX-RS is a reflection of the HTTP world.  Using Java-5 annotations only. » Lack of concrete security model. 57
  58. 58. Q&A
  59. 59. Thank you !!! Applause now !

×