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

Post on 25-May-2015

1.367 Views

Category:

Technology

3 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

TRANSCRIPT

<Insert Picture Here>

Advanced Java API for RESTful Web ServicesLee Chuk Munnchuk-munn.lee@oracle.com

<Insert Picture Here>

Examine some “advance” features in JAX-RS

Objective

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

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

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

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

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

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

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

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

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

DemoDemo

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

}

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

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

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

… }

}

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

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

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() { }

DemoDemo

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

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

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

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

}}

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

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

}

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

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

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

Exception Classes

Class A extends RuntimeException { … }

Class B extends A { … }

Class C extends B { … }

Exception Mapper

@Providerpublic class AMapper

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

}

@Providerpublic class BMapper

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

}

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

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

}}

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

For More Information

search.oracle.com

or

oracle.com

Alternate Title with SubheadArial Size 18 (Gray)

• First-level bullet– Second-level bullet

• Third-level bullet– Fourth-level bullet

• Fifth-level bullet

top related