Click here to load reader

JAX-RS 2.0: RESTful Web Services

  • View
    4.710

  • Download
    0

Embed Size (px)

DESCRIPTION

JAX-RS 2.0 presentation at IndicThreads

Text of JAX-RS 2.0: RESTful Web Services

  • 1. JAX-RS 2.0: RESTful Java on SteroidsArun Gupta, Java EE & GlassFish Guyhttp://blogs.oracle.com/arungupta, @arungupta 1 Copyright 2012, Oracle and/or its affiliates. All rights reserved.

2. The following is intended to outline our general product direction. It isintended for information purposes only, and may not be incorporated intoany contract. It is not a commitment to deliver any material, code, orfunctionality, and should not be relied upon in making purchasingdecisions. The development, release, and timing of any features orfunctionality described for Oracle s products remains at the sole discretionof Oracle.2 Copyright 2012, Oracle and/or its affiliates. All rights reserved.2011, 3. Part I: How we got here ?3 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 4. How We Got Here? Shortest intro to JAX-RS 1.0 Requested features for JAX-RS 2.0 JSR 339: JAX-RS 2.04 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 5. JAX-RS Origins JAX-RS 1.0 is Java API for RESTful WS RESTFul Principles: Assign everything an ID Link things together Use common set of methods Allow multiple representations Stateless communications5 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 6. JAX-RS 1.0 Goals POJO-Based API HTTP Centric Format Independence Container Independence Inclusion in Java EE6 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 7. Example: JAX-RS API [email protected]("/atm/{cardId}")URI Parameterpublic class AtmService { [email protected] @Path("/balance")@Produces("text/plain")public String balance(@PathParam("cardId") String card, @QueryParam("pin") String pin) {return Double.toString(getBalance(card, pin));} HTTP MethodBuilt-in BindingSerialization 7 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 8. Example: JAX-RS API (contd.) Custom [email protected] @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);}}8 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 9. Example: JAX-RS API (contd.)9 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 10. Example: JAX-RS API (contd.)10 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 11. Requested Features Client API Client-side and Server-side Asynchronous Filters and Interceptors Improved Connection Negotiation Validation Hypermedia Alignment with JSR 330 Model-View-Controller11 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 12. JSR 339 Expert Group EG Formed in March 2011 Oracle Leads: Marek Potociar / Santiago Pericas-G. Expert Group: Jan Algermissen, Florent Benoit, Sergey Beryozkin (Talend),Adam Bien, Bill Burke (RedHat), Clinton Combs, Bill De Hora,Markus Karg, Sastry Malladi (Ebay), Julian Reschke, GuilhermeSilveira, Dionysios Synodinos Early Draft 3 published on Jun 7, 2012!12 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 13. Part II: Where We Are Going13 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 14. In-Scope Features Client API Filters and Interceptors Client-side and Server-side Asynchronous Improved Connection Negotiation Validation Hypermedia Alignment with JSR 330 Model-View-Controller14 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 15. New in JAX-RS 2.0 Client API Filters and Interceptors Client-side and Server-side Asynchronous Improved Connection Negotiation Validation Hypermedia Alignment with JSR 33015 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 16. Client API - Motivation HTTP client libraries too low level Sharing features with JAX-RS server API E.g., MBRs and MBWs Supported by some JAX-RS 1.0 implementations Need for a standard16 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 17. Client API Old and New Client-side API URL url = new URL("http://.../atm/balance"); HttpURLConnection conn = (HttpURLConnection) url.openConnection();Old conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(false); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { out.println(line); }# Client client = ClientFactory.newClient();# String balance = client.target("http://.../atm/balance")#.request()#.get(String.class);#New17 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 18. Example: Client API// Get instance of ClientClient client = ClientFactory.newClient();Can also inject @URI for the target // Get account balanceString bal = client.target("http://.../atm/balance").pathParam("card", "111122223333").queryParam("pin", "9876") .request().get(String.class);18 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 19. Example: Client API (contd.)// Withdraw some moneyMoney mon = client.target("http://.../atm/withdraw").pathParam("card", "111122223333").queryParam("pin", "9876").request("application/json").post(text("50.0"), Money.class);19 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 20. Example: Generic Interface (Command pattern, Batch processing)Invocation inv1 = client.target("http://.../atm/balance").request().buildGet();Invocation inv2 = client.target("http://.../atm/withdraw").request().buildPost(text("50.0"));20 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 21. Example: Generic Interface (contd.)Collection invs = Arrays.asList(inv1, inv2);Collection ress = Collections.transform(invs, new F() {public Response apply(Invocation inv) { return inv.invoke(); }});21 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 22. New in JAX-RS 2.0 Client API Filters and Interceptors Client-side and Server-side Asynchronous Improved Connection Negotiation Validation Hypermedia Alignment with JSR 33022 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 23. Filters & Interceptors Motivation Customize JAX-RS implementations via well-definedextension points Use Cases: Logging, Compression, Security, Etc. Shared by client and server APIs Supported by most JAX-RS 1.0 implementations All using slightly different types or semantics23 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 24. Filters Non-wrapping extension points Pre: Interface RequestFilter Post: Interface ResponseFilter Part of a filter chain Do not call the next filter directly Each filter decides to proceed or break chain By returning FilterAction.NEXT or FilterAction.STOP24 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 25. Filter Example: [email protected] LoggingFilter implements RequestFilter, ResponseFilter {@Overridepublic FilterAction preFilter(FilterContext ctx) throws IOException { logRequest(ctx.getRequest()); return FilterAction.NEXT;}25 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 26. Filter Example: LoggingFilter (contd.)@Override public FilterAction postFilter(FilterContext ctx) throws IOException { logResponse(ctx.getResponse()); return FilterAction.NEXT; } } 26 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 27. Interceptors Wrapping extension points ReadFrom: Interface ReaderInterceptor WriteTo: Interface WriterInterceptor Part of an interceptor chain Call the next handler directly Each handler decides to proceed or break chain By calling ctx.proceed()27 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 28. Handler Example: [email protected] GzipInterceptor implements ReaderInterceptor,WriterInterceptor { @Override public Object aroundReadFrom(ReadInterceptorContext ctx) throws IOException { if (gzipEncoded(ctx)) { InputStream old = ctx.getInputStream(); ctx.setInputStream(new GZIPInputStream(old)); } return ctx.proceed(); } } 28 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 29. Order of ExecutionRequest WriteTo RequestReadFrom Filter HandlerFilter Handler ReadFromResponse WriteToResponseHandlerFilter HandlerFilterClientServer29 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 30. Binding Example: LoggingFilter! @NameBinding // or @Qualifier ? @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface Logged { } @Provider @Logged public class LoggingFilter implements RequestFilter, ResponseFilter { } 30 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 31. Binding Example: LoggingFilter! @Path("/") public class MyResourceClass { @Logged @GET @Produces("text/plain") @Path("{name}") public String hello(@PathParam("name") String name) { return "Hello " + name; } } 31 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 32. New in JAX-RS 2.0 Client API Filters and Interceptors Client-side and Server-side Asynchronous Improved Connection Negotiation Validation Hypermedia Alignment with JSR 33032 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 33. Asynchronous Motivation Let borrowed threads run free! Container environment Suspend and resume connections Suspend while waiting for an event Resume when event arrives Leverage Servlet 3.X async support (if available) Client API support Future, InvocationCallback33 Copyright 2012, Oracle and/or its affiliates. All rights reserved. 34. Example: Suspend and Resume @Path("/async/longRunning") public class MyResource { @Context private ExecutionContext ctx; @GET @Produces("text/plain") public void longRunningOp() { Executors.newSingleThreadExecutor().submit( new Runnable() { public void run() { Thread.sleep(10000); // Sleep 10 secs ctx.resume("Hello async world!"); } }); ctx.suspend(); // Suspe

Search related