SlideShare una empresa de Scribd logo
1 de 77
Descargar para leer sin conexión
BeJUG JAX-RS
Representational State Transfer
      theory and JAX-RS
Me, Me, Me…
• Alex Van Boxel
  – R&D Engineer : Progress Software
     • DataDirect : All sorts of middleware stuff ( database,
       xml, xquery, data virtualization )
• Low-level stuff
  – So the Enterprise stack is a hobby project
  – To keep track of what happens in the real world
• So don’t kill me if I can’t answer all your
  questions about this topic.
BeJUG JAX-RS Agenda
• REST theory
  – Core principles
  – Anti-Patterns
  – Patterns
• JAX-RS
  – Introduction
  – The Code
     • JAX-RS (1) : Life cycle en Path matching
     • JAX-RS (2) : Content and Update
     • JAX-RS (3) : Providers
REST
Representational State Transfer, Core
   principles and (Anti)patterns.
BeJUG JAX-RS Agenda
• REST theory
  – Core principles
  – Anti-Patterns
  – Patterns
• JAX-RS
  – Introduction
  – The Code
     • JAX-RS (1) : Life cycle en Path matching
     • JAX-RS (2) : Content and Update
     • JAX-RS (3) : Providers
Representational State Transfer

REST
Core REST principles
1.   Addressability
2.   Connectedness
3.   Uniform Interface
4.   Representations
5.   Statelessness
(1) Addressability
• All resources should have an ID
• In RESTful web services: URI representation
• Everything should be a resource
     • The more, the better
     • Process step: ex. salery increase should be a resource
• Actually violated by a lot of framework, where
  everything is tunneled though POST
(1) Addressability (cont.)
• Nice example: Amazon
    • Everything has an ID
    • You can send link
    • http://www.amazon.com/gp/product/B002JCSV8A/


• More framework SHOULD support
  addressability
    • First step to being RESTful
Core REST principles
1.   Addressability
2.   Connectedness
3.   Uniform Interface
4.   Representations
5.   Statelessness
(2) Connectedness
• Link everything together
<member id=“/../members/me”>
  <membership ref=“/../memberships/0042”/>
    <link ref=“delete” method=“DELETE” ref=“..”/>
</member>

• Provide as much as possible
      • Relations
      • Actions
• This will help the client discover the actions
Core REST principles
1.   Addressability
2.   Connectedness
3.   Uniform Interface
4.   Representations
5.   Statelessness
(3) Uniform Interface
• You limit yourself to a Uniform interface for
  ALL resources
• HTTP methods
     • GET/PUT/POST/DELETE
• HTTP:GET safe get representation
  – 80% reading (web optimized)
  – If your don’t make it safe, it your fault if google
    deletes your record, by following a link
(3) Uniform Interface
• HTTP:PUT
  – Create a new resource (app manager id)
  – Modify an existing resource
• HTTP:POST
  – Create a new resource (server manager id)
     • Create subordinate resources
• HTTP:DELETE
  – Delete a resource
Interlude (1+2+3)
• /memberships/
    •   GET: list all events (ref= to real entities)
    •   POST: create a membership (id is container managed)
    •   PUT: not used (405: Method not allowed, Accept=GET,POST)
    •   DELETE: not used (idem)
• /memberships/00042
    •   GET: get a membership with ID 00042
    •   POST: not used (405, Accept=GET,PUT,DELETE)
    •   PUT: update a membership
    •   DELETE: delete a membership
Interlude (1+2+3)
• /events/
     •   GET: list all events
     •   POST: not used (id is client managed 405, Accept=GET)
     •   PUT: t(405, Accept=GET )
     •   DELETE: not used (405, Accept=GET )
• /events/2010jaxrs
     •   GET: get an event with ID 2010jaxrs
     •   POST: not used (405, Accept=GET,PUT,DELETE)
     •   PUT: create/update an event
     •   DELETE: delete an event
Core REST principles
1.   Addressability
2.   Connectedness
3.   Uniform Interface
4.   Representations
5.   Statelessness
(4) Representations
• You interact with the resource through a
  representation
• Representation : ANY usefull information about
  the state of a resource
• Accept: header
  – Tell the server what the client understands
• Supply machine readable formats
  – Even different formats (xml, json)
  – Or different formats
  – Supply human readable formats (XHTML)
(4) Representations
• Example: a person
  – Browser: Accept: application/xml
     • Send xml+ref=“xslt”
  – Old browser: Accept: text/html
     • Send transformed xml+xslt > html
  – Outlook
     • Import text/x-vcard
  – Internal business app (old and new)
     • application/vnd.bejug.v1.member+xml
     • application/vnd.bejug.v2.member+xml
Core REST principles
1.   Addressability
2.   Connectedness
3.   Uniform Interface
4.   Representations
5.   Statelessness
(5) Statelessness
• Your communication with the server is
  stateless
• Server doesn’t keep state
  – HTTP Request happens in complete isolation
  – HTTP Request includes all information to full the
    request
  – The server never relies on information from a
    previous request
(5) Statelessness (cont.)
• Possible states of the server are resources
  – The client should not trick the server into a state
    to listen to a certain request
• Application- versus Resource state?
  – Application state should only live on the client
(5) Statelessness (cont.)
• Example: Search Engine
• Stateless
   – Application state (on client) current query and page
      • search?query=jaxrs&page=2
      • search?query=jaxrs&page=3
• Statefull (not REST)
      • search?query=jaxrs
      • search?page=2
   – State would make individual HTTP request simpler, but
     would make the protocal more complex
(5) Statelessness (cont.)
• Example: Shopping card
  – Classic implementation: Memory state
  – Make it a resource… persist it…
  – Accept as an URL
(5) Statelessness (cont.)
• Stateless brings a few benefits
  – Scalability
     • No 2 request depend on each other
     • Load-balancing ( Cluster )
  – Cacheable
     • Again not depended on a previous state
     • So easier to cache
• HTTP is stateless by default
     • You have to do some work to break it
So is REST simple?
• Need a shift in thinking
• Identifying resources
• Externalizing the state

• But if done right, it can be a useful tool
     • Consumption oriented
     • Inversion of Control
Don’t do this, Don’t do that

REST ANTI-PATTERNS
REST ANTI-PATTERNS
1.   Tunneling over GET
2.   Tunneling over POST
3.   Ignore cache
4.   Ignore status code
5.   Hypermedia & MIME
6.   Break self descriptiveness
Anti-Pattern (1): Tunneling over GET
• Tunneling thought GET
  – http://ex.org/endpoint?method=delete&id=666
     • Resources are not identified by URI
     • HTTP method doesn’t match semantics
     • Not bookmarkable
Anti-Pattern (1): Tunneling over GET
• Is this a RESTful URI:
  some-app/method-findEvent?id=2010jax-rs
    • Accidently RESTful
• -> read only API. OK, but what if it’s extended
  with a update API using the same URI scheme.
  Better:
  /events/2010jax-rs
Anti-Pattern (2): Tunneling over POST
• Tunneling though POST
     • Is actually what SOAP does
     • Not cacheable for reads
     • Again not bookmarkable
• A lot of other framework violate this as well
Anti-Pattern (2): Tunneling over POST
• <soap:Env>
• Endpoint -> dead end
• WSDL -> generate client specifically written for
  that endpoint
• In defense: SOAP-WS not be meant to be on
  the web, but generic
Anti-Pattern (3) : Ignore caching
• Ignoring caching
     • ETag support
     • If-Modified-Since
     • Don’t ignore on server, and don’t forget the client
Anti-Pattern (3) : Ignore caching
•   Is the stock qoute updates? NO … waiting 2s…
•   Is the stock qoute updates? NO … waiting 2s…
•   Is the stock qoute updates? NO … waiting 2s…
•   Is the stock qoute updates? NO … waiting 2s…
•   Is the stock qoute updates? NO … waiting 2s…
•   Is the stock qoute updates? NO … waiting 2s…
      •   80% requests : GET
      •   Provide an expires value
      •   After the expire time, check the E-TAG
      •   You don’t need to check it every 2 seconds when you know
          in advance it has a 15 minutes delay.
Anti-Pattern (3) : Ignore caching
• E-Tag : A HASH value
• If-not-monified: 404 not modified
Anti-Pattern (4): Ignore status codes
• Ignoring status codes
     • HTTP has a rich set of application level error codes
        –   200: OK
        –   201: Created
        –   404: Not found (resource not found)
        –   409: Conflict (concurrent update?)
        –   410: Gone (it was here but is now gone?)
     • Accepts: What methods are allowed
Anti-Pattern (4): Ignore status codes
•   Did the operation succeed?
•   Everything created as intended?
•   Can we continue?
•   Did you accept the request?
Small sample
•   100 Continue                   •   404 Not Found
•   101 Switch Protocols           •   304 Method Not Allowed
•   200 OK                         •   406 Not Acceptable
•   201 Created                    •   407 Proxy Authentication Required
•   202 Accepted                   •   408 Request Timeout
•   203 Non-Authoritative          •   409 Conflict
•   204 No Content                 •   410 Gone
•   205 Reset Content              •   411 Length Required
•   206 Partial Content            •   412 Precondition Failed
•   300 Multiple Choices           •   413 Request Entity Too Lange
•   301 Moved Permanently          •   414 Request-URI Too Long
•   302 Found                      •   415 Unsupported Media Type
•   303 See Oher                   •   416 Requested Range Not Satisfiable
•   304 Not Modified               •   417 Expectation Failed
•   305 Use Proxy                  •   500 Internal Server Error
•   307 Temporary Redirect         •   501 Not Implemented
•   400 Bad Request                •   502 Bad Gateway
•   401 Unauthorized               •   503 Service Unavailable
•   402 Payment Required           •   504 Gateway Timeout
•   403 Forbidden                  •   505 HTTP Version Not Supported
Anti-Pattern (5): Hypermedia & MIME
• Link everything together
     • Ideally a client should get everywhere from one URI
     • Even know what actions are available
     • No dead ends (what are the relations?)
• Ignore MIME types
     •   HTTP allows content negotiation
     •   Ex: Machine readable (XML) vs Human Readable (PDF)
     •   Ex: Language binding: XML, JSON, YAML
     •   vnd.mytype (but look for a standard one)
     •   XHTML (with micro-formats?)
Break self descriptiveness
• URI: good, but do you need a manual to to
  know how to constuct the URI?
• You should discover the URI’s
  – <link ref=“update” …/>
The good

PATTERNS
URI design
• WARNING: Don’t worry too much about URI
  design
• But it’s good practice
• Linking is important, you should think about
  that, more than having a nice URI design
• Make them self descriptive
Named Link
• Standard method of giving a meaning to a link
  – alternate representations
     • <link rel=“alternate” type=“application/atom+xml”
       href=“self”/>

  – actions
     • <link ref=“delete” method=“DELETE” href=“self”/>

  – navigation
     • <link ref=“next” type=“application/xml”
       method=“GET” href=“self?page=2”/>
Collection Resource
• Related resources grouped
     • /events/
     • /memberships/0042/invoices/
     • /members/
• Collections are resources (accessable by URI)
• Collection representation should can contain
  usefull information
     • point to other resources
     • contain summary information n
Read only views
• Multiviews of the same collection
     /events/ < all
     /events/?tag=REST
     /events/?limit=10
     /events/2009/10/
     /memberships/0042/invoices/?outstanding=true
Resource Creation
• POST to an entity to a collection resource
• You receive a 201: location
     • If you do it again you create yet another resource
     • After POST you can update with the URI using PUT


• Alternative: Client UUID: PUT it
Paging
Return subset
Embed links to the next/prev chunks
  <link rel=“self” type=“” ref=“”/>
  <link rel=“next” type=“” ref=“”/>
  <link rel=“prev” type=“” ref=“”/>

  /events/?page=2
Notification Polling
• Polling: Not for real time update (for real time
  extensions look@PubSubHubbub)
• Expose a view as RSS/Atom
• BUT: ensure cache control headers
     • ETag
     • Last-Modified
• Atom views: Loose coupling: better then
  traditional SOA
Conflict
• Protect against concurrent modification
  – Lost update problem
• HTTP solutions
  – Provide Etag
  – Last-Modified Headers
  – Pre-conditions
• HTTP response codes
  – 409 Conflict
  – 412 Pre-Condition Failed
Extensions
• Supports linking to different representations
• It’s not one of my favorites, but…
• Increases testability
  /members/r2d2
  /members/r2d2.xhtml
  /members/r2d2.json
  /members/r2d2.vcard
Canonical Representation
• Similar like implementing .toString() in Java
  – It helps debugging
• HTML presentation
• HTML forms for input
Deep ETags
• Hash calculated on limited set of data (not
  complete response)
Externalize Caching
• Server: Concentrate on the correct headers
     •   E-tag
     •   Last Modified
     •   Deep E-tags
     •   Simplified
Putting theory into practice
BeJUG JAX-RS Agenda
• REST theory
  – Core principles
  – Anti-Patterns
  – Patterns
• JAX-RS
  – Introduction
  – The Code
     • JAX-RS (1) : Life cycle en Path matching
     • JAX-RS (2) : Content and Update
     • JAX-RS (3) : Providers
Java™ API for RESTful
Web Services

JAX-RS INTRO
JSR311 : JAX-RS
• Annotation driven API
• Help developers build RESTful Web Services
  – Guides novice developers
  – Intuitive for advanced developers
• J2EE6 integration
JSR311 : JAX-RS
• Remember: This is a tool
• You still need to learn the core REST principles
• You can still abuse the API to build non-
  RESTfull application
     • It’s not the API that should be RESTfull
     • It’s the application that you build that need to be
       RESTfull
JAX-RS implementations
• CXF
• Jersey
     • The reference implementation. Bundled with GlassFish
• RESTEasy
     • JBoss implementation. Seems to have some nice
       extensions
• RESTlet
     • REST api pioneers, now support JAX-RS as a plus
     • Seems to have a good client api (have a look…)
The Code

JAX-RS (1): LIFE CYCLE AND PATH
MATCHING
JAX-RS (1): Life cycle and Path
               matching
• The Resource Classes
  – Lifecycle
     • Default is per request (makes sense in REST)
     1. Constructor is called (with params if available)
     2. Dependencies are injected (don’t use the
        dependencies in the constructor!
     3. Appropriate method is called
     4. Resource is GC’ed
JAX-RS (1): Life cycle and Path
               matching
• Annotations
  – Path matching
     • @Path
  – Parameter matching
     • @PathParam, @QueryParam, @CookieParam,
       @HeaderParam, @MatrixParam
     • @DefaultValue
  – Injection
     • @Context
     • Request, UriInfo, Application, SecurityContext, <T>
  – Method (@GET, …)
Life cycle and Path matching

JAX-RS (1) CODE SESSION
The Code

JAX-RS (2) : CONTENT AND UPDATE
JAX-RS (2) : Content and Update
• HTTP verbs (methods)
     • @GET, @POST, @PUT, @DELETE
• Content Negotiation
     • @Consumes and @Produces
• Response Utilities
     • UriBuilder and Response
• Standard Entity Providers
     • What JavaType <> Content Type
JAX-RS (2) : Content and Update
• Content Negotiation
  – Incoming:
     • @Consumes(mime-type)
  – Outgoing:
     • @Produces(mime-type)
• Mime
  – type (text, application, …)
  – subtype ( plain, html, … , xml, json, …)
JAX-RS (2) : Content and Update
• Response
  – Helps to create a proper response
     • Errors
     • Headers
     • Redirect
• UriBuilder
  – Helps to create URI’s
JAX-RS (2) : Content and Update
• Standard Entity Providers
     •   Byte[] : mime ( */* )
     •   String : mime ( */* )
     •   InputStream : mime ( */* )
     •   Reader : mime ( */* )
     •   File : mime ( */* )
     •   DataSource : mime ( */* )
     •   Source : mime ( */*xml )
     •   JAXB : mime ( */*xml )
     •   MulticalueMap<String,String> : mime (application/x-
         www-form-urlencoded )
Content and Update

JAX-RS (2) CODE SESSION
The Code

JAX-RS (3) : PROVIDERS
JAX-RS (3) Providers
• 3 types of providers
  – Context Provider
  – Entity Provider
     • MessageBody(Writer/Reader)
  – Exception Mapping Provider
• All annotated with @Provider
Providers

JAX-RS (3) CODE SESSION
JAX-RS : The Code
• URL mapping
     • @Path, @GET, @PathParam, @QueryParam,…
• Consuming requests
     • @POST, @FormParam
• JAXB integration
     • Producing/Consument
• Content Negotiation
     • @Consumes and @Produces
• Building URI and Response
     • UriBuilder and Response
JAX-RS : The advanced
• Advanced, but oh so useful
• MessageBodyWriter/Reader
  – @Provider: VCard example
  – @Provider: XStream integration
Java™ API for RESTful
Web Services

REFERENCES
References
• Video
  – Parleys: Stefan Tilkov (RESTful Design)
  – Parleys: JAX-RS: The Java API for RESTful Web s.
• Audio
  – Episode 98: Stefan Tilkov on REST
• Web
  – JAX-RS spec ( quite readable )
References
• Book
  – RESTful Web Services


• Me again
    • http://alex.vanboxel.be
    • email:alex@vanboxel.be
    • http://twitter.com/alexvb

    +

Más contenido relacionado

La actualidad más candente

WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects OptimizationWO Community
 
Webinar: What's New in Solr 7
Webinar: What's New in Solr 7 Webinar: What's New in Solr 7
Webinar: What's New in Solr 7 Lucidworks
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Apache Solr crash course
Apache Solr crash courseApache Solr crash course
Apache Solr crash courseTommaso Teofili
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conferenceErik Hatcher
 
Battle of the Giants round 2
Battle of the Giants round 2Battle of the Giants round 2
Battle of the Giants round 2Rafał Kuć
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and TricksMaksym Bruner
 
Data Science with Solr and Spark
Data Science with Solr and SparkData Science with Solr and Spark
Data Science with Solr and SparkLucidworks
 
Enterprise Search Using Apache Solr
Enterprise Search Using Apache SolrEnterprise Search Using Apache Solr
Enterprise Search Using Apache Solrsagar chaturvedi
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solrKnoldus Inc.
 
Sem tech 2010_integrity_constraints
Sem tech 2010_integrity_constraintsSem tech 2010_integrity_constraints
Sem tech 2010_integrity_constraintsClark & Parsia LLC
 
Solr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksSolr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksErik Hatcher
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchFrom zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchRafał Kuć
 
Использование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайтуИспользование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайтуOlga Lavrentieva
 
A Survey of Elasticsearch Usage
A Survey of Elasticsearch UsageA Survey of Elasticsearch Usage
A Survey of Elasticsearch UsageGreg Brown
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to SolrErik Hatcher
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 

La actualidad más candente (20)

WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
Hibernate performance tuning
Hibernate performance tuningHibernate performance tuning
Hibernate performance tuning
 
Webinar: What's New in Solr 7
Webinar: What's New in Solr 7 Webinar: What's New in Solr 7
Webinar: What's New in Solr 7
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Solr Recipes
Solr RecipesSolr Recipes
Solr Recipes
 
Apache Solr crash course
Apache Solr crash courseApache Solr crash course
Apache Solr crash course
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
 
Battle of the Giants round 2
Battle of the Giants round 2Battle of the Giants round 2
Battle of the Giants round 2
 
REST Api Tips and Tricks
REST Api Tips and TricksREST Api Tips and Tricks
REST Api Tips and Tricks
 
Data Science with Solr and Spark
Data Science with Solr and SparkData Science with Solr and Spark
Data Science with Solr and Spark
 
Enterprise Search Using Apache Solr
Enterprise Search Using Apache SolrEnterprise Search Using Apache Solr
Enterprise Search Using Apache Solr
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solr
 
Sem tech 2010_integrity_constraints
Sem tech 2010_integrity_constraintsSem tech 2010_integrity_constraints
Sem tech 2010_integrity_constraints
 
Solr Indexing and Analysis Tricks
Solr Indexing and Analysis TricksSolr Indexing and Analysis Tricks
Solr Indexing and Analysis Tricks
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchFrom zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and Elasticsearch
 
Использование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайтуИспользование Elasticsearch для организации поиска по сайту
Использование Elasticsearch для организации поиска по сайту
 
it's just search
it's just searchit's just search
it's just search
 
A Survey of Elasticsearch Usage
A Survey of Elasticsearch UsageA Survey of Elasticsearch Usage
A Survey of Elasticsearch Usage
 
Introduction to Solr
Introduction to SolrIntroduction to Solr
Introduction to Solr
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 

Similar a BeJUG JAX-RS Event

REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologiesjrodbx
 
RESTful web
RESTful webRESTful web
RESTful webAlvin Qi
 
RESTful modules in zf2
RESTful modules in zf2RESTful modules in zf2
RESTful modules in zf2Corley S.r.l.
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11Evert Pot
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfPatiento Del Mar
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST Ram Awadh Prasad, PMP
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 
Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIsamesar0
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeCale Hoopes
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application TechnologiesSam Bowne
 
REST 101: An Overview To Representational State Transfer.
REST 101: An Overview To Representational State Transfer.REST 101: An Overview To Representational State Transfer.
REST 101: An Overview To Representational State Transfer.Omar Fernando Zafe
 
Coding 100-session-slides
Coding 100-session-slidesCoding 100-session-slides
Coding 100-session-slidesCisco DevNet
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesSam Bowne
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debateRestlet
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
 
Mendix rest services
Mendix rest servicesMendix rest services
Mendix rest servicesG Acellam
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Restful风格ž„web服务架构
Restful风格ž„web服务架构Restful风格ž„web服务架构
Restful风格ž„web服务架构Benjamin Tan
 

Similar a BeJUG JAX-RS Event (20)

REST Methodologies
REST MethodologiesREST Methodologies
REST Methodologies
 
RESTful web
RESTful webRESTful web
RESTful web
 
RESTful modules in zf2
RESTful modules in zf2RESTful modules in zf2
RESTful modules in zf2
 
So you think you know REST - DPC11
So you think you know REST - DPC11So you think you know REST - DPC11
So you think you know REST - DPC11
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdf
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
Pragmatic REST APIs
Pragmatic REST APIsPragmatic REST APIs
Pragmatic REST APIs
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's Rye
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 
REST 101: An Overview To Representational State Transfer.
REST 101: An Overview To Representational State Transfer.REST 101: An Overview To Representational State Transfer.
REST 101: An Overview To Representational State Transfer.
 
Coding 100-session-slides
Coding 100-session-slidesCoding 100-session-slides
Coding 100-session-slides
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
The never-ending REST API design debate
The never-ending REST API design debateThe never-ending REST API design debate
The never-ending REST API design debate
 
Rest web services
Rest web servicesRest web services
Rest web services
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Mendix rest services
Mendix rest servicesMendix rest services
Mendix rest services
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Restful风格ž„web服务架构
Restful风格ž„web服务架构Restful风格ž„web服务架构
Restful风格ž„web服务架构
 

Más de Stephan Janssen

Devoxx speaker training (June 27th, 2018)
Devoxx speaker training (June 27th, 2018)Devoxx speaker training (June 27th, 2018)
Devoxx speaker training (June 27th, 2018)Stephan Janssen
 
The new DeVoxxEd websites with JHipster, Angular & Kubernetes
The new DeVoxxEd websites with JHipster, Angular & KubernetesThe new DeVoxxEd websites with JHipster, Angular & Kubernetes
The new DeVoxxEd websites with JHipster, Angular & KubernetesStephan Janssen
 
The new Voxxed websites with JHipster, Angular and GitLab
The new Voxxed websites  with JHipster, Angular and GitLabThe new Voxxed websites  with JHipster, Angular and GitLab
The new Voxxed websites with JHipster, Angular and GitLabStephan Janssen
 
Devoxx2011 timesheet day3-4-5
Devoxx2011 timesheet day3-4-5Devoxx2011 timesheet day3-4-5
Devoxx2011 timesheet day3-4-5Stephan Janssen
 
Devoxx2011 timesheet day1-2
Devoxx2011 timesheet day1-2Devoxx2011 timesheet day1-2
Devoxx2011 timesheet day1-2Stephan Janssen
 

Más de Stephan Janssen (17)

Devoxx speaker training (June 27th, 2018)
Devoxx speaker training (June 27th, 2018)Devoxx speaker training (June 27th, 2018)
Devoxx speaker training (June 27th, 2018)
 
The new DeVoxxEd websites with JHipster, Angular & Kubernetes
The new DeVoxxEd websites with JHipster, Angular & KubernetesThe new DeVoxxEd websites with JHipster, Angular & Kubernetes
The new DeVoxxEd websites with JHipster, Angular & Kubernetes
 
The new Voxxed websites with JHipster, Angular and GitLab
The new Voxxed websites  with JHipster, Angular and GitLabThe new Voxxed websites  with JHipster, Angular and GitLab
The new Voxxed websites with JHipster, Angular and GitLab
 
Java, what's next?
Java, what's next?Java, what's next?
Java, what's next?
 
Programming 4 kids
Programming 4 kidsProgramming 4 kids
Programming 4 kids
 
Devoxx2011 timesheet day3-4-5
Devoxx2011 timesheet day3-4-5Devoxx2011 timesheet day3-4-5
Devoxx2011 timesheet day3-4-5
 
Devoxx2011 timesheet day1-2
Devoxx2011 timesheet day1-2Devoxx2011 timesheet day1-2
Devoxx2011 timesheet day1-2
 
EJB 3.1 by Bert Ertman
EJB 3.1 by Bert ErtmanEJB 3.1 by Bert Ertman
EJB 3.1 by Bert Ertman
 
Whats New In Java Ee 6
Whats New In Java Ee 6Whats New In Java Ee 6
Whats New In Java Ee 6
 
Glass Fishv3 March2010
Glass Fishv3 March2010Glass Fishv3 March2010
Glass Fishv3 March2010
 
Advanced Scrum
Advanced ScrumAdvanced Scrum
Advanced Scrum
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Intro To OSGi
Intro To OSGiIntro To OSGi
Intro To OSGi
 
Kick Start Jpa
Kick Start JpaKick Start Jpa
Kick Start Jpa
 
BeJUG - Di With Spring
BeJUG - Di With SpringBeJUG - Di With Spring
BeJUG - Di With Spring
 
BeJUG - Spring 3 talk
BeJUG - Spring 3 talkBeJUG - Spring 3 talk
BeJUG - Spring 3 talk
 
BeJug.Org Java Generics
BeJug.Org   Java GenericsBeJug.Org   Java Generics
BeJug.Org Java Generics
 

BeJUG JAX-RS Event

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