SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
#DevoxxUS
JAX-RS 2.1 Reloaded
Santiago Pericas-Geertsen
JAX-RS Co-Spec Lead
#jax-rs @spericas
#DevoxxUS
Agenda
•  Reactive Extensions
•  Server-Sent Events
•  Non-Blocking IO
#jax-rs @spericas
#DevoxxUS
Reactive Extensions
#jax-rs @spericas
#DevoxxUS
Asynchronous Processing in 2.0
Server side:
•  Using @Suspended and AsyncResponse
•  Resume execution on a different thread
Client side:
•  Future<T>
•  InvocationCallback<T>
4
#DevoxxUS
Example Using Future<T>
5
What’s the
problem
here?
Client client = ClientBuilder.newClient();
WebTarget target = client.target(“http://…”);
Future<String> f =
target.request().async().get(String.class);
// some time later …
String user = f.get();
#DevoxxUS
Example using InvocationCallback<T>
6
WebTarget target = client.target(“http://…”);
target.request().async().get(
new InvocationCallback<String>() {
@Override
public void completed(String user) {
// do something
}
@Override
public void failed(Throwable t) {
// do something
} });
#DevoxxUS
Example using InvocationCallback<T>
7
target1.request().async().get(new
InvocationCallback<String>() {
public void completed(String user) {
target2.request().header(“user”, user).async().get(
new InvocationCallback<String>() {
public void completed(String quote) {
System.out.println(quote);
}
public void failed(Throwable t) {
// do something
}
}); }
public void failed(Throwable t) {
// do something
}}));
#DevoxxUS
Some use cases for Async Computations
•  Compose two or more asynchronous tasks
•  Combine the output of two or more asynchronous tasks
•  Consume value of asynchronous task
•  Wait for all tasks in a collection to complete
•  Wait for any of the tasks in a collection to complete
And many more …
#DevoxxUS
Meet CompletionStage<T> in JAX-RS
9
CompletionStage<String> cs1 =
target1.request().rx().get(String.class);
CompletionStage<String> cs2 =
cs1.thenCompose(user ->
target2.request().header(“user”, user)
.rx().get(String.class));
cs2.thenAccept(quote -> System.out.println(quote));
#DevoxxUS
What about other Rx libraries?
10
Client client =
client.register(ObservableRxInvokerProvider.class);



Observable<String> of = 

client.target("forecast/{destination}”)
.resolveTemplate("destination", "mars”)
.request()
.rx(ObservableRxInvoker.class)
.get(String.class);
of.subscribe(System.out::println);
Register a
Provider
Override
default Invoker
#DevoxxUS
Server-Sent Events Summary
•  New invoker to support Rx
•  Default support for CompletionStage
•  Extension mechanism for other Rx libraries
11
#DevoxxUS
Server-Sent Events
#jax-rs @spericas
#DevoxxUS
Server-Sent Events
•  Originally W3C (HTML5), now maintainted by WHATWG
•  HTTP-based protocol for one-way server to client messaging
•  Special media type text/event-stream
13
#DevoxxUS
Client API
14
try (SseEventSource source =
SseEventSource.target(“http://…”).build()) {
source.subscribe(System.out::println);
source.open();

Thread.sleep(500); 

} catch (InterruptedException e) {

// falls through

}
Publisher
#DevoxxUS
Server API
15
@GET

@Produces(“text/event-stream”)

public void eventStream(
@Context SseEventSink eventSink,

@Context Sse sse) {
executor.execute(() -> {
try (SseEventSink sink = eventSink) {

eventSink.onNext(sse.newEvent("event1"));
eventSink.onNext(sse.newEvent("event2"));
eventSink.close();
} catch (IOException e) {

// handle exception

} });}
Subscriber
#DevoxxUS
Broadcasting (1 of 2)
16
@Path("/")

@Singleton
public class SseResource {
private final Sse sse;
private final SseBroadcaster sseBroadcaster;
public SseResource(@Context Sse sse) {
this.sse = sse;
this.sseBroadcaster = sse.newBroadcaster();
}

…
One Publisher
Lifecycle
controlled by
App
#DevoxxUS
Broadcasting (2 of 2)
17
@GET @Path(“subscribe”)
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context SseEventSink eventSink) {
eventSink.onNext(sse.newEvent("welcome!"));
sseBroadcaster.subscribe(eventSink);
}

@POST @Path(“broadcast”)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void broadcast(@FormParam("event") String event) {

sseBroadcaster.broadcast(sse.newEvent(event));
} … }
Many
Subscribers
#DevoxxUS
Reactive Extensions Summary
•  New types SseEventSink, SseEventSource, Sse and
SseBroadcaster
•  Sse and SseEventSink’s lifecycle controlled by runtime
•  Singleton scope useful for broadcasting
18
#DevoxxUS
Non-Blocking IO
#jax-rs @spericas
#DevoxxUS
Motivation
•  Certain apps need more control over IO
•  Higher throughput is hard with blocking IO
•  Precedence with StreamingOutput
20
#DevoxxUS
StreamingOutput in JAX-RS
21
@GET
public Response get() {
return Response.ok(new StreamingOutput() {
@Override
public void write(OutputStream out) throws … {
out.write(…);
}
}).build();
}
Direct access
to stream
Still blocking!
#DevoxxUS
First NIO Proposal
22
return Response.ok().entity(

out -> {

try {

final int n = in.read(buffer);

if (n >= 0) {

out.write(buffer, 0, n);

return true; // more to write

}

in.close();

return false; // we're done

} catch (IOException e) { … }

}).build();
Write handler
#DevoxxUS
First Proposal Limitations
•  Byte streams are not sufficient in JAX-RS
•  We want POJOs!
•  What about JAX-RS readers, writers and interceptors?
•  Poor integration with other third-party libraries and APIs
23
#DevoxxUS
Current Proposal: Flows
•  Standardized in Java 9
•  Originaly appeared in Reactive Streams
•  Not just bytes, POJOs too
•  Possibility of integration with third-party libraries and APIs
24
#DevoxxUS
Simple Concepts
25
Publisher
Subscriber
Processor
Publisher
Subscriber
0
N
Processor
#DevoxxUS
Why and when to NIO?
•  Non-blocking code tends to be more involved
•  Beneficial for large payloads
•  Large payloads often involve collections
•  In Flow terms, a collection of Pojos is a Publisher<Pojo>
26
#DevoxxUS
Processing a collection
27
@POST
@Consumes(“application/json”)
void process(Publisher<Pojo> pojos,
@Suspended AsyncResponse response) {
pojos.subscribe(new Subscriber<Pojo> {
public onNext(Pojo pojo) {
// process single pojo
}
public onComplete() {
return response.ok().build();
}
…
} }
Asynchronous
by nature
#DevoxxUS
MessageBodyReader for Pojo?
•  MessageBodyReader for Pojo or Publisher<Pojo>?
•  We need a new type of Reader: NioBodyReader
•  Knows how to process a collection of Pojos
•  May use MessageBodyReader for each Pojo
•  (Ditto for MessageBodyWriters …)
28
#DevoxxUS
Pojo Processor in REST
29
@POST
@Consumes(“application/json”)
@Produces(“application/json”)
Publisher<Pojo> process(Publisher<Pojo> pojos,
@Suspended AsyncResponse response) {
Processor<Pojo> pp = new MyProcessor(response);
pojos.subscribe(pp);
return pp;
}
Processors are
publishers!
#DevoxxUS
Third-party Libraries
30
@GET
@Produces(“application/json”)
Publisher<Pojo> process(
@QueryParam(“predicate”) String predicate) {
return DB.get(Pojo.class).filter(predicate);
}
Third-party
Library
#DevoxxUS
What about Filters and Interceptors?
•  Need special support for NIO
•  For example, additional methods and contexts
•  Discussion still ongoing
•  May impact how NioBodyReader/NioBodyWriter are defined
31
#DevoxxUS
And NIO Clients?
•  Will be supported as well
•  Need re-usability of readers and writers for NIO
•  Likely using a new client Invoker
32
#DevoxxUS
NIO Client
33
WebTarget resource = target(“…”).path(“pojos”);
Publisher<Pojo> pojos =
resource.request().nio().get(Pojo.class);
pojos.subscribe(new Subscriber<Pojo> {
public onNext(Pojo pojo) {
// process single pojo
}
…
});
NioBodyReader
#DevoxxUS
Tentative Vocabulary
•  Publisher = Source
•  Subscriber = Sink
•  Does this ring a bell?
34
#DevoxxUS
SSE is a special case of Flow!
•  Where what flows are SSE protocol messages
•  Initial SSE proposal may be impacted
•  Return a Source instead of injecting a Sink
35
#DevoxxUS
Non-Blocking IO Summary
•  Based on Flows
•  New readers/writers for collections
•  Support for Flows without depending on Java 9
•  Support for Pojos, not just byte streams
•  Publisher<Pojo> and Publisher<ByteArray>
36
#DevoxxUS
Public Release In Progress
•  Support for NIO and Flows
•  Some minor changes to SSE possible
•  Stay tuned!
37

Weitere ähnliche Inhalte

Was ist angesagt?

Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
vantinhkhuc
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 

Was ist angesagt? (20)

Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 
Simple REST with Dropwizard
Simple REST with DropwizardSimple REST with Dropwizard
Simple REST with Dropwizard
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Why Play Framework is fast
Why Play Framework is fastWhy Play Framework is fast
Why Play Framework is fast
 
WebLogic in Practice: SSL Configuration
WebLogic in Practice: SSL ConfigurationWebLogic in Practice: SSL Configuration
WebLogic in Practice: SSL Configuration
 
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...
 
Dropwizard Internals
Dropwizard InternalsDropwizard Internals
Dropwizard Internals
 
Spring.io
Spring.ioSpring.io
Spring.io
 
Deployment of WebObjects applications on FreeBSD
Deployment of WebObjects applications on FreeBSDDeployment of WebObjects applications on FreeBSD
Deployment of WebObjects applications on FreeBSD
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
The First Contact with Java EE 7
The First Contact with Java EE 7The First Contact with Java EE 7
The First Contact with Java EE 7
 
Building Reactive Microservices with Vert.x
Building Reactive Microservices with Vert.xBuilding Reactive Microservices with Vert.x
Building Reactive Microservices with Vert.x
 
Microservices in Scala: Play Framework
Microservices in Scala: Play FrameworkMicroservices in Scala: Play Framework
Microservices in Scala: Play Framework
 
Grizzly 20080925 V2
Grizzly 20080925 V2Grizzly 20080925 V2
Grizzly 20080925 V2
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Se lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
Se lancer dans l'aventure microservices avec Spring Cloud - Julien RoySe lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
Se lancer dans l'aventure microservices avec Spring Cloud - Julien Roy
 

Ähnlich wie JAX-RS 2.1 Reloaded @ Devoxx

Ähnlich wie JAX-RS 2.1 Reloaded @ Devoxx (20)

Programming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for AndroidProgramming Sideways: Asynchronous Techniques for Android
Programming Sideways: Asynchronous Techniques for Android
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
Boost Development With Java EE7 On EAP7 (Demitris Andreadis)
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Mutation Testing DevoxxUK 2021
Mutation Testing DevoxxUK 2021Mutation Testing DevoxxUK 2021
Mutation Testing DevoxxUK 2021
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
Rx 101  - Tamir Dresher - Copenhagen .NET User GroupRx 101  - Tamir Dresher - Copenhagen .NET User Group
Rx 101 - Tamir Dresher - Copenhagen .NET User Group
 
Don't Wait! Develop responsive applications with Java EE7 instead
Don't Wait! Develop responsive applications with Java EE7 insteadDon't Wait! Develop responsive applications with Java EE7 instead
Don't Wait! Develop responsive applications with Java EE7 instead
 
Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejs
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019Managing State in React Apps with RxJS by James Wright at FrontCon 2019
Managing State in React Apps with RxJS by James Wright at FrontCon 2019
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Kürzlich hochgeladen (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

JAX-RS 2.1 Reloaded @ Devoxx