Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JAX-RS 2.1 Reloaded

1,168 views

Published on

JAX-RS 2.1 update
Presented at JPrime (Sofia May 2017)

Published in: Software
  • Be the first to comment

JAX-RS 2.1 Reloaded

  1. 1. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | David Delabassee @delabassee Oracle May 2017 JAX-RS 2.1 Reloaded
  2. 2. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS •  Standard based RESTful framework – JAX-RS 2.0 – JSR 339 (*) – JAX-RS 2.1 – JSR 370 – Jersey, JBoss RESTEasy, Restlet, Apache CXF, Apache Wink, IBM JAX-RS, … •  Java SE and Java EE 2 Java API for RESTful Web Services
  3. 3. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 3
  4. 4. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Safe Harbor Statement The following is intended to outline our general product direc[on. It is intended for informa[on purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or func[onality, and should not be relied upon in making purchasing decisions. The development, release, and [ming of any features or func[onality described for Oracle’s products remains at the sole discre[on of Oracle. 4
  5. 5. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Client-side Confiden[al – Oracle Internal/Restricted/Highly Restricted 5
  6. 6. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  Fluent API – Client Builder è Client è WebTarget è … è Request building è Response •  Client – Client side container – Customizable •  Keystore, sslContext, Timeout, etc. •  Set executor service (2.1) – ClientBuilder.executorService(…); javax.ws.rs.client.Client interface 6
  7. 7. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  WebTarget – Target remote URI – Build from a client – path() + resolveTemplates(), queryParam(), matrixParam(), … •  Request invoca[on builder – Build from a WebTarget – acceptXXX(), cookie(), header(), cacheControl(), … – HTTP methods javax.ws.rs.client.Client interface 7
  8. 8. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  Client Instance è WebTarget è Request Invoca[on javax.ws.rs.client.Client interface 8 Client client = ClientBuilder.newClient(); List<Forecast> forecast = client.target("http://weath.er/cities") .accept("application/json") .header("Foo","bar") .get(new GenericType<List<Forecast>>() {});
  9. 9. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  Synchronous invoker •  Asynchronous invoker 9 String city = client.target("http://locati.on/api") .queryParam("city", "Paris") .request() .get(String.class); Future<String> future = client.target("http://locati.on/api") … .request() .async() .get(String.class);
  10. 10. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API Asynchronous invoca:on 10 Future<String> future = client.target("http://locati.on/api") … .request() .async() .get(String.class); String city = future.get();
  11. 11. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API Asynchronous invoca:on 11 Future<String> future = client.target("http://locati.on/api") … .request() .async() .get(String.class); try { String city = future.get(5, TimeUnit.SECONDS); } catch( TimeoutException timeout ) { … }
  12. 12. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API Asynchronous invoca:on 12 Future<String> future = client.target("http://locati.on/api") … .request() .async() .get(String.class); while ( !future.isDone() ) { // response hasn't been received yet … } String city = f.get(); … // Set ClientProperties.CONNECT_TIMEOUT & READ_TIMEOUT
  13. 13. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  Invoca[onCallback Interface – javax.ws.rs.client.Invoca[onCallback<RESPONSE> •  Will receive the asynchronous processing events from an invoca[on – completed(RESPONSE response) – failed(Throwable throwable) 13 Asynchronous invoca:on
  14. 14. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API 14 Invoca:onCallback … WebTarget myResource = client.target("http://examp.le/api/read"); Future<Customer> future = myResource.request(MediaType.TEXT_PLAIN) .async() .get(new InvocationCallback<Customer>() { @Override public void completed (Customer customer) { // do something with the given customer } @Override public void failed (Throwable throwable) { // Oops! } });
  15. 15. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 15 The Travel Service
  16. 16. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 16 The Travel Service destination.path("recommendedDestinations").request() .header("Rx-User", "...") .async() .get(new InvocationCallback<List<Destination>>() { @Override public void completed(final List<Destination> recommended) { final CountDownLatch innerLatch = new CountDownLatch(recommended.size()); final Map<String, Forecast> forecasts = Collections.synchronizedMap(new HashMap<>()); for (final Destination dest : recommended) { forecast.resolveTemplate("dest", dest.getDestination()).request() .async() .get(new InvocationCallback<Forecast>() { @Override public void completed(final Forecast forecast) { forecasts.put(dest.getDestination(), forecast); innerLatch.countDown(); }
  17. 17. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 17 JAX-RS 2.0 @Override public void failed(final Throwable throwable) { innerLatch.countDown(); } }); } try { if (!innerLatch.await(10, TimeUnit.SECONDS)) { // timeout } } catch (final InterruptedException e) { // Ooops, interrupted! } // Continue with processing… } @Override public void failed(final Throwable throwable) { // Recommendation error } });
  18. 18. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 18 JAX-RS 2.1 // JAX-RS 2.1 CompletionStage<Response> csResponse = ClientBuilder.newClient() .target("http://example.com/api") .request() .rx() .get(); Future<Response> fResponse = ClientBuilder.newClient() .target("http://example.com/api") .request() .async() .get(); Response response = ClientBuilder.newClient() .target("http://example.com/api") .request() .get();
  19. 19. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Comple[onStage interface •  “A stage of a possibly asynchronous computa[on, that performs an ac:on or computes a value. On termina[on a stage may in turn trigger other dependent stages.” •  A stage's execu[on may be triggered by comple[on of stage(s) – 1 “then”, 2 “combine” or 1 of 2 “either” •  Does the computa[on takes an argument and returns a result? – “apply” Func[on, “accept” Consumer or “run” Runnable •  ... 19 hrps://docs.oracle.com/javase/8/docs/api/java/u[l/concurrent/Comple[onStage.html
  20. 20. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 20 JAX-RS 2.1 CompletionStage<Number> csp = client.target("price/{destination}") .resolveTemplate("destination", "Paris") .request() .rx() .get(Number.class); CompletionStage<String> csf = client.target("forecast/{destination}") .resolveTemplate("destination", "Paris") .request() .rx() .get(String.class); newCs = cscsp.thenCombine( csf, (price, forecast) -> reserveIfAfforadble(price, forecast) );
  21. 21. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Demo •  The Travel Service 21 hrps://github.com/jersey/jersey/tree/master/examples/rx-client-webapp
  22. 22. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 Reac[ve Client API 22 Sync Async RX Performance and scalability ✗✗ ✔ ✔ Easy to develop and maintain ✔ ✗ ✔ … complex workflow ✗ ✗ ✔ … error handling ✗ ✗ ✔ Leverage new Java SE feature ✗ ✗ ✔
  23. 23. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS Client API •  REST Client Side container •  Synchronous – javax.ws.rs.client.SyncInvoker interface – Default invoker •  Asynchronous – javax.ws.rs.client.AsyncInvoker interface – async() invoker – Might block! – Invoca[onCallback 23 Summary
  24. 24. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 Reac[ve Client API •  New Async Reac[ve invoker – javax.ws.rs.client.RxInvoker interface •  Reac[veInvoker Providers – Java SE 8 Comple[on Stage – Jersey •  RxJava - rx.Observable •  RxJava 2 - io.reac[vex.Flowable •  Guava – ListenableFuture •  ClientBuilder.executorService(…); 24
  25. 25. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Server-side Confiden[al – Oracle Internal/Restricted/Highly Restricted 25
  26. 26. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 26 Server-side @Path("/Item") public class ItemResource { @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public ItemResource getItemResource(@PathParam("id") String id) { return ItemResource.getInstance(id); } @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_JSON) public Response createItem(@QueryParam("name") String name) { //... return Response.status(Status.OK).entity(…).build(); } }
  27. 27. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | 27 Server-side Async @Path("async/longRunning") public class ItemResource { @GET public void longRunningOp(@Suspended AsyncResponse ar) { mes.execute(new Runnable() { @Override public void run() { try { // long running computation... ar.resume(Response.ok(...).build()); } catch (InterruptedException ex) { // Ooops! } } }); ...
  28. 28. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Server-side Async •  Asynchronous response – Provides means for asynchronous server side response processing – Injectable via @Suspended – Bound to the request •  Request processing – Suspend – Resume – Configure – Cancel 28 AsyncResponse interface
  29. 29. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Server-side Async 29 New in 2.1 @Path("/async/longRunning") public class ItemResource { @GET public CompletionStage<String> longRunningOp() { CompletableFuture<String> cs = new CompletableFuture<>(); executor.submit(new Runnable() { public void run() { executeLongRunningOp(); cs.complete("Hello async world!"); } }); return cs; } ... }
  30. 30. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Server-side Async 30 Client Server @Suspended AsyncResponse.resume(…) Long running opera[on… Request Response
  31. 31. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Long running REST opera[ons è POST ... long running opera[on ... ç ‘201 Created’ + Loca[on 31 è POST ç ‘202 Accepted’ + Temp Loca[on è GET Temp Loca[on ç ‘200 OK’ (+ ETA) … è GET Temp Loca[on ç ‘303 See Other’ + Final Loca[on
  32. 32. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Server-sent Events •  Persistent, one-way communica[on channel •  Text protocol, special media type "text/event-stream" •  Server can send mul[ple messages (events) to a client •  Can contain id, name, comment retry interval •  Supported in all modern browsers 32
  33. 33. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 33 SSE •  SseEvent – ID, Name, Comment, … •  OutboundSseEvent – Server-side representa[on of a Server-sent event – OutboundSseEvent.Builder() •  InboundSseEvent – Client-side representa[on of a Server-sent event
  34. 34. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 34 SSE – Server side •  SseEventSink – Outbound Server-Sent Events stream – SseBroadcaster @GET @Path ("sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void eventStream(@Context SseEventSink eventSink, @Context SSE sse) { ... eventSink.send( sse.newEvent("an event") ); eventSink.send( sse.newEvent("another event") ); ... eventSink.close(); }
  35. 35. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 35 SSE – Client side •  SseEventSource – Client for processing incoming Server-Sent Events SseEventSource es = SseEventSource.target(SSE_target) .reconnectingEvery(5, SECONDS) .build(); es.register(System.out::println); // InboundSseEvent consumer es.register(...); // Throwable consumer es.open(); ... es.close();
  36. 36. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Wrap-up Confiden[al – Oracle Internal/Restricted/Highly Restricted 36
  37. 37. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS •  Java API for RESTful Web Services – JAX-RS 2.0 – JSR 339 •  Standard based RESTful framework – Server-side and client-side – Java SE and Java EE – Jersey, JBoss RESTEasy, Restlet, Apache CXF, Apache Wink, IBM JAX-RS, … 37
  38. 38. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | JAX-RS 2.1 – JSR 370 •  Reac[ve Client API •  Server-sent Events support •  JSON-B & JSON-P 1.1 support •  Misc. – Providers ordering – Passing incoming request Locale to BV – Serable Client executor service – Return an instance of Comple[onStage<T> – … hrps://github.com/jax-rs/api/labels/2.1-candidate (tbc) 38 •  Non-blocking IO support •  Make JAXB op[onal
  39. 39. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Java EE 8 39 Bean Valida:on CDI 2.0 JSON-B 1.0 Security 1.0 BV 2.0 JSF 2.3 Servlet 4.0 JSON-P 1.1 JAX-RS 2.1 Reac[ve client API, Server-sent events, … HTTP/2, server push, … Java <-> JSON binding Updates to JSON standards, JSON Collectors, … Async event, event priority, SE support, … Embrace Java SE 8, new constraints Improved CDI, WebSocket, SE 8 integra[on, … Standardized Iden[ty Store, Authen[ca[on, Security Context
  40. 40. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Java EE 8 •  Work in progress – Final Release - Summer 2017 (plan) •  Open Source Reference Implementa[ons – hrps://github.com/javaee – hrps://github.com/jersey •  Contribute! – Adopt A JSR •  Stay tuned… – hrps://blogs.oracle.com/theaquarium/ 40
  41. 41. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Resources •  JAX-RS specifica[on – hrps://github.com/jax-rs/api •  Jersey – hrps://github.com/jersey •  Jersey – Asynchronous Services and Clients – hrps://jersey.github.io/documenta[on/latest/user-guide.html#async •  Comple[onStage Javadoc – hrps://docs.oracle.com/javase/8/docs/api/java/u[l/concurrent/Comple[onStage.html 41
  42. 42. Copyright © 2017, Oracle and/or its affiliates. All rights reserved. | Q&A Confiden[al – Oracle Internal/Restricted/Highly Restricted 42

×