CDI, Seam & RESTEasy
       You haven’t seen REST yet!



Dan Allen
Senior Software Engineer
JBoss, by Red Hat
Agenda

 REST principles
 JAX-RS
 Seam RESTEasy integration
 JAX-RS enhanced with CDI
 Demo
Abusing HTTP with SOAP
REST to the rescue




        Web Service
Staying grounded with REST

  Simple
  Lightweight
  High performance
Simple ingredients of the Web

  HTTP application protocol
  URI naming standard
  XML markup language
  (and alternatives)
A tale of two webs

                   Document


                        HTML +
   Browsable web       images +
         ...
Every web site is a service
Enabling automation
REST, spelled out




   REpresentational State Transfer
RESTful architectural principles

  Addressable resources
  Uniformed, constrained interface
  Representation-oriented
  S...
Addressable resources

  URI for every resource in system
  Resource reachable by unique ID
  http://socialize.com/rest/up...
Uniformed, constrained interface

  Protocol method == operation
  –   4 HTTP methods: GET, PUT, DELETE, POST
  An archite...
HTTP methods

 GET - read only, idempotent and safe
 PUT - insert or update, idempotent
 DELETE - remove services, idempot...
Representation-oriented

  Data has a representation
  –   Negotiated between client and server
  HTTP was designed for th...
Stateless communication

  More scalable
  –   GET lends itself well to caching
  Client maintains state
  Takes burden of...
Respect the medium

  Request               Response
  –   HTTP method       –   HTTP response code
  –   URI             ...
What do you need to REST?

  HTTP client (browser, bot, smart phone)
  HTTP server that speaks REST




                  ...
JSR-311: JAX-RS

  Java APIs for developing Web Services
  following the REST architectural style
  Served via an HTTP ser...
Our first REST resource




      http://socialize.com/rest/timeline
Our first JAX-RS resource

@Path("/timeline")
public class TimelineService {

    @GET
    public String getUpdates() {
  ...
How it works

  REST Servlet handles GET request
  Instance of TimelineService is created
  @GET method called
  Return va...
Throttling the response




   http://socialize.com/rest/timeline?count=25
Accepting a query parameter

@Path("/timeline")
public class TimelineService {

    @GET
    public String getUpdates(@Que...
Parameter types

  @QueryParam – Query string
  @HeaderParam – HTTP header
  @CookieParam – HTTP cookie
  @FormParam – For...
Stepping into a sub-resource




   http://socialize.com/rest/timeline/mojavelinux
Mapping a path parameter

@Path("/timeline")                  Name defined in path expression;
                           ...
Mapping different patterns

@Path("/timeline")
public class TimelineService {

    @GET
    @Path("/{id:[0-9]+}")
    publ...
Negotiating a response

  Which representation?
  –   Plain text?
  –   HTML?
  –   XML?
  –   JSON?
  The client needs to...
Producing explicitly

@Path("/timeline")                        Specify which formats are
                                ...
Producing explicitly

@Path("/timeline")                         Specify which formats are
                               ...
Simplifying response production

  Creating XML and JSON is laborious :(
  JAX-RS supports converters
  –   HTTP entity bo...
A model with XML hints

@XmlRootElement(name = "updates")
public class Timeline implements Serializable {

    private Lis...
A related model with XML hints

@Entity
@XmlRootElement
public class Update implements Serializable {

    private Long id...
Turning production over to JAXB

@Path("/timeline")
public class TimelineService {

    @GET
    @Path("/{u}")
    @Produc...
RESTEasy

 Fully certified JAX-RS implementation
 Portable to any container
 Embedded server for testing
 Client-side fram...
Invoking a service with RESTEasy

public interface TimelineClient {

    @GET
    @Path("/timeline")
    @Produces("applic...
What does Seam 2 provide?

  RESTEasy bootstrap and configuration
  –   Automatic resource/provider discovery
  –   Resour...
Typical JAX-RS setup (Java EE 5)

public abstract class Application {
  public abstract Set<Class<?>> getClasses();
  publ...
REST as a Seam resource




http://socialize.com/seam/resources/rest/timeline/mojavelinux
Seam-infused REST

@Name("timelineService")
@Path("/timeline")
public class TimelineService {
  @In TimelineDao timelineDa...
Trapping exceptions

<exception class="com.socialize.NoSuchUserException">
 <http-error error-code="404">
    <message>No ...
REST in a few fragments

<components>
 <framework:entity-home name="userHome"
   entity-class="com.socialize.model.User"/>...
Java EE 6, keeping it simple

@ApplicationPath("rest")
public class JaxRsConfig extends Application {}

@Stateless
@Path("...
Java EE 6, keeping it clean

@ApplicationPath("rest")
public class JaxRsConfig extends Application {}

@Stateless
@Path("/...
Socialize demo
Summary and call to action

  Respect HTTP
  –   Resources are the foundation of the web
  Expose your data in a standard ...
Must reads




  RESTful Web Services   RESTful Java with JAX-RS
  Richardson & Ruby      Bill Burke
  O’Reilly           ...
To follow me


               mojavelinux
GET /questions? HTTP/1.1
Presentation resources

  JSR-311
  –   http://jcp.org/en/jsr/detail?id=311
  RESTEasy
  –   http://jboss.org/resteasy
  S...
Upcoming SlideShare
Loading in …5
×

CDI, Seam & RESTEasy: You haven't seen REST yet!

10,391 views

Published on

JSR-311 (JAX-RS) is one of the simplest, most elegant of all the Java EE specifications. It enables you to create RESTful web services from POJOs by sprinkling a handful of annotations on them. As of Java EE 6, JAX-RS resources can now tie into the rest of the Java EE platform through the use of the standard contexts and dependency injection.
facility (JSR-299: CDI).

Seam's RESTEasy module takes this a step further by allowing you to use JAX-RS annotations on your existing Seam components, giving your REST resources access to the Seam container, infusing them with enhanced security, persistence management and other Seam portable extensions. You'll also discover that Seam eliminates the configuration required to add JAX-RS to your application and you'll be enthralled by the module's innovative approach to doing CRUD over REST. Using Seam, CDI and JAX-RS together let's you REST like never before.

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
10,391
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
102
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

CDI, Seam & RESTEasy: You haven't seen REST yet!

  1. 1. CDI, Seam & RESTEasy You haven’t seen REST yet! Dan Allen Senior Software Engineer JBoss, by Red Hat
  2. 2. Agenda REST principles JAX-RS Seam RESTEasy integration JAX-RS enhanced with CDI Demo
  3. 3. Abusing HTTP with SOAP
  4. 4. REST to the rescue Web Service
  5. 5. Staying grounded with REST Simple Lightweight High performance
  6. 6. Simple ingredients of the Web HTTP application protocol URI naming standard XML markup language (and alternatives)
  7. 7. A tale of two webs Document HTML + Browsable web images + CSS, etc XML Programmable web (or JSON)
  8. 8. Every web site is a service
  9. 9. Enabling automation
  10. 10. REST, spelled out REpresentational State Transfer
  11. 11. RESTful architectural principles Addressable resources Uniformed, constrained interface Representation-oriented Stateless communication
  12. 12. Addressable resources URI for every resource in system Resource reachable by unique ID http://socialize.com/rest/updates/311 Provides scoping information – Query string used to narrow result set Stepping stones – Makes it possible to link (linkability) – Allows disparate applications to interact
  13. 13. Uniformed, constrained interface Protocol method == operation – 4 HTTP methods: GET, PUT, DELETE, POST An architecture based on 4 methods? – SQL (SELECT, INSERT, UPDATE, DELETE) – JMS (send, receive)
  14. 14. HTTP methods GET - read only, idempotent and safe PUT - insert or update, idempotent DELETE - remove services, idempotent POST - NOT idempotent NOR unsafe – constraints are relaxed for flexibility
  15. 15. Representation-oriented Data has a representation – Negotiated between client and server HTTP was designed for this purpose Client – “I would prefer...” – Accept (MIME type) – Accept-Language – Accept-Encoding Server – “Here's what I'll give you...” – Content-type header (MIME type)
  16. 16. Stateless communication More scalable – GET lends itself well to caching Client maintains state Takes burden off server
  17. 17. Respect the medium Request Response – HTTP method – HTTP response code – URI – Response headers – Request headers – Entity body – Entity body
  18. 18. What do you need to REST? HTTP client (browser, bot, smart phone) HTTP server that speaks REST JAX-RS
  19. 19. JSR-311: JAX-RS Java APIs for developing Web Services following the REST architectural style Served via an HTTP servlet Goals: – POJO-based (annotations) – HTTP-centric – Format independent (MIME type) – Container independent – Inclusion in Java EE 5+
  20. 20. Our first REST resource http://socialize.com/rest/timeline
  21. 21. Our first JAX-RS resource @Path("/timeline") public class TimelineService { @GET public String getUpdates() { return "<updates><update>...</update></updates>"; } }
  22. 22. How it works REST Servlet handles GET request Instance of TimelineService is created @GET method called Return value sent as response Resource instance thrown away JAX-RS component model is intentionally simple!
  23. 23. Throttling the response http://socialize.com/rest/timeline?count=25
  24. 24. Accepting a query parameter @Path("/timeline") public class TimelineService { @GET public String getUpdates(@QueryParam("count") @DefaultValue("50") int count) { ... } } http://socialize.com/rest/timeline ↴ http://socialize.com/rest/timeline?count=50
  25. 25. Parameter types @QueryParam – Query string @HeaderParam – HTTP header @CookieParam – HTTP cookie @FormParam – Form input @PathParam – URI path @MatrixParam – Matrix URI segment
  26. 26. Stepping into a sub-resource http://socialize.com/rest/timeline/mojavelinux
  27. 27. Mapping a path parameter @Path("/timeline") Name defined in path expression; segment injected into method public class TimelineService { @GET @Path("/{username}") public String getUpdates(@PathParam("username") String u) { ... } }
  28. 28. Mapping different patterns @Path("/timeline") public class TimelineService { @GET @Path("/{id:[0-9]+}") public String getUpdatesById(@PathParam("id") long id) { ... } Fallback if patterns don't match @GET @Path("/{username}") public String getUpdatesByUsername( @PathParam("username") String u) { ... } }
  29. 29. Negotiating a response Which representation? – Plain text? – HTML? – XML? – JSON? The client needs to tell us – Accept formats, weighted by preference We have to decide what we support – Respond with best match
  30. 30. Producing explicitly @Path("/timeline") Specify which formats are supported using @Produces public class TimelineService { @GET @Path("/{u}") @Produces("application/xml") public String getUpdatesAsXml(@PathParam("u") String u) { ... } ... }
  31. 31. Producing explicitly @Path("/timeline") Specify which formats are supported using @Produces public class TimelineService { @GET @Path("/{u}") @Produces("application/json") public String getUpdatesAsJson(@PathParam("u") String u) { ... } ... }
  32. 32. Simplifying response production Creating XML and JSON is laborious :( JAX-RS supports converters – HTTP entity body readers/writers Provides built-in JAXB provider! – Object ⇔ XML – Object ⇔ JSON
  33. 33. A model with XML hints @XmlRootElement(name = "updates") public class Timeline implements Serializable { private List<Update> updates = new ArrayList<Update>(); // constructors @XmlElement(name = "update") public List<Update> getUpdates() { return updates; } public void setUpdates(List<Update> updates) { this.updates = updates; } }
  34. 34. A related model with XML hints @Entity @XmlRootElement public class Update implements Serializable { private Long id; private User user; private Date created; private String text; // getters and setters }
  35. 35. Turning production over to JAXB @Path("/timeline") public class TimelineService { @GET @Path("/{u}") @Produces("application/xml") public Timeline getUpdates(@PathParam("u") String u) { List<Update> updates = ...; return new Timeline(updates); } }
  36. 36. RESTEasy Fully certified JAX-RS implementation Portable to any container Embedded server for testing Client-side framework for JAX-RS Response caching and compression Rich set of providers – XML, JSON, RSS, Atom, YAML, etc. Asynchronous support
  37. 37. Invoking a service with RESTEasy public interface TimelineClient { @GET @Path("/timeline") @Produces("application/xml") Timeline getUpdates(@QueryParam("count") int count); } TimelineClient client = ProxyFactory.create(TimelineClient.class, ROOT_URI); String response = client.getUpdates(25);
  38. 38. What does Seam 2 provide? RESTEasy bootstrap and configuration – Automatic resource/provider discovery – Resources/providers are Seam components Seam security – HTTP authentication – Authorization: @Restrict, @PermissionCheck Exception to HTTP response mapping Media type extension mapping REST CRUD framework SeamTest support
  39. 39. Typical JAX-RS setup (Java EE 5) public abstract class Application { public abstract Set<Class<?>> getClasses(); public abstract Set<Object>getSingletons(); } public SocializeConfig extends Application { ... } <context-param> <param-name>javax.ws.rs.core.Application</param-name> <param-value>com.socialize.SocializeConfig</param-value> </context-param>
  40. 40. REST as a Seam resource http://socialize.com/seam/resources/rest/timeline/mojavelinux
  41. 41. Seam-infused REST @Name("timelineService") @Path("/timeline") public class TimelineService { @In TimelineDao timelineDao; @GET @Path("/{u}") @Produces("application/xml") public Timeline getUpdates(@PathParam("u") String u) { return timelineDao.fetchTimelineForUsername(u); } }
  42. 42. Trapping exceptions <exception class="com.socialize.NoSuchUserException"> <http-error error-code="404"> <message>No such user</message> </http-error> </exception>
  43. 43. REST in a few fragments <components> <framework:entity-home name="userHome" entity-class="com.socialize.model.User"/> <resteasy:resource-home name="userResourceHome" path="/users" entity-home="#{userHome}" entity-id-class="java.lang.Long" media-types="application/xml application/json" readonly="false"/> <resteasy:resource-query name="userResourceQuery" path="/users" entity-class="com.socialize.model.User" media-types="application/xml application/json"/> </components>
  44. 44. Java EE 6, keeping it simple @ApplicationPath("rest") public class JaxRsConfig extends Application {} @Stateless @Path("/timeline") Must be a managed public class TimelineService { bean to enable CDI @PersistenceContext EntityManager em; @GET @Path("/{u}") @Produces("application/xml") public Timeline getUpdates(@PathParam("u") String u) { return new Timeline(em.createQuery( "select u from Update u where u.user.username = :u") .setParameter("u", u).getResultList()); } }
  45. 45. Java EE 6, keeping it clean @ApplicationPath("rest") public class JaxRsConfig extends Application {} @Stateless @Path("/timeline") public class TimelineService { @Inject TimelineDao timelineDao; @GET @Path("/{u}") @Produces("application/xml") public Timeline getUpdates(@PathParam("u") String u) { return timelineDao.fetchTimelineForUsername(u); } }
  46. 46. Socialize demo
  47. 47. Summary and call to action Respect HTTP – Resources are the foundation of the web Expose your data in a standard way – Don’t ball it up inside web pages! Embrace simplicity – Seam 2 + RESTEasy – Java EE 6 (JAX-RS + CDI) – Seam 3 integration coming soon...
  48. 48. Must reads RESTful Web Services RESTful Java with JAX-RS Richardson & Ruby Bill Burke O’Reilly O’Reilly
  49. 49. To follow me mojavelinux
  50. 50. GET /questions? HTTP/1.1
  51. 51. Presentation resources JSR-311 – http://jcp.org/en/jsr/detail?id=311 RESTEasy – http://jboss.org/resteasy Seam RESTEasy integration – Web Services chapter of Seam reference guide Bill Burke’s REST series on DZone – http://java.dzone.com/articles/putting-java-rest Code samples – http://seaminaction.googlecode.com/svn/demos

×