KEMBAR78
Building Restful Web Services with Java | PPTX
© 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

Building Restful Web Services with Java

  • 1.
    © 2010 VMwareInc. All rights reserved Building RESTful Web Services with Java Vassil Popovski (vpopovski@vmware.com) Staff Engineer, R&D VMware, Inc. 10/07/2010
  • 2.
    2 Agenda  REST Principlesand examples  Java (JAX-RS) and REST  Live Demo  JAX-RS Advanced concepts
  • 3.
  • 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 (RESTfulsystems) 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 (inthe 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
  • 13.
  • 14.
    15 JAX-RS: Java APIfor 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 (mostcommonly 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") publicclass UserHandler { @GET @Path("{id}") @Produces("application/xml”) public JaxbUser getUser(@PathParam("id") long id) { ... }
  • 19.
    20 JAX-RS complete example @Path("/users") publicclass 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") publicclass 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") publicclass 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") publicclass 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") publicclass 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") publicclass 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") publicclass 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  Regularexpressions in @Path  @*Params  ExceptionMapper  MessageBodyReader/MessageBodyWriter
  • 29.
    30 @Path and regularexpression 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 • Forexample …/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 publicinterface ExceptionMapper<E extends Throwable> { Response toResponse(E exception); }
  • 32.
    33 MessageBodyReader  MessageBodyReader  MessageBodyWriter packagejavax.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 interfaceMessageBodyWriter<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 thatwere 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 topicsnot covered  Restful java clients  WADL  REST support in Spring 3.0
  • 36.
    37 Additional materials  ApacheCXF (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.