Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 1
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 2 JAX-RS 2.0: New and Noteworthy in the RESTful Web Services API John Clingan Java EE and GlassFish Product Manager
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 16 What’s New in JAX-RS 2.0 JAX-RS Review Client API Common Configuration Asynchronous Processing Filters/Interceptors Hypermedia Support Server-side Content Negotiation
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 4 JAX-RS – Java API for RESTful Services POJO-Based Resource Classes HTTP Centric Programming Model Entity Format Independence Container Independence Included in Java EE Standard annotation-driven API that aims to help developers build RESTful Web services and clients in Java
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide public Money String String pin, String amount) { return getMoney(card, pin, amount); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 6 JAX-RS Annotations MethodAnnotation possibly cached or create without a known ID or create with a known ID with no response methods
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 7 JAX-RS Annotations (Continued) the value from the value of query the value of a the value of a HTTP the value of an HTML the value of a matrix parameter,
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 8 JAX RS 2.0 Client API
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 9 Client API HTTP client libraries too low level Leveraging providers/concepts from JAX-RS 1.x API Proprietary APIs introduced by major implementations Motivation
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Client API // Get instance of Client Client client = ClientBuilder.newClient(); // Get account balance String bal = client.target(" " ").queryParam("pin", "9876").request("text/plain").get(String.class);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Client API // Withdraw some money Money money = client.target(" " ").queryParam("pin", "9876").request("application/json").post(text("50.0"), Money.class);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Client API Invocation invocation1 = client.target(" Invocation invocation2 = client.target("
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Client API Collection invocations = Arrays.asList(inv1, inv2); Collection responses = Collections.transform( invocations, new F () { public Response apply(Invocation invocation) { return invocation.invoke(); } });
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Client API // Create client and register MyProvider1 Client client = ClientBuilder.newClient(); client.register(MyProvider1.class); // Create atm target; inherits MyProvider1 WebTarget atm = client.target(" // Register MyProvider2 atm.register(MyProvider2.class); // Create balance target; inherits MyProvider1, MyProvider2 WebTarget balance = atm.path(”{cardId}/balance"); // Register MyProvider3 balance.register(MyProvider3.class);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX RS 2.0 Common Configuration
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration - Motivation Client-side client.register(JsonMessageBodyReader.class).register(JsonMessageBodyWriter.class).register(JsonpInterceptor.class).property(“jsonp.callback.name”, “callback”).property(“jsonp.callback.queryParam”, “true”)...
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration - Motivation Server-side public class MyApp extends javax.ws.rs.core.Application { public Set > getClasses() { Set > classes = new HashSet ();... classes.add(JsonMessageBodyReader.class); classes.add(JsonMessageBodyWriter.class); classes.add(JsonpInterceptor.class);... return classes; }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration - Solution Client-side client.register(JsonMessageBodyReader.class).register(JsonMessageBodyWriter.class).register(JsonpInterceptor.class).property(“jsonp.callback.name”, “callback”).property(“jsonp.callback.queryParam”, “true”)... JsonFeature jf = new JsonFeature().enableCallbackQueryParam(); client.register(jf);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration - Solution Server-side public Set > getClasses() {... classes.add(JsonMessageBodyReader.class); classes.add(JsonMessageBodyWriter.class); classes.add(JsonpInterceptor.class);... } public Set > getClasses() {... classes.add(JsonFeature.class);... }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration public interface Configurable { Configuration getConfiguration(); Configurable property(String name, Object value); Configurable register(...); } public interface Configuration { Set getClasses(); Map getContracts(Class componentClass); Set getInstances(); Map getProperties(); Object getProperty(String name); Collection getPropertyNames(); boolean isEnabled(Feature feature); boolean isRegistered(Object component);... }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Common Configuration public interface Feature { boolean configure(FeatureContext context); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide A Feature Example public void JsonFeature implements Feature { public boolean configure(FeatureContext context) { context.register(JsonMessageBodyReader.class).register(JsonMessageBodyWriter.class).register(JsonpInterceptor.class).property(CALLBACK_NAME, calbackName).property(USE_QUERY_PARAM, useQueryParam); return true; }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Dynamic Feature Server-side only public interface DynamicFeature { void configure(ResourceInfo ri, FeatureContext context); } public interface ResourceInfo { Method getResourceMethod(); Class getResourceClass(); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX RS 2.0 Asynchronous Processing
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Asynchronous Processing Server API – Off-load I/O container threads – Efficient asynchronous event processing – Leverage Servlet 3.x async support (if available) Client API – Asynchronous request invocation API
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide public class public void AsyncResponse ar) { ar.setTimeoutHandler(new MyTimoutHandler()); ar.setTimeout(15, SECONDS); final String result = executeLongRunningOperation(); ar.resume(result); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Asynchronous Processing: Server Side public interface AsyncResponse { public void resume(Object/Throwable response); public void cancel(); public void cancel(int/Date retryAfter); public boolean isSuspended(); public boolean isCancelled(); public boolean isDone(); public void setTimeout(long time, TimeUnit unit); public void setTimeoutHandler(TimeoutHandler handler); public Collection > register(Class callback); public Map,Collection >> register(Class callback, Class... callbacks); public Collection > register(Object callback); public Map,Collection >> register(Object callback, Object... callbacks); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Asynchronous Processing: @Documented Suspended { } public interface TimeoutHandler { void handleTimeout(AsyncResponse asyncResponse); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Asynchronous Processing: Server Side public interface CompletionCallback { public void onComplete(Throwable throwable); } public interface ConnectionCallback { public void onDisconnect(AsyncResponse disconnected); }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Asynchronous Processing: Client Side WebTarget target = client.target(" // Start async call and register callback Future handle = target.request().async().get( new InvocationCallback () { void complete(String balance) { … } void failed(InvocationException e) { … } }); // After waiting for too long… if (!handle.isDone()) handle.cancel(true);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX RS 2.0 Filters/Interceptors
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors Customize JAX-RS request/response processing – Use Cases: Logging, Compression, Security, etc. Introduced for client and server APIs Replace existing proprietary support Motivation
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors Non-wrapping filter chain – Filters do not invoke next filter in the chain directly – Managed by the JAX-RS runtime Each filter decides to proceed or break the chain Filter each incoming/outgoing message Request Request – ContainerRequestFilter, ClientRequestFilter Response Response – ContainerResponseFilter, ClientResponseFilter Server-side specialties DynamicFeature
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors A Logging Filter Exampe public class RequestLoggingFilter implements ContainerRequestFilter public void filter(ContainerRequestContext requestContext) { log(requestContext); // non-wrapping => returns without invoking the next filter }... }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors Invoked ONLY when/if entity processing occurs – Performance boost Wrapping interceptors chain – Each interceptor invokes the next one in the chain via context.proceed() Intercept entity providers MessageBodyReader interceptor – ReaderInterceptor interface MessageBodyWriter interceptor – WriterInterceptor interface
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors A Gzip Reader Interceptor Example public class GzipInterceptor implements ReaderInterceptor Object aroundReadFrom(ReaderInterceptorContext ctx) { InputStream old = ctx.getInputStream(); ctx.setInputStream(new GZIPInputStream(old)); // wrapping => invokes the next interceptor Object entity = ctx.proceed(); ctx.setInputStream(old); return entity; }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors Application Request Filter Network Transport … … Response Filter write(…) Writer Interceptor … MBW read(…) - optional … MBR Writer Interceptor Reader Interceptor Reader Interceptor
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Filters & Interceptors Response Application Filter Network … Response Filter write(…) … MBW Writer Interceptor Writer Interceptor Filter … Request read(…) - optional Reader Interceptor … MBR Reader Interceptor Filter Resource
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Bindings & Priorities Binding – Associating filters and interceptors with resource methods – Server-side concept Priority – Declaring relative position in the execution chain priority) Shared concept by filters and interceptors Scoped BindingGlobal Binding Dynamic DynamicFeature N/A
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 = RetentionPolicy.RUNTIME) @Priority(USER) public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter { … }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 public class public String String name) { return "Hello " + name; }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide A DynamicFeature Example Server-side only public void SecurityFeature implements DynamicFeature { public boolean configure(ResourceInfo ri, FeatureContext context) { String[] roles = getRolesAllowed(ri); if (roles != null) { context.register(new RolesAllowedFilter(roles)); }... }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX RS 2.0 Hypermedia Support
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Hypermedia Support REST Principles – Identifiers and Links – HATEOAS (Hypermedia As The Engine Of App State) Link types: – Structural Links – Transitional Links
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Hypermedia Support Link: ; rel=ship, ; rel=cancel Transitional Links Structural Links
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Hypermedia Link and LinkBuilder classes – RFC 5988: Web Linking Support for Link in ResponseBuilder and filters – Transitional links (headers) Support for manual structural links – Via Link.JaxbAdapter & Link.JaxbLink Create a resource target from a Link in Client API
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Hypermedia // Producer API (server-side) Link self = Link.fromMethod(MyResource.class, ”handleGet”).build(); Link update = Link.fromMethod(MyResource.class, “handlePost”).rel(”update”).build();... Response res = Response.ok(order).link(" "ship").links(self, update).build();
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Hypermedia Response order = client.target(…).request("application/xml").get(); // Consumer API (client-side) Link shipmentLink = order.getLink(“ship”); if (shipmentLink != null) { Response shipment = client.target(shipmentLink).post(null); … }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX RS 2.0 Server-side Content Negotiation
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Server-side Content Negotiation GET Accept: text/*; q=1 … Path("widgets2") public class "text/html") public Widgets getWidget() {...} }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Server Side Content Negotiation GET Accept: text/*; q=1 … Path("widgets2") public class qs=0.5", "text/html; qs=0.75") public Widgets getWidget() {...} }
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide JAX-RS 2.0 Summary Major New Features – Client API, Filters & Interceptors, Asynchronous Resources, Hypermedia Many minor API improvements and extensions – Bean Validation, Request / Response, URI Builder, String MultivaluedHashMap, GenericType, … DI Integration,, Java EE Security, MVC, high-level client API deferred
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide Additional Resources Read JSR 343 specification at GlassFish 4.0 – – Open Message Queue 5.0 – –
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 54