4. Architectural Style
• Music styles – baroque, romantic, rap, jazz, etc
– There is no Jazz (music) note
– How you put the notes that makes the style
• Computing styles – client/server, object oriented, etc.
– There is no client/server API
• “... a coordinated set of architectural constraints that
restricts the roles/features of architectural elements
and the allowed relationships among those elements
within any architecture that conforms to that style” -
Dr. Roy Fielding
5. What is REST?
• REpresentation State Transfer
– Architectural Styles and the Design of Network-based
Software Architecture – Roy Fielding PhD thesis
• Major components
– Nouns (resources) are identified by URIs
– A small subset of verbs to manipulate the nouns
– State of the data
– Representation is how you would like to view the state
• Use verbs to exchange application states and
representation
• Hypermedia is the engine for application state
transition
6. REST Example
• HTTP is one of the most RESTful protocol
• Example: the web browser
– The URL is the noun (resource)
– GET (verb) the page from the server
– State of the page is transferred from the server to the browser
• Page maybe static or dynamic
• State of page now exists on the client
– Page may be represented as HTML, RSS, JSON, etc.
– Click on a link in page (hypermedia) the process is repeated
7. What is REST?
Request
GET /music/artists/magnum/recordings HTTP/1.1
Host: media.example.com
Accept: application/xml
Verb Response Noun
HTTP/1.1 200 OK
Date: Tue, 08 May 2007 16:41:58 GMT
Server: Apache/1.3.6
Content-Type: application/xml; charset=UTF-8
State <?xml version="1.0"?>
<recordings xmlns="…">
transfer <recording>…</recording>
… Representation
</recordings>
8. JAX-RS in One Slide
@Path(“/music”)
@Produces(“application/xml”)
public class Music { www.mymusic.com/music
@GET //Returns List<Genre>
public Response getGenreList() {
...
}
@GET @Path(“{genre}”) //Returns List<Song>
public Response getSongs(
@PathParam(“genre”) String genreId) {
...
} www.mymusic.com/music/jazz
}
9. Selected Topics
• Runtime resource resolution
• Integration with EJB and CDI
• Runtime content negotiation
• Conditional HTTP request
• Dealing with type erasure
• Pluggable exception handling
10. Terms
• Root resource
http://server/department/eng
@Path(“department”)
public class Department {
• Sub resource method
– Handles the request
@GET @Path(“{id}”)
public Department get(
@PathParam(“id”) String deptId) {
• Sub resource locator
– Returns an object that will handle the request
@Path(“{id}”)
public Department get(
@PathParam(“id”) String deptId) {
11. Runtime Resource Resolution
@Path(“department”)
public class Department {
@Path(“{id}”)
public Object get(
@PathParam(“id”) String id) {
//Determine department type and return resource
return (new ...);
}
public class Marketing extends Department {
@GET @Path(“{type}”)
public Response get(
@PathParam(“type”) String deptType) { ... }
12. Runtime Resource Resolution
@Path(“department”)
public class Department {
@Path(“{id}”)
public Object get(
@PathParam(“id”) String id) { ... }
GET /department/marketing/tele
public class Marketing extends Department {
@GET @Path(“{type}”)
public Response get(
@PathParam(“type”) String deptType) { ... }
14. More Resource Resolution
• Sub resource locators determines what type of
resource to return dynamically
– Eg. Use JPA to query data and return that as a resource
– Can be used with CDI or EJBs
– All parameters must be annotated
@Path(“department”)
public class Department {
@Path(“{id}”)
public Object get(@PathParam(“id”) String id) {
EntityManager em = ... //Get an instance
Department dept = em.find(Department.class, id);
return (dept);
}
15. Resource Methods and Locators
• Easy to get confuse with sub-resource locator and
sub-resource methods
• Both are annotated with @Path
• Sub-resource methods has resource method
designators
– Eg. @GET
• Sub-resource locator do not have method designators
16. Integration with EJB
• Annotate @Path to convert into a root resource
– Stateless session bean
– Singleton bean
@Path("stateless-bean")
@Stateless
public class StatelessResource { ... }
@Path("singleton-bean")
@Singleton
public class SingletonResource { ... }
17. CDI One Pager
@Stateless public class ShoppingService {
@Inject private Cart myCart;
public void addToCart(Item someItem) {
myCart.add(someItem);
}
…
}
public interface Cart {
public void add(Item item);
}
@ConversationScoped
public class DefaultShoppingCart implements Cart {
@PersistenceContext private EntityManager em;
public void add(Item item) {
…
}
}
18. Using CDI with Root Resources
• Perfect world – use CDI to manage REST resources
– CDI providing lifecycle management, dependency, etc
• Not very well specified
• See http://www.mentby.com/paul-sandoz/jax-rs-on-
glassfish-31-ejb-injection.html
19. JAX-RS/CDI Component Models
• Root resources are managed in the request scope
– Default
• CDI requires “normal” scoped beans to be proxyable
– Annotated with @RequestScoped or @ApplicationScoped
– Unproxyable beans
• No non-private constructor with no argument
• Final class
• Root resources needs to be annotated with CDI
scoped to be managed by CDI
20. Using CDI with JAX-RS
• Request scoped, JAX-RS managed
@Path(“customer/{id}”)
public class Customer {
public Customer(@PathParam(“id”) String id) {
• Application scoped, CDI managed, will fail
@Path(“customer/{id}”) @ApplicationScoped
public class Customer {
@Inject
public Customer(@PathParam(“id”) String id) {
• Application scoped, provide a no-args constructor
– Use resource method to get id
@Path(“customer/{id}”) @ApplicationScoped
public class Customer {
public Customer() { }
22. Representation
Request
GET /music/artists/magnum/recordings HTTP/1.1
Host: media.example.com
Accept: application/xml
Format
Response
HTTP/1.1 200 OK
Date: Tue, 08 May 2007 16:41:58 GMT
Server: Apache/1.3.6
Content-Type: application/xml; charset=UTF-8
<?xml version="1.0"?>
<recordings xmlns="…">
<recording>…</recording>
…
</recordings>
23. Supported Media Types
• Out-of-the-box support for
– */* - byte[], InputStream, DataSource
– text/* - String
– text/xml, application/xml, application/*+xml –
JAXBElement
– application/x-www-form-urlencoded –
MultivalueMap
• Use @Produces or @Consumes to match with HTTP
headers
– Accept, Content-Type
24. Runtime Content Negotiation
• Static content/media type negotiation of
representation supported with @Produces
• Runtime content negotiation of representation
supports 4 dimensions
– Media type, character set, language, encoding
• Each representation has a Variant which is a point
in the 4 dimension space
List<Variant> variant = Variant
.mediaType(MediaType.APPLICATION.JSON
, MediaType.APPLICATION.XML)
.languages(Locale.ENGLISH, Locale.CHINESE);
assert variant.size() == 4
25. Select Most Acceptable Variant
@GET public Response get(@Context Request r) {
List<Variant> vs = ...
Variant v = r.selectVariant(vs);
if (v == null)
return (Response.notAcceptable(vs).build());
else {
Object rep = selectRepresentation(v);
return (Response.ok(rep, v));
}
}
• Selection will compare the list of variants with the
correspond acceptable values in the client request
– Accept, Accept-Langauge, Accept-Encoding, Accept-
Charset
26. Conditional HTTP Request
• Save bandwidth and client processing
– A GET can return a 304 (not modified) if representation has
not changed since previous request
• Avoid the lost update problem
– A PUT can return 412 (precondition failed) if the resource state
has been modified since previous request
• A date and/or entity tag can be used
– Last-Modified and Etag headers
– HTTP dates have granularity of 1 second
– Etags are better for use with PUT
28. Dealing with Type Erasure – 1
• Resources can return an entity
@GET List<Customer> getCustomers() { ...
• Type information is lost when returning Response
@GET Response getCustomers() {
List<Customer> list = ...
return (Response.ok(list).build());
• MessageBodyWriter support for List<Customer>
will not work when type information is lost
– Converts Java object to stream
29. Dealing with Type Erasure – 2
• Use GenericEntity to preserve type information at
runtime
@GET Response getCustomers() {
List<Customer> list = ...
GenericEntity<List<Customer>> ge =
new GenericEntity<List<Customer>>(list){};
return (Response.ok(list).build());
30.
31. Pluggable Exception Handling
• Propagation on unmapped exceptions to web
container
– A runtime exception thrown by the JAX-RS container or
application is propagated as is
– A checked exception is thrown by the application is
propagated as the cause of a ServletException
– Propagated exceptions can be mapped to error pages
• Runtime/checked exceptions can be “caught” and
mapped to Response using ExceptionMapper
32. Exception Classes
Class A extends RuntimeException { … }
Class B extends A { … }
Class C extends B { … }
33. Exception Mapper
@Provider
public class AMapper
implements ExceptionMapper<A> {
public Response toResponse(A a) { … }
}
@Provider
public class BMapper
implements ExceptionMapper<B> {
public Response toResponse(B b) { … }
}
34. Throwing Exceptions
// throwing A maps to Response of AMapper
@GET public String a() throws A { ... }
// throwing B maps to Response of BMapper
@GET public String b() throws B { ... }
// throwing C maps to Response of BMapper
@GET public String c() throws C { ... }
35. ExceptionMapper
• ExceptionMapper “closest” to exception class is
selected to map exception
• Can map Throwable
@Provider public class CatchAll
implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable t) {
// Internal Server Error
return Response.status(500).build();
}
}
• Inject @Provider to delegate
– Map the cause of the exception
36. We encourage you to use the newly minted corporate tagline
“Software. Hardware. Complete.” at the end of all your presentations.
This message should replace any reference to our previous corporate
tagline “Oracle Is the Information Company.”