SlideShare a Scribd company logo
© 2010 VMware Inc. All rights reserved
Building RESTful Web Services with Java
Vassil Popovski (vpopovski@vmware.com)
Staff Engineer, R&D
VMware, Inc.
10/07/2010
2
Agenda
 REST Principles and examples
 Java (JAX-RS) and REST
 Live Demo
 JAX-RS Advanced concepts
3
What is REST?
4
5
What is REST ? (now seriously)
 Representational State Transfer
 Introduced in 2000 by Roy Fielding:
• in his PhD thesis (chapter 5)
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
• Captured his interpretation of the WWW architecture
 Architectural style for distributed system such as World Wide Web
• Note: REST is *not* a standard, just a set of principles
 Positioned as an alternative to WS-* implementations
6
What is REST ? (now seriously)
7
REST Principles (RESTful systems)
Everything is a resource
• Examples: Customer, Locations, Item, List of users
Resources have identifiers
• Examples: URIs for web
Uniform interfaces to access the resources
• Examples: HTTP methods (GET, POST, PUT, DELETE, HEAD)
Resources have representations
• Examples: XML, JSON, Binary
Link resources together
• Hypermedia as the Engine of Application State (HATEOAS)
• Examples: Hyperlinks
1
2
3
4
5
9
Real life example
 Bug tracking system (over simplified)
• Bugs (summary, priority, user who reported it)
• Notes (description, user who created the note)
• Users (user name)
UML Notation:
“whole-part” relationship (composition)
“part” is exclusively owned by “whole”
UML Notation:
One-way association
UML Notation:
Generalization / inheritance
10
Real life example – resources and identifies
 Resources:
• User, Bug, Note,
• All users, All bugs, All notes for a particular bug
 Identifiers
Identifiers Note
http://<host>/users All users
http://<host>/users/{userId} A particular user
http://<host>/bugs All bugs
http://<host>/bugs/{bugId} A particular bug
http://<host>/bugs/{bugId}/notes All notes for a particular bug
http://<host>/bugs/{bugId}/notes/{noteId} A particular note for a particular bug
1 Everything is a resource
2 Resources have identifiers
11
Uniform interfaces (in the context of REST)
 HTTP verbs (CRUD interfaces)
HTTP verb Meaning Safe? Idempotent? Cacheable?
POST Create*
GET Retrieve
PUT Update*
DELETE Delete
f(f(x)) = f(x)
Does not cause
side effects
(*) POST and PUT may also have other meanings
POST – can be used for partial updates and also to add something to a
resource (PASTE AFTER)
PUT – can be used to create if sending the full content of the specified
resource and you know the URI of the resource (PASTE OVER)
12
Real life example – uniform interfaces
Operation Description
GET http://<host>/users List all users
POST http://<host>/users Creates a new user
GET http://<host>/users/345 Retrieves a particular user
PUT http://<host>/users/345 Modifies a particular user
DELETE http://<host>/users/345 Deletes a particular user
Operation Description
GET http://<host>/bugs/234/notes List all notes for bug 234
POST http://<host>/bugs/234/notes Creates a new note for bug 234
[GET | PUT | DELETE] .../bugs/234/notes/34 [retrieves | modifies | deletes]
note 34 in bug 234
3 Uniform interfaces to access the resources
13
Real life example – representations and linking resources
 XML representation for note:
 JSON representation for bug:
GET http://localhost:9000/bugs/1/notes/1
Content-type: application/xml
<Note href=“http://localhost:9000/bugs/1/notes/1">
<description>It is really broken</description>
<owner>http://localhost:9000/users/1</owner>
</Note>
POST http://localhost:9000/bugs
Content-type: application/json
{
"Bug" : {
"priority" : "P1",
"reporter" : "http://localhost:9000/users/1",
"summary" : "Something is wrong"
}
}
4 Resources have representations
5 Link resources together
Note: the client can request
different representations
using “Accept” http header
Note: the client declares what
representation it sends to
server with “Content-type”
http header
14
Java and REST
15
JAX-RS: Java API for RESTful Web Services
 JSR 311 (https://jsr311.dev.java.net/)
• Current version of JAX-RS spec is 1.1
• The spec is “readable”!
• Roy Fielding is an expert group member for this JSR
• javax.ws.rs.*
 JAX-RS in 1 sentence:
• JAX-RS = POJOs + Annotations
 JAX-RS capabilities:
• Dispatch URIs to specific classes and methods that can handle requests
• Methods deal with POJOs (nicely integrates with JAXB)
• Allows to map HTTP requests to method invocations
• URI manipulation functionality
16
JAX-RS implementations
 Jersey (reference implementation)
 Apache CXF (the one used in the demo)
 Apache Wink
 eXo
 RESTEasy
 Restlet
 Triaxrs
17
JAX-RS key concepts
 Resource classes
• Java classes that have at least one method annotated with @Path or a request method designator
(@GET, @PUT, @POST, @DELETE)
• Lifecycle:
• By default a new resource class instance is created for each request
• The JSR does not restrict other implementation specific lifecycles
 Resource methods
• A public method of a resource class annotated with a request method designator (@GET, @PUT,
@POST, @DELETE, @OPTIONS, @HEAD)
 Provider classes
• Classes annotated with @Provider and implementing one or more JAX-RS interfaces:
• MessageBodyReader/MessageBodyWriter
• ExceptionMapper
• ContextResolver
• Lifecycle:
• By default single instance of each provider class is instantiated for each JAX-RS application
• The JSR does not restrict other implementation specific lifecycles
18
JAX-RS annotations (most commonly used)
Annotation Target Description
@Path Class or Method Relative path for a resource
@Consumes
@Produces
Class or Method List of media types that can be consumed /
produced
@GET
@POST
@PUT
@DELETE
@OPTIONS
@HEAD
Method HTTP verb handled by the annotated method
@PathParam Parameter (also
field, POJO method)
Value that can be extracted from URI
@Context Parameter (also
field, POJO method)
Inject contextual information – UriInfo,
HttpHeaders, Request, ContextResolver, etc.
19
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
20
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Base URI path to resource
21
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
The HTTP method for
getUser() method
22
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
URI path
segment/parameter
23
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
GET …/users/{id}
24
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Returned Content-Type
25
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
Injects the value of URI
segment into the id
parameter
26
JAX-RS complete example
@Path("/users")
public class UserHandler {
@GET
@Path("{id}")
@Produces("application/xml”)
public JaxbUser getUser(@PathParam("id") long id) {
...
}
GET http://localhost:9000/users/2
Content-Type: application/xml
<?xml version="1.0" encoding="UTF-8"?>
<User> … </User>
27
28
Demo
to wake you up…
29
Advanced topics
 Regular expressions in @Path
 @*Params
 ExceptionMapper
 MessageBodyReader/MessageBodyWriter
30
@Path and regular expression mappings
 @Path(path-expression)
"{" variable-name [ ":" regular-expression ] "}“
 Examples
• @Path("example2/{var:.+}") matches following:
• …/example2/a
• …/example2/a/b/c
• @Path("example3/{var:d+}") matches following:
• …/example3/345
• …/example3/23
• @Path(“example4/{name}-{id}”) matches following:
• …/example4/a-1
• …/example4/a----1
31
@[Query|Header|Matrix|Cookie|Form]Param
 @QueryParam
• For example …/query?sorted=true
@GET
@Path("query")
public String queryParamExample(@QueryParam(“sorted") String var) {
return var;
}
 @MartixParam
• For example …/users;sorted=true
 @HeaderParam
• For example “Date” header
 @CookieParam / @FormParam
 @DefaultValue – can be used with any @*Param to specify the default
value
32
Exception Mappers
package javax.ws.rs.ext
public interface ExceptionMapper<E extends Throwable> {
Response toResponse(E exception);
}
33
MessageBodyReader
 MessageBodyReader
 MessageBodyWriter
package javax.ws.rs.ext
public interface MessageBodyReader<T> {
boolean isReadable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType);
T readFrom(Class<T> type, Type genericType,
Annotation annotations[], MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException;
}
34
MessageBodyWriter
package javax.ws.rs.ext
public interface MessageBodyWriter<T> {
boolean isWriteable(Class<?> type, Type genericType,
Annotation annotations[], MediaType mediaType);
long getSize(T t, Class<?> type, Type genericType, Annotation annotations[],
MediaType mediaType);
void writeTo(T t, Class<?> type, Type genericType, Annotation annotations[],
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException;
}
35
JAX-RS features that were not covered
 PathSegment
 @Encoded
 @ApplicationPath
 Cookies
 Complex negotiation / Variant processing (javax.ws.rs.core.Variant):
 @OPTIONS, @HEAD, @HttpMethod
 SecurityContext
 CacheControl (+ Etags, conditional GET/PUT)
 Application (+ how to deploy in servlet container, EE6, EJB)
 Integration with Spring
 Security
36
Several other topics not covered
 Restful java clients
 WADL
 REST support in Spring 3.0
37
Additional materials
 Apache CXF (JAX-RS part): http://cxf.apache.org/docs/jax-rs.html
 RESTEasy users guide:
http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/pdf/RESTEas
y_Reference_Guide.pdf
 WizTools REST Client: http://code.google.com/p/rest-client/
38

More Related Content

What's hot (20)

PDF
Java - File Input Output Concepts
Victer Paul
 
PDF
I/O in java Part 1
ashishspace
 
PDF
Files in java
Muthukumaran Subramanian
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
Java file
sonnetdp
 
PPTX
04 darwino concepts and utility classes
darwinodb
 
PPT
14 file handling
APU
 
PPTX
Session 23 - JDBC
PawanMM
 
PPTX
Session 22 - Java IO, Serialization
PawanMM
 
PPTX
Understanding java streams
Shahjahan Samoon
 
PPT
Input output streams
Parthipan Parthi
 
PPT
Java stream
Arati Gadgil
 
PDF
Java IO
UTSAB NEUPANE
 
PPTX
Handling I/O in Java
Hiranya Jayathilaka
 
PPT
Various io stream classes .47
myrajendra
 
PPS
Files & IO in Java
CIB Egypt
 
PDF
input/ output in java
sharma230399
 
PDF
32.java input-output
santosh mishra
 
PPT
Character stream classes introd .51
myrajendra
 
PPT
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java - File Input Output Concepts
Victer Paul
 
I/O in java Part 1
ashishspace
 
Java I/o streams
Hamid Ghorbani
 
Java file
sonnetdp
 
04 darwino concepts and utility classes
darwinodb
 
14 file handling
APU
 
Session 23 - JDBC
PawanMM
 
Session 22 - Java IO, Serialization
PawanMM
 
Understanding java streams
Shahjahan Samoon
 
Input output streams
Parthipan Parthi
 
Java stream
Arati Gadgil
 
Java IO
UTSAB NEUPANE
 
Handling I/O in Java
Hiranya Jayathilaka
 
Various io stream classes .47
myrajendra
 
Files & IO in Java
CIB Egypt
 
input/ output in java
sharma230399
 
32.java input-output
santosh mishra
 
Character stream classes introd .51
myrajendra
 
Chapter 12 - File Input and Output
Eduardo Bergavera
 

Similar to Building Restful Web Services with Java (20)

PPTX
Ppt on web development and this has all details
gogijoshiajmer
 
PPTX
JAX-RS. Developing RESTful APIs with Java
Jerry Kurian
 
PDF
RESTful Java With JAX RS 1st Edition Bill Burke
rohismhmob88
 
PDF
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
PDF
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Arun Gupta
 
PPT
Developing RESTful WebServices using Jersey
b_kathir
 
PDF
RESTful Java With JAX RS 1st Edition Bill Burke
jolokmertah
 
PPTX
6 Months Industrial Training in Spring Framework
Arcadian Learning
 
PDF
RESTful Web services using JAX-RS
Arun Gupta
 
PPTX
RESTful application with JAX-RS and how to expose and test them
Kumaraswamy M
 
PPT
ROA.ppt
KGSCSEPSGCT
 
PPTX
Restful web services with java
Vinay Gopinath
 
PPTX
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
PPTX
Rest
Carol McDonald
 
PPTX
Overview of RESTful web services
nbuddharaju
 
PDF
Introduction to Restful Web Services
weili_at_slideshare
 
PDF
Java colombo-deep-dive-into-jax-rs
Sagara Gunathunga
 
ODP
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
PDF
JAX-RS Creating RESTFul services
Ludovic Champenois
 
PDF
ERRest: the Basics
WO Community
 
Ppt on web development and this has all details
gogijoshiajmer
 
JAX-RS. Developing RESTful APIs with Java
Jerry Kurian
 
RESTful Java With JAX RS 1st Edition Bill Burke
rohismhmob88
 
JAX-RS JavaOne Hyderabad, India 2011
Shreedhar Ganapathy
 
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Arun Gupta
 
Developing RESTful WebServices using Jersey
b_kathir
 
RESTful Java With JAX RS 1st Edition Bill Burke
jolokmertah
 
6 Months Industrial Training in Spring Framework
Arcadian Learning
 
RESTful Web services using JAX-RS
Arun Gupta
 
RESTful application with JAX-RS and how to expose and test them
Kumaraswamy M
 
ROA.ppt
KGSCSEPSGCT
 
Restful web services with java
Vinay Gopinath
 
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
Overview of RESTful web services
nbuddharaju
 
Introduction to Restful Web Services
weili_at_slideshare
 
Java colombo-deep-dive-into-jax-rs
Sagara Gunathunga
 
RESTing with JAX-RS
Ezewuzie Emmanuel Okafor
 
JAX-RS Creating RESTFul services
Ludovic Champenois
 
ERRest: the Basics
WO Community
 
Ad

More from Vassil Popovski (6)

PPTX
Why Teams and Culture Matter: Leadership lessons
Vassil Popovski
 
PPTX
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
Vassil Popovski
 
PPT
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Vassil Popovski
 
PDF
Automated Unit Test Generation - ISTA 2013
Vassil Popovski
 
PDF
Automated unit test generation presentation - Java2ays 2013
Vassil Popovski
 
PPT
Testing multithreaded java applications for synchronization problems
Vassil Popovski
 
Why Teams and Culture Matter: Leadership lessons
Vassil Popovski
 
ISTA 2017: Practical Chatbots - Technology Overview with Real-Life Stories
Vassil Popovski
 
Testing Multithreaded Java Applications for Synchronization Problems, ISTA 2011
Vassil Popovski
 
Automated Unit Test Generation - ISTA 2013
Vassil Popovski
 
Automated unit test generation presentation - Java2ays 2013
Vassil Popovski
 
Testing multithreaded java applications for synchronization problems
Vassil Popovski
 
Ad

Recently uploaded (20)

PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 

Building Restful Web Services with Java

  • 1. © 2010 VMware Inc. All rights reserved Building RESTful Web Services with Java Vassil Popovski ([email protected]) Staff Engineer, R&D VMware, Inc. 10/07/2010
  • 2. 2 Agenda  REST Principles and examples  Java (JAX-RS) and REST  Live Demo  JAX-RS Advanced concepts
  • 4. 4
  • 5. 5 What is REST ? (now seriously)  Representational State Transfer  Introduced in 2000 by Roy Fielding: • in his PhD thesis (chapter 5) http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm • Captured his interpretation of the WWW architecture  Architectural style for distributed system such as World Wide Web • Note: REST is *not* a standard, just a set of principles  Positioned as an alternative to WS-* implementations
  • 6. 6 What is REST ? (now seriously)
  • 7. 7 REST Principles (RESTful systems) Everything is a resource • Examples: Customer, Locations, Item, List of users Resources have identifiers • Examples: URIs for web Uniform interfaces to access the resources • Examples: HTTP methods (GET, POST, PUT, DELETE, HEAD) Resources have representations • Examples: XML, JSON, Binary Link resources together • Hypermedia as the Engine of Application State (HATEOAS) • Examples: Hyperlinks 1 2 3 4 5
  • 8. 9 Real life example  Bug tracking system (over simplified) • Bugs (summary, priority, user who reported it) • Notes (description, user who created the note) • Users (user name) UML Notation: “whole-part” relationship (composition) “part” is exclusively owned by “whole” UML Notation: One-way association UML Notation: Generalization / inheritance
  • 9. 10 Real life example – resources and identifies  Resources: • User, Bug, Note, • All users, All bugs, All notes for a particular bug  Identifiers Identifiers Note http://<host>/users All users http://<host>/users/{userId} A particular user http://<host>/bugs All bugs http://<host>/bugs/{bugId} A particular bug http://<host>/bugs/{bugId}/notes All notes for a particular bug http://<host>/bugs/{bugId}/notes/{noteId} A particular note for a particular bug 1 Everything is a resource 2 Resources have identifiers
  • 10. 11 Uniform interfaces (in the context of REST)  HTTP verbs (CRUD interfaces) HTTP verb Meaning Safe? Idempotent? Cacheable? POST Create* GET Retrieve PUT Update* DELETE Delete f(f(x)) = f(x) Does not cause side effects (*) POST and PUT may also have other meanings POST – can be used for partial updates and also to add something to a resource (PASTE AFTER) PUT – can be used to create if sending the full content of the specified resource and you know the URI of the resource (PASTE OVER)
  • 11. 12 Real life example – uniform interfaces Operation Description GET http://<host>/users List all users POST http://<host>/users Creates a new user GET http://<host>/users/345 Retrieves a particular user PUT http://<host>/users/345 Modifies a particular user DELETE http://<host>/users/345 Deletes a particular user Operation Description GET http://<host>/bugs/234/notes List all notes for bug 234 POST http://<host>/bugs/234/notes Creates a new note for bug 234 [GET | PUT | DELETE] .../bugs/234/notes/34 [retrieves | modifies | deletes] note 34 in bug 234 3 Uniform interfaces to access the resources
  • 12. 13 Real life example – representations and linking resources  XML representation for note:  JSON representation for bug: GET http://localhost:9000/bugs/1/notes/1 Content-type: application/xml <Note href=“http://localhost:9000/bugs/1/notes/1"> <description>It is really broken</description> <owner>http://localhost:9000/users/1</owner> </Note> POST http://localhost:9000/bugs Content-type: application/json { "Bug" : { "priority" : "P1", "reporter" : "http://localhost:9000/users/1", "summary" : "Something is wrong" } } 4 Resources have representations 5 Link resources together Note: the client can request different representations using “Accept” http header Note: the client declares what representation it sends to server with “Content-type” http header
  • 14. 15 JAX-RS: Java API for RESTful Web Services  JSR 311 (https://jsr311.dev.java.net/) • Current version of JAX-RS spec is 1.1 • The spec is “readable”! • Roy Fielding is an expert group member for this JSR • javax.ws.rs.*  JAX-RS in 1 sentence: • JAX-RS = POJOs + Annotations  JAX-RS capabilities: • Dispatch URIs to specific classes and methods that can handle requests • Methods deal with POJOs (nicely integrates with JAXB) • Allows to map HTTP requests to method invocations • URI manipulation functionality
  • 15. 16 JAX-RS implementations  Jersey (reference implementation)  Apache CXF (the one used in the demo)  Apache Wink  eXo  RESTEasy  Restlet  Triaxrs
  • 16. 17 JAX-RS key concepts  Resource classes • Java classes that have at least one method annotated with @Path or a request method designator (@GET, @PUT, @POST, @DELETE) • Lifecycle: • By default a new resource class instance is created for each request • The JSR does not restrict other implementation specific lifecycles  Resource methods • A public method of a resource class annotated with a request method designator (@GET, @PUT, @POST, @DELETE, @OPTIONS, @HEAD)  Provider classes • Classes annotated with @Provider and implementing one or more JAX-RS interfaces: • MessageBodyReader/MessageBodyWriter • ExceptionMapper • ContextResolver • Lifecycle: • By default single instance of each provider class is instantiated for each JAX-RS application • The JSR does not restrict other implementation specific lifecycles
  • 17. 18 JAX-RS annotations (most commonly used) Annotation Target Description @Path Class or Method Relative path for a resource @Consumes @Produces Class or Method List of media types that can be consumed / produced @GET @POST @PUT @DELETE @OPTIONS @HEAD Method HTTP verb handled by the annotated method @PathParam Parameter (also field, POJO method) Value that can be extracted from URI @Context Parameter (also field, POJO method) Inject contextual information – UriInfo, HttpHeaders, Request, ContextResolver, etc.
  • 18. 19 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... }
  • 19. 20 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Base URI path to resource
  • 20. 21 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } The HTTP method for getUser() method
  • 21. 22 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } URI path segment/parameter
  • 22. 23 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } GET …/users/{id}
  • 23. 24 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Returned Content-Type
  • 24. 25 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } Injects the value of URI segment into the id parameter
  • 25. 26 JAX-RS complete example @Path("/users") public class UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... } GET http://localhost:9000/users/2 Content-Type: application/xml <?xml version="1.0" encoding="UTF-8"?> <User> … </User>
  • 26. 27
  • 28. 29 Advanced topics  Regular expressions in @Path  @*Params  ExceptionMapper  MessageBodyReader/MessageBodyWriter
  • 29. 30 @Path and regular expression mappings  @Path(path-expression) "{" variable-name [ ":" regular-expression ] "}“  Examples • @Path("example2/{var:.+}") matches following: • …/example2/a • …/example2/a/b/c • @Path("example3/{var:d+}") matches following: • …/example3/345 • …/example3/23 • @Path(“example4/{name}-{id}”) matches following: • …/example4/a-1 • …/example4/a----1
  • 30. 31 @[Query|Header|Matrix|Cookie|Form]Param  @QueryParam • For example …/query?sorted=true @GET @Path("query") public String queryParamExample(@QueryParam(“sorted") String var) { return var; }  @MartixParam • For example …/users;sorted=true  @HeaderParam • For example “Date” header  @CookieParam / @FormParam  @DefaultValue – can be used with any @*Param to specify the default value
  • 31. 32 Exception Mappers package javax.ws.rs.ext public interface ExceptionMapper<E extends Throwable> { Response toResponse(E exception); }
  • 32. 33 MessageBodyReader  MessageBodyReader  MessageBodyWriter package javax.ws.rs.ext public interface MessageBodyReader<T> { boolean isReadable(Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); T readFrom(Class<T> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException; }
  • 33. 34 MessageBodyWriter package javax.ws.rs.ext public interface MessageBodyWriter<T> { boolean isWriteable(Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); long getSize(T t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType); void writeTo(T t, Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException; }
  • 34. 35 JAX-RS features that were not covered  PathSegment  @Encoded  @ApplicationPath  Cookies  Complex negotiation / Variant processing (javax.ws.rs.core.Variant):  @OPTIONS, @HEAD, @HttpMethod  SecurityContext  CacheControl (+ Etags, conditional GET/PUT)  Application (+ how to deploy in servlet container, EE6, EJB)  Integration with Spring  Security
  • 35. 36 Several other topics not covered  Restful java clients  WADL  REST support in Spring 3.0
  • 36. 37 Additional materials  Apache CXF (JAX-RS part): http://cxf.apache.org/docs/jax-rs.html  RESTEasy users guide: http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/pdf/RESTEas y_Reference_Guide.pdf  WizTools REST Client: http://code.google.com/p/rest-client/
  • 37. 38