JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London

  • View
    4.757

  • Download
    2

Embed Size (px)

DESCRIPTION

JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London

Text of JAX-RS 2.0: New and Noteworthy in RESTful Web services API at JAX London

  • 1.JAX-RS 2.0: New andNoteworthy in RESTfulWeb Services APIArun GuptaJava EE & GlassFish Guyblogs.oracle.com/arungupta, @arungupta1 Copyright 2012, Oracle and/or its affiliates. All rights reserved.

2. JAX-RS - Java API for RESTful ServicesStandard annotation-driven API POJO-Based Resource Classesthat aims to help developers HTTP Centric Programming Modelbuild RESTful Web services and clients Entity Format Independence in Java Container Independence Included in Java EE2 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 3. Example: JAX-RS APIResources@Path("/atm/{cardId}")URI Parameterpublic class AtmService { Injection@GET @Path("/balance")@Produces("text/plain")public String balance(@PathParam("cardId") String card, @QueryParam("pin") String pin) {return Double.toString(getBalance(card, pin));} HTTP Method Built-in Binding Serialization3 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 4. Example: JAX-RS API (contd.) Custom Serialization @POST @Path("/withdrawal") @Consumes("text/plain") @Produces("application/json") public Money withdraw(@PathParam("card") String card, @QueryParam("pin") String pin, String amount){ return getMoney(card, pin, amount); }}4 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 5. Example: JAX-RS API (contd.)5 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 6. Example: JAX-RS API (contd.)6 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 7. JSR-339 a.k.a. JAX-RS 2.0 Expert Group formed in February, 2011 Lead by Oracle Marek Potociar, Santiago Pericas-Geertsen 13 Group members Jan Algermissen, Florent Benoit (OW2), Sergey Beryozkin (Talend/CXF), Adam Bien, Bill Burke (RedHat), Clinton L Combs, Bill De Hora, Markus Karg, Sastry Mallady (eBay), Wendy Raschke (IBM), Julian Reschke, Guilherme Silveira, Dionysios Synodinos Public Review Draft published on Sep 28, 2012 See JSR-339 JCP site jcp.org/en/jsr/detail?id=3397 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 8. JAX-RS 2.0 Client API Common configuration Asynchronous processing Filters Interceptors Hypermedia support Server-side content negotiation8 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 9. JAX-RS 2.0 Client API Common configuration Asynchronous processing Filters Interceptors Hypermedia support Server-side content negotiation9 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 10. Client APIMotivation HTTP client libraries too low level Leveraging providers and concepts from the JAX-RS 1.x API E.g., MBRs and MBWs Proprietary APIs introduced by major JAX-RS 1.x implementations Need for a standard10 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 11. Client API // Get instance of Client Client client = ClientFactory.newClient(); // Get account balance String bal = client.target("http://.../atm/{cardId}/balance") .resolveTemplate("cardId", "111122223333") .queryParam("pin", "9876") .request("text/plain").get(String.class);11 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 12. Client API // Withdraw some money Money mon = client.target("http://.../atm/{cardId}/withdrawal") .resolveTemplate("cardId", "111122223333") .queryParam("pin", "9876") .request("application/json") .post(text("50.0"), Money.class);12 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 13. Client API Invocation inv1 = client.target("http://.../atm/{cardId}/balance") .request(text/plain).buildGet(); Invocation inv2 = client.target("http://.../atm/{cardId}/withdraw") .request("application/json") .buildPost(text("50.0"));13 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 14. Client API Collection invocations = Arrays.asList(inv1, inv2); Collection responses = Collections.transform( invocations, new F() { public Response apply(Invocation inv) { return inv.invoke(); } });14 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 15. Client API // Create client and register MyProvider1 Client client = ClientFactory.newClient(); client.configuration().register(MyProvider1.class); // Create atm target; inherits MyProvider1 WebTarget atm = client.target("http://.../atm"); // Register MyProvider2 atm.configuration().register(MyProvider2.class); // Create balance target; inherits MyProvider1, MyProvider2 WebTarget balance = atm.path({cardId}/balance"); // Register MyProvider3 balance.configuration().register(MyProvider3.class);15 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 16. JAX-RS 2.0 Client API Common configuration Asynchronous processing Filters Interceptors Hypermedia support Server-side content negotiation16 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 17. Common configuration - motivationClient-side client.configuration() .register(JsonMessageBodyReader.class) .register(JsonMessageBodyWriter.class) .register(JsonpInterceptor.class) .setProperty(jsonp.callback.name, callback) .setProperty(jsonp.callback.queryParam, true) ...17 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 18. Common configuration - motivationServer-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; } }18 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 19. Common configuration - solutionClient-side client.configuration() .register(JsonMessageBodyReader.class) .register(JsonMessageBodyWriter.class) .register(JsonpInterceptor.class) .setProperty(jsonp.callback.name, callback) .setProperty(jsonp.callback.queryParam, true) ... JsonFeature jf = new JsonFeature().enableCallbackQueryParam(); Client.configuration().register(jf);19 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 20. Common configuration - solutionServer-side public Set> getClasses() { classes.add(JsonMessageBodyReader.class); classes.add(JsonMessageBodyWriter.class); classes.add(JsonpInterceptor.class); } public Set> getClasses() { classes.add(JsonFeature.class); }20 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 21. Common configuration public interface Configurable { Map getProperties(); Object getProperty(String name);Configurable setProperties(Map properties);Configurable setProperty(String name, Object value);Collection getFeatures();Set> getProviderClasses();Set getProviderInstances();Configurable register(...);... }21 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 22. Common configuration public interface Feature { boolean configure(Configurable configurable); }22 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 23. A Feature example public void JsonFeature implements Feature { public boolean configure(Configurable config) { config.register(JsonMessageBodyReader.class) .register(JsonMessageBodyWriter.class) .register(JsonpInterceptor.class) .setProperty(CALLBACK_NAME, calbackName) .setProperty(USE_QUERY_PARAM, useQueryParam);return true; } }23 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 24. Dynamic FeatureServer-side only public interface DynamicFeature { void configure(ResourceInfo ri, Configurable configurable); } public interface ResourceInfo { Method getResourceMethod(); Class getResourceClass(); }24 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 25. JAX-RS 2.0 Client API Common configuration Asynchronous processing Filters Interceptors Hypermedia support Server-side content negotiation25 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 26. Async Processing Server API support Off-load I/O container threads Long-running operations Efficient asynchronous event processing Suspend while waiting for an event Resume when event arrives Leverage Servlet 3.x async support (if available) Client API support Asynchronous request invocation API Future, InvocationCallback 26 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 27. Async Processing: Server-side @Path("/async/longRunning") public class MyResource { @GET public void longRunningOp(@Suspended AsyncResponse ar) {ar.setTimeoutHandler(new MyTimoutHandler());ar.setTimeout(15, SECONDS);Executors.newSingleThreadExecutor().submit(new Runnable() {public void run() {ar.resume(result);}}); } }27 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 28. Async 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);publicboolean register(Class callback);publicboolean[] register(Class callback, Class... callbacks);publicboolean register(Object callback);publicboolean[] register(Object callback, Object... callbacks); }28 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 29. Async Processing: Server-side @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Suspended { } public interface TimeoutHandler { void handleTimeout(AsyncResponse asyncResponse); }29 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 30. Async Processing: Server-side public interface ResumeCallback { public void onResume(AsyncResponse resuming, Response response); public void onResume(AsyncResponse resuming, Throwable error); } public interface CompletionCallback { public void onComplete(); public void onError(Throwable throwable); } public interface ConnectionCallback { public void onDisconnect(AsyncResponse disconnected); }30 Copyright 2012, Oracle and/or its affiliates. All r