SlideShare a Scribd company logo
1 of 51
Download to read offline
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 +
                        CSS, etc




                          XML
Programmable web       (or JSON)
Every web site is a service
Enabling automation
REST, spelled out




   REpresentational State Transfer
RESTful architectural principles

  Addressable resources
  Uniformed, constrained interface
  Representation-oriented
  Stateless communication
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
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)
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
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)
Stateless communication

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

  Request               Response
  –   HTTP method       –   HTTP response code
  –   URI               –   Response headers
  –   Request headers   –   Entity body
  –   Entity body
What do you need to REST?

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




                                  JAX-RS
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+
Our first REST resource




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

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

    @GET
    public String getUpdates() {
      return "<updates><update>...</update></updates>";
    }

}
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!
Throttling the response




   http://socialize.com/rest/timeline?count=25
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
Parameter types

  @QueryParam – Query string
  @HeaderParam – HTTP header
  @CookieParam – HTTP cookie
  @FormParam – Form input
  @PathParam – URI path
  @MatrixParam – Matrix URI segment
Stepping into a sub-resource




   http://socialize.com/rest/timeline/mojavelinux
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) {
      ...
    }

}
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) {
      ...
    }
}
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
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) {
      ...
    }

    ...
}
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) {
      ...
    }

    ...
}
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
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;
    }

}
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

}
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);
    }

}
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
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);
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
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>
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 timelineDao;

    @GET
    @Path("/{u}")
    @Produces("application/xml")
    public Timeline getUpdates(@PathParam("u") String u) {
      return timelineDao.fetchTimelineForUsername(u);
    }

}
Trapping exceptions

<exception class="com.socialize.NoSuchUserException">
 <http-error error-code="404">
    <message>No such user</message>
 </http-error>
</exception>
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>
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());
    }
}
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);
    }

}
Socialize demo
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...
Must reads




  RESTful Web Services   RESTful Java with JAX-RS
  Richardson & Ruby      Bill Burke
  O’Reilly               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
  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

More Related Content

What's hot

RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
Shaun Smith
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 
WCF Data Services - Office Business Application &amp; iPhone
WCF Data Services - Office Business Application &amp; iPhoneWCF Data Services - Office Business Application &amp; iPhone
WCF Data Services - Office Business Application &amp; iPhone
Andri Yadi
 
Introduction to RESTful Webservice
Introduction to RESTful WebserviceIntroduction to RESTful Webservice
Introduction to RESTful Webservice
Eftakhairul Islam
 
quickguide-einnovator-8-spring-cloud
quickguide-einnovator-8-spring-cloudquickguide-einnovator-8-spring-cloud
quickguide-einnovator-8-spring-cloud
jorgesimao71
 

What's hot (20)

RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
SCDJWS 6. REST JAX-P
SCDJWS 6. REST  JAX-PSCDJWS 6. REST  JAX-P
SCDJWS 6. REST JAX-P
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
 
RESTful services with JAXB and JPA
RESTful services with JAXB and JPARESTful services with JAXB and JPA
RESTful services with JAXB and JPA
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
WCF Data Services - Office Business Application &amp; iPhone
WCF Data Services - Office Business Application &amp; iPhoneWCF Data Services - Office Business Application &amp; iPhone
WCF Data Services - Office Business Application &amp; iPhone
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Hadoop introduction
Hadoop introductionHadoop introduction
Hadoop introduction
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
Json to hive_schema_generator
Json to hive_schema_generatorJson to hive_schema_generator
Json to hive_schema_generator
 
Introduction to RESTful Webservice
Introduction to RESTful WebserviceIntroduction to RESTful Webservice
Introduction to RESTful Webservice
 
REST presentation
REST presentationREST presentation
REST presentation
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
 
quickguide-einnovator-8-spring-cloud
quickguide-einnovator-8-spring-cloudquickguide-einnovator-8-spring-cloud
quickguide-einnovator-8-spring-cloud
 
Introduction to JAX-RS @ SIlicon Valley Code Camp 2010
Introduction to JAX-RS @ SIlicon Valley Code Camp 2010Introduction to JAX-RS @ SIlicon Valley Code Camp 2010
Introduction to JAX-RS @ SIlicon Valley Code Camp 2010
 

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

Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with Java
Vassil Popovski
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
Java Technology
Java TechnologyJava Technology
Java Technology
ifnu bima
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
elliando dias
 
03 form-data
03 form-data03 form-data
03 form-data
snopteck
 

Similar to CDI, Seam & RESTEasy: You haven't seen REST yet! (20)

Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
 
RESTful Web services using JAX-RS
RESTful Web services using JAX-RSRESTful Web services using JAX-RS
RESTful Web services using JAX-RS
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
JSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian MotlikJSUG - RESTful Web Services by Florian Motlik
JSUG - RESTful Web Services by Florian Motlik
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RSSpark IT 2011 - Developing RESTful Web services with JAX-RS
Spark IT 2011 - Developing RESTful Web services with JAX-RS
 
Felix HTTP - Paving the road to the future
Felix HTTP - Paving the road to the futureFelix HTTP - Paving the road to the future
Felix HTTP - Paving the road to the future
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Building Restful Web Services with Java
Building Restful Web Services with JavaBuilding Restful Web Services with Java
Building Restful Web Services with Java
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
REST
RESTREST
REST
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
 
RESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test themRESTful application with JAX-RS and how to expose and test them
RESTful application with JAX-RS and how to expose and test them
 
REST made simple with Java
REST made simple with JavaREST made simple with Java
REST made simple with Java
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
 
Rest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swaggerRest with java (jax rs) and jersey and swagger
Rest with java (jax rs) and jersey and swagger
 
03 form-data
03 form-data03 form-data
03 form-data
 

More from Dan Allen

More from Dan Allen (7)

Real Java Enterprise Testing
Real Java Enterprise TestingReal Java Enterprise Testing
Real Java Enterprise Testing
 
Arquillian: The Extendable Enterprise Test Platform
Arquillian: The Extendable Enterprise Test PlatformArquillian: The Extendable Enterprise Test Platform
Arquillian: The Extendable Enterprise Test Platform
 
Moving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutterMoving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutter
 
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
 
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
 
CDI, Weld and the future of Seam
CDI, Weld and the future of SeamCDI, Weld and the future of Seam
CDI, Weld and the future of Seam
 
Real Java EE Testing with Arquillian and ShrinkWrap
Real Java EE Testing with Arquillian and ShrinkWrapReal Java EE Testing with Arquillian and ShrinkWrap
Real Java EE Testing with Arquillian and ShrinkWrap
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

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

  • 1. CDI, Seam & RESTEasy You haven’t seen REST yet! Dan Allen Senior Software Engineer JBoss, by Red Hat
  • 2. Agenda REST principles JAX-RS Seam RESTEasy integration JAX-RS enhanced with CDI Demo
  • 4. REST to the rescue Web Service
  • 5. Staying grounded with REST Simple Lightweight High performance
  • 6. Simple ingredients of the Web HTTP application protocol URI naming standard XML markup language (and alternatives)
  • 7. A tale of two webs Document HTML + Browsable web images + CSS, etc XML Programmable web (or JSON)
  • 8. Every web site is a service
  • 10. REST, spelled out REpresentational State Transfer
  • 11. RESTful architectural principles Addressable resources Uniformed, constrained interface Representation-oriented Stateless communication
  • 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. 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. 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. 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. Stateless communication More scalable – GET lends itself well to caching Client maintains state Takes burden off server
  • 17. Respect the medium Request Response – HTTP method – HTTP response code – URI – Response headers – Request headers – Entity body – Entity body
  • 18. What do you need to REST? HTTP client (browser, bot, smart phone) HTTP server that speaks REST JAX-RS
  • 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. Our first REST resource http://socialize.com/rest/timeline
  • 21. Our first JAX-RS resource @Path("/timeline") public class TimelineService { @GET public String getUpdates() { return "<updates><update>...</update></updates>"; } }
  • 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. Throttling the response http://socialize.com/rest/timeline?count=25
  • 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. Parameter types @QueryParam – Query string @HeaderParam – HTTP header @CookieParam – HTTP cookie @FormParam – Form input @PathParam – URI path @MatrixParam – Matrix URI segment
  • 26. Stepping into a sub-resource http://socialize.com/rest/timeline/mojavelinux
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. REST as a Seam resource http://socialize.com/seam/resources/rest/timeline/mojavelinux
  • 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. Trapping exceptions <exception class="com.socialize.NoSuchUserException"> <http-error error-code="404"> <message>No such user</message> </http-error> </exception>
  • 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. 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. 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); } }
  • 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. Must reads RESTful Web Services RESTful Java with JAX-RS Richardson & Ruby Bill Burke O’Reilly O’Reilly
  • 49. To follow me mojavelinux
  • 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