s313265 - advanced java api for restful web services at javaone brazil 2010

38

Upload: arun-gupta

Post on 25-May-2015

1.367 views

Category:

Technology


3 download

DESCRIPTION

S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

TRANSCRIPT

Page 1: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Page 2: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

<Insert Picture Here>

Advanced Java API for RESTful Web ServicesLee Chuk [email protected]

Page 3: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

<Insert Picture Here>

Examine some “advance” features in JAX-RS

Objective

Page 4: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 5: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 6: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 7: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

What is REST?

RequestGET /music/artists/magnum/recordings HTTP/1.1Host: media.example.comAccept: application/xml

ResponseHTTP/1.1 200 OKDate: Tue, 08 May 2007 16:41:58 GMTServer: Apache/1.3.6Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?><recordings xmlns="…"> <recording>…</recording> …</recordings>

Verb Noun

Representation

Statetransfer

Page 8: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

JAX-RS in One Slide

@Path(“/music”)@Produces(“application/xml”)public class 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

www.mymusic.com/music/jazz

Page 9: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Selected Topics• Runtime resource resolution• Integration with EJB and CDI• Runtime content negotiation• Conditional HTTP request• Dealing with type erasure• Pluggable exception handling

Page 10: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Terms• Root resource

• Sub resource method– Handles the request

• Sub resource locator– Returns an object that will handle the request

@Path(“department”)public class Department {

@GET @Path(“{id}”)public Department get(

@PathParam(“id”) String deptId) {

@Path(“{id}”)public Department get(

@PathParam(“id”) String deptId) {

http://server/department/eng

Page 11: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Runtime Resource Resolution

@Path(“department”)public class Department {

@Path(“{id}”)public Object get(

@PathParam(“id”) String id) {//Determine department type and return resourcereturn (new ...);

}

public class Marketing extends Department {@GET @Path(“{type}”)public Response get(

@PathParam(“type”) String deptType) { ... }

Page 12: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Runtime Resource Resolution

@Path(“department”)public class Department {

@Path(“{id}”)public Object get(

@PathParam(“id”) String id) { ... }

public class Marketing extends Department {@GET @Path(“{type}”)public Response get(

@PathParam(“type”) String deptType) { ... }

GET /department/marketing/tele

Page 13: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

DemoDemo

Page 14: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

}

Page 15: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 16: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Integration with EJB • Annotate @Path to convert into a root resource

– Stateless session bean– Singleton bean

@Path("stateless-bean")@Statelesspublic class StatelessResource { ... }

@Path("singleton-bean")@Singletonpublic class SingletonResource { ... }

Page 17: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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);}@ConversationScopedpublic class DefaultShoppingCart implements Cart {

@PersistenceContext private EntityManager em;public void add(Item item) {

… }

}

Page 18: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 19: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 20: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Using CDI with JAX-RS• Request scoped, JAX-RS managed

• Application scoped, CDI managed, will fail

• Application scoped, provide a no-args constructor– Use resource method to get id

@Path(“customer/{id}”)public class Customer {

public Customer(@PathParam(“id”) String id) {

@Path(“customer/{id}”) @ApplicationScopedpublic class Customer {

@Injectpublic Customer(@PathParam(“id”) String id) {

@Path(“customer/{id}”) @ApplicationScopedpublic class Customer {

public Customer() { }

Page 21: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

DemoDemo

Page 22: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Representation

RequestGET /music/artists/magnum/recordings HTTP/1.1Host: media.example.comAccept: application/xml

ResponseHTTP/1.1 200 OKDate: Tue, 08 May 2007 16:41:58 GMTServer: Apache/1.3.6Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?><recordings xmlns="…"> <recording>…</recording> …</recordings>

Format

Page 23: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 24: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 25: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Select Most Acceptable Variant

• Selection will compare the list of variants with the correspond acceptable values in the client request– Accept, Accept-Langauge, Accept-Encoding, Accept-Charset

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

}}

Page 26: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 27: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Processng Etags

@GETpublic Response get(@Context Request r) {

EntityTag et = ... //Calculate etagResponse.ResponseBuilder rb =

r.evaluatePreconditions(et);if (rb != null) {

// Return 304 (Not Modified)return rb.build();

}String rep = ...return Response.ok(rep).tag(et).build();

}

Page 28: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Dealing with Type Erasure – 1 • Resources can return an entity

• Type information is lost when returning Response

• MessageBodyWriter support for List<Customer> will not work when type information is lost– Converts Java object to stream

@GET List<Customer> getCustomers() { ...

@GET Response getCustomers() { List<Customer> list = ...return (Response.ok(list).build());

Page 29: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 30: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Page 31: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 32: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Exception Classes

Class A extends RuntimeException { … }

Class B extends A { … }

Class C extends B { … }

Page 33: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Exception Mapper

@Providerpublic class AMapper

implements ExceptionMapper<A> {public Response toResponse(A a) { … }

}

@Providerpublic class BMapper

implements ExceptionMapper<B> {public Response toResponse(B b) { … }

}

Page 34: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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

Page 35: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

ExceptionMapper• ExceptionMapper “closest” to exception class is

selected to map exception• Can map Throwable

• Inject @Provider to delegate– Map the cause of the exception

@Provider public class CatchAllimplements ExceptionMapper<Throwable> {

public Response toResponse(Throwable t) {// Internal Server Errorreturn Response.status(500).build();

}}

Page 36: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

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.”

Page 37: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

For More Information

search.oracle.com

or

oracle.com

Page 38: S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010

Alternate Title with SubheadArial Size 18 (Gray)

• First-level bullet– Second-level bullet

• Third-level bullet– Fourth-level bullet

• Fifth-level bullet