Click here to load reader

GIDS 2012: JAX-RS 2.0: RESTful Java on Steroids

  • View
    6.369

  • Download
    2

Embed Size (px)

DESCRIPTION

GIDS 2012: JAX-RS 2.0: RESTful Java on Steroids

Text of GIDS 2012: JAX-RS 2.0: RESTful Java on Steroids

  • 1. JAX-RS 2.0: RESTful Java on SteroidsArun Gupta, Java EE & GlassFish Guyhttp://blogs.oracle.com/arungupta, @arungupta 1 Copyright 2011, 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 2011, Oracle and/or its affiliates. All rights reserved. 3. Part I: How we got here ?3 Copyright 2011, 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 2011, 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 2011, 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 2011, 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 2011, 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 2011, Oracle and/or its affiliates. All rights reserved. 9. Requested Features Filters/Handlers Client APIHypermediaAsyncJSR 330 ValidationImproved ConnegMVC9 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 10. 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 2 published on Feb 9, 2012!10 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 11. Part II: Where We Are Going11 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 12. New in JAX-RS 2.0 Filters/HandlersClient API Hypermedia AsyncJSR 330 Validation ImprovedConnegMVC12 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 13. New in JAX-RS 2.0 InterceptorsClient API/Handlers Hypermedia AsyncJSR 330Validation ImprovedConneg13 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 14. 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 standard14 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 15. Client APIResource TargetClient FactoryClientatmConfiguration Resource Target ConfigurationConfiguration {cardId}Resource Target Resource TargetInvocationRequest Builderbalance withdrawalResponse15 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 16. 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("text/plain").get(String.class);16 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 17. 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);17 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 18. Example: Generic Interface (Command pattern, Batch processing)Invocation inv1 = client.target("http://.../atm/balance").request(text/plain).buildGet();Invocation inv2 = client.target("http://.../atm/withdraw").request("application/json").buildPost(text("50.0"));18 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 19. 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(); }});19 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 20. Example: Configuration// Get client and register MyProvider1Client client = ClientFactory.newClient();client.configuration().register(MyProvider1.class);// Create atm and register MyProvider2// Inherits MyProvider1 from clientTarget atm = client.target("http://.../atm");atm.configuration().register(MyProvider2.class);// Create balance and register MyProvider3// Inherits MyProvider1, MyProvider2 from atmTarget balance = atm.path("balance");// new instancebalance.configuration().register(MyProvider3.class);20 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 21. New in JAX-RS 2.0 InterceptorsClient API/Handlers Hypermedia AsyncJSR 330 Validation ImprovedConneg21 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 22. 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 semantics22 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 23. 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.STOP23 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 24. Filter Example: [email protected] LoggingFilter implements RequestFilter, ResponseFilter {@Overridepublic FilterAction preFilter(FilterContext ctx) throws IOException { logRequest(ctx.getRequest()); return FilterAction.NEXT;}24 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 25. Filter Example: LoggingFilter (contd.)@Override public FilterAction postFilter(FilterContext ctx) throws IOException { logResponse(ctx.getResponse()); return FilterAction.NEXT; } } 25 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 26. Interceptors Wrapping extension points ReadFrom: Interface ReaderInterceptor WriteTo: Interface WriterInterceptor Part of a interceptor chain Call the next handler directly Each handler decides to proceed or break chain By calling ctx.proceed()26 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 27. 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(); } } 27 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 28. Order of executionRequest WriteTo RequestReadFrom Filter HandlerFilter Handler ReadFromResponse WriteToResponseHandlerFilter HandlerFilterClientServer28 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 29. Binding Associating filters and handlers with resource methods Same mechanism for filters and handlersName Binding Global [email protected]/ StaticDEFAULT @Qualifier?DynamicBinding DynamicBindingDynamic interfaceInterface29 Copyright 2011, 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 2011, 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 2011, Oracle and/or its affiliates. All rights reserved. 32. New in JAX-RS 2.0 Filters/HandlersClient API Hypermedia AsyncJSR 330 Validation ImprovedConneg32 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 33. Motivation Services must validate data Bean Validation already provides the mechanism Integration into JAX-RS Support for constraint annotations in: Fields and properties Parameters (including request entity) Methods (response entities) Resource classes33 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 34. Example: Constraint Annotations @Path("/") class MyResourceClass { @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED)Built-in public void registerUser( @NotNull @FormParam("firstName") String fn,Custom @NotNull @FormParam("lastName") String ln, @Email @FormParam("email") String em) { ... } } 34 Copyright 2011, Oracle and/or its affiliates. All rights reserved. 35. Example: User defined Constraints @Target({ METHOD, FIELD, PARAMETER }) @Retention(RUNTIME) @Constraint(validatedBy = Ema

Search related