SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131
Server Sent Events, Async Servlet,
WebSockets and JSON; born to work
together
Bhakti Mehta
Principal Member of Technical Staff
Oracle
Twitter: @bhakti_mehta
Program Agenda
§Introduction
§Polling
§Server Sent Events (SSE)
§WebSockets
§JSON-P
§JAXRS 2.0
§AsyncServlet
§Demo
§Q&A
Introduction
§All new or improved in Java EE 7
§GlassFish trunk build is in-progress implementation of EE 7
§All sample codes work on latest GlassFish 4
:http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/
Polling
§Used by vast number of AJAX applications
§Poll the server for data
§Client --->request--> Server
§If no data empty response is returned
Polling Drawbacks
§Http overhead
§Long intervals result in delay in getting the latest data
§Short intervals consume more resources
§Not scalable for many many users in smaller farms
Long Polling
§Uses persistent or long-lasting HTTP connection between the server
and the client
§If server does not have data holds request open
§COMET
Long Polling Drawbacks
§Missing error handling
§Involves hacks by adding script tags to an infinite iframe
§Hard to check the request state
Server Sent Events
§Client subscribe to event source
§Events can be streamed from server to client when happens
§Connection stays open
§Unidirectional channel between server and client
Server Sent Events and EventSource
§Subscribing to event stream (JavaScript way)
• create an EventSource object:
eventSource = new EventSource(url);
source.onmessage = function (event) {
// a message arrived
};
§Event Source is a URL of course.
§Can setup handlers for source.onopen and source.onerror
Server Sent Events and Message format
§Plain text format
§Response Content-Type is text/event-stream
§The content follows the SSE format
§The response should contain a "data:" line, followed by the message,
followed by two "n" characters to end the stream:
§Sample message format
data: My messagenn
Server Sent Events and JSON
§Possible to send multiline texts
§E.g. Sending JSON
data: {n
data: "name": "John Doe",n
data: "id": 12345n
data: }nn
§On client side
source.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
//process the data
}, false);
Server Sent Events and Reconnection
§If the connection drops, the EventSource fires an error event and
automatically tries to reconnect.
§The server can also control the timeout before the client tries to
reconnect.
Server Sent Events and Jersey 2.0 apis
§Client apis in Jersey 2.0
Client client = ClientBuilder.newClient();
WebTarget webTarget= client.target(new URI(TARGET_URI)) ;
§ EventSource apis in Jersey 2.0
EventSource eventSource = new EventSource(webTarget) {
@Override
public void onEvent(InboundEvent inboundEvent) {
//Get the data from the InboundEvent
//Process it as needed.
}
Best practices for ServerSentEvents
§Check that the data in question is of the expected format.
§Limit the arriving messages per minute
§Check if eventSource's origin attribute is the expected
domain to get the messages from
if (e.origin != 'http://foo.com') {
alert('Origin was not http://foo.com');
return;
Best practices for ServerSentEvents
§Associating an ID with an event
●
Each event has an unique ID as event.id
●
EventSource uses the event.id when reconnecting
●
Server knows how many pushed events the client has missed
●
Good to resume a failed connection
Polling vs Long Polling vs Server Sent Events
§Polling: GET. If data, process data. GET...
1 GET = 1 HTTP response header and maybe a chunk of data.
§Long-polling: GET. Wait. Process data. GET...
1 GET = 1 HTTP response header and chunks of data.
§SSE: Subscribe to event stream. Wait. Process data. Wait. Process
data. Wait..
1 GET = 1 HTTP response header, many chunks of data
WebSockets
§Full duplex communication in either direction
§A component of HTML5
§API under w3c, protocol under IETF(RFC 6455)
§Good support by different browsers
§Use existing infrastructure
WebSockets Client Server Handshake
§Client and Server upgrade from Http protocol to WebSocket protocol
during initial handshake
GET /text HTTP/1.1rn
Upgrade: WebSocketrn
Connection: Upgradern
Host: www.websocket.orgrn …rn
§Handshake from server looks like
HTTP/1.1 101 WebSocket Protocol Handshakern
Upgrade: WebSocketrn
Connection: Upgradern …rn
WebSockets Code Snippet
§After the upgrade HTTP is completely out of the picture.
§Messages are send bidirectional using WebSockets wire protocl
§In JavaScript:
var socket = new WebSocket("ws://localhost:8000/ws/wsst");
socket.onopen: When a socket has opened
socket.onmessage: When a message has been received
socket.onclose: When a socket has been closed
§For example
socket.onmessage = function(msg){
alert(msg);
}
WebSockets API JSR 356
§@ServerEndpoint
signifies that the Java class it decorates is to be deployed as
a WebSocket endpoint.
§The following components can be annotated with @ServerEndpoint
●
a stateless session EJB
●
a singleton EJB
●
a CDI managed bean
WebSockets Annotations
§Decorate methods on @ServerEndpoint annotated Java class with
●
@OnMessage To specify the method processing the message
●
@OnOpen to specify a handler when a connection is opened.
●
@OnClose to specify the handler when connection is closed.
●
@OnError To specify the handler when error happened
WebSockets and security
§WebSockets URI starts with ws/wss
§Conform to the same security that already exists at container level
Java API for Processing JSON (JSON-P)
JSR 353
§Part of Java EE 7
§Streaming API to produce/consume JSON Similar to StAX API in XML
world
§Object model API to represent JSON Similar to DOM API in XML
world
Json Stream parsing API Main classes
§JsonParser: Pull parser
§JsonGenerator: Stream writer
§JsonObject/JsonArray – JSON object and array structure
§JsonString and JsonNumber for string and number value
JsonParser class
§JsonParser: Parses JSON in a streaming way from input sources
§Similar to StAX’s XMLStreamReader, a pull parser
§Parser state events :
START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING,
VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL, END_OBJECT,
END_ARRAY
§Created using :
javax.json.Json.createParser(…),
Json.createParserFactory(...).createParser(…)
JSON sample data
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }]}
]
}
JSonParser
Iterator<Event> it = parser.iterator();
Event event = it.next(); // START_OBJECT
event = it.next(); // KEY_NAME
event = it.next(); // VALUE_STRING
String name = parser.getString(); // "John”
JsonGenerator
§JsonGenerator: Generates JSON in a streaming way to output
sources
§Similar to StAX’s XMLStreamWriter
§Created using :
Json.createGenerator(…),
Json.createGeneratorFactory(...).createGenerator(…)
JsonGenerator
generator.writeStartArray() [
.writeStartObject () {
.write("type", "home”).add("number", "212 555-1234") "type": "home", "number": "212 555-1234"
.writeEnd. }
.writeStartObject() ,{
.write("type", "fax”).add("number", "646 555-4567") "type": "fax", "number": "646 555-4567"
.writeEnd }
.writeend();
generator.close(); ]
Object Model API Main Classes
§JsonBuilder – Builds JsonObject and JsonArray Programmatically
§JsonReader – Reads JsonObject and JsonArray from input source
§JsonWriter – Writes JsonObject and JsonArray to output source
§JsonObject/JsonArray – JSON object and array structure
§JsonString and JsonNumber for string and number value
JsonReader
§Reads JsonObject and JsonArray from input source
§Uses pluggable JsonParser
§Read a json object:
JsonReader reader = new JsonReader(io)
JsonObject obj = reader.readObject();
JsonWriter
§Writes JsonObject and JsonArray to output source
§Uses pluggable JsonGenerator
§Write a json object:
JsonWriter writer = new JsonWriter(io)
writer.writeObject(obj);
JAX-RS 2.0
§New in JAX-RS 2.0
§Client API
§Filters and Interceptors
§Client-side and Server-side Asynchronous
§Improved Connection Negotiation
§Validation Alignment with JSR 330
JAXRS 2.0 Client API
§Code snippet:
Client client = ClientBuilder.newClient();
WebTarget webTarget= client.target(new URI(TARGET_URI)) ;
webTarget.request().post(Entity.text(message));
JAXRS 2.0 and Asynchronous support
@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(); // Suspend connection and return
} … }
JAXRS 2.0 and @Suspend annotation
@Path("/async/longRunning")
public class MyResource {
@Context private ExecutionContext ctx;
@GET @Produces("text/plain") @Suspend
public void longRunningOp() {
Executors.newSingleThreadExecutor().submit( new Runnable() {
public void run() {
Thread.sleep(10000); // Sleep 10 secs
ctx.resume("Hello async world!");
} });
//ctx.suspend(); // Suspend connection and return
} … }
Async Servlet components
§Thread Pool and Queue
§AsyncContext
§Runnable instance
§Servlet/Filter chain
DEMO
Demo class diagram
Gets data from
twitter search
apis
Writes the message
on the EventChannel
Create EventSource
ParseJson data
Display in servlet
AsyncServlet code sample
protected void service(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
final AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(TIMEOUT);
asyncContext.addListener(new AsyncListener() {
// Override the methods for onComplete, onError, onAsyncStartup
}
Thread t = new Thread(new AsyncRequestProcessor(asyncContext));
t.start();
}
AsyncServlet code sample
class AsyncRequestProcessor implements Runnable {
@Override
public void run() {
Client client = ClienttBuildernewClient();
webTarget = client.target(new URI(TARGET_URI));
EventSource eventSource = new EventSource(webTarget, executorService) {
public void onEvent(InboundEvent inboundEvent) {
try {
//get the JSON data and parse it
}
Trying the sample
Clone the sample from the following repo:
https://github.com/kalali/jersey-sse-twitter-sample/
Follow the readme which involves:
●
Do a mvn clean install
●
Get latest GlassFish build
●
Deploy the application
●
Hit the http://localhost:8080/jersey-sse-twitter-sample/TestClient
43
Questions?
Con fess 2013-sse-websockets-json-bhakti

Mais conteúdo relacionado

Mais procurados

Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAXRaveendra R
 
Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters MongoDB
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkitpetertmarks
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Android webservices
Android webservicesAndroid webservices
Android webservicesKrazy Koder
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationMongoDB
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationMicha Kops
 
Welcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDBWelcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDBMongoDB
 
Understanding JavaScript Event-based Interactions
Understanding JavaScript Event-based InteractionsUnderstanding JavaScript Event-based Interactions
Understanding JavaScript Event-based InteractionsSALT Lab @ UBC
 
HeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP ClientHeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP ClientDimitar Ivanov
 
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: Tutorial
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: TutorialMongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: Tutorial
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: TutorialMongoDB
 
High Performance Python Microservice Communication
High Performance Python Microservice CommunicationHigh Performance Python Microservice Communication
High Performance Python Microservice CommunicationJoe Cabrera
 
Json web token api authorization
Json web token api authorizationJson web token api authorization
Json web token api authorizationGiulio De Donato
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code維佋 唐
 
Java web programming
Java web programmingJava web programming
Java web programmingChing Yi Chan
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityIMC Institute
 
Webinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDBWebinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDBMongoDB
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
 

Mais procurados (20)

Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAX
 
Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters Database Trends for Modern Applications: Why the Database You Choose Matters
Database Trends for Modern Applications: Why the Database You Choose Matters
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Android webservices
Android webservicesAndroid webservices
Android webservices
 
Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Welcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDBWelcome the Offical C# Driver for MongoDB
Welcome the Offical C# Driver for MongoDB
 
Understanding JavaScript Event-based Interactions
Understanding JavaScript Event-based InteractionsUnderstanding JavaScript Event-based Interactions
Understanding JavaScript Event-based Interactions
 
HeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP ClientHeadCouch - CouchDB PHP Client
HeadCouch - CouchDB PHP Client
 
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: Tutorial
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: TutorialMongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: Tutorial
MongoDB .local Chicago 2019: Practical Data Modeling for MongoDB: Tutorial
 
High Performance Python Microservice Communication
High Performance Python Microservice CommunicationHigh Performance Python Microservice Communication
High Performance Python Microservice Communication
 
Json web token api authorization
Json web token api authorizationJson web token api authorization
Json web token api authorization
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Java Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application SecurityJava Web Programming [9/9] : Web Application Security
Java Web Programming [9/9] : Web Application Security
 
Webinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDBWebinar: Transitioning from SQL to MongoDB
Webinar: Transitioning from SQL to MongoDB
 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
 

Destaque

Let if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreLet if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreBhakti Mehta
 
Resilience planning and how the empire strikes back
Resilience planning and how the empire strikes backResilience planning and how the empire strikes back
Resilience planning and how the empire strikes backBhakti Mehta
 
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Bhakti Mehta
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsBhakti Mehta
 
Architecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedArchitecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedBhakti Mehta
 
Expect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesExpect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesBhakti Mehta
 

Destaque (9)

Let if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and moreLet if flow: Java 8 Streams puzzles and more
Let if flow: Java 8 Streams puzzles and more
 
Devoxx2017
Devoxx2017Devoxx2017
Devoxx2017
 
Resilience planning and how the empire strikes back
Resilience planning and how the empire strikes backResilience planning and how the empire strikes back
Resilience planning and how the empire strikes back
 
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...Expect the unexpected: Anticipate and prepare for failures in microservices b...
Expect the unexpected: Anticipate and prepare for failures in microservices b...
 
Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
50 tips50minutes
50 tips50minutes50 tips50minutes
50 tips50minutes
 
Architecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learnedArchitecting for Failures in micro services: patterns and lessons learned
Architecting for Failures in micro services: patterns and lessons learned
 
Expect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservicesExpect the unexpected: Prepare for failures in microservices
Expect the unexpected: Prepare for failures in microservices
 
Think async
Think asyncThink async
Think async
 

Semelhante a Con fess 2013-sse-websockets-json-bhakti

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!Masoud Kalali
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2kriszyp
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...Ivanti
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptxitzkuu01
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2Geoffrey Fox
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5Bhakti Mehta
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 

Semelhante a Con fess 2013-sse-websockets-json-bhakti (20)

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!
 
08 ajax
08 ajax08 ajax
08 ajax
 
Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2Java Script Based Client Server Webapps 2
Java Script Based Client Server Webapps 2
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Json
JsonJson
Json
 
CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2CTS Conference Web 2.0 Tutorial Part 2
CTS Conference Web 2.0 Tutorial Part 2
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5
 
Ajax
AjaxAjax
Ajax
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Ajax
AjaxAjax
Ajax
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 

Con fess 2013-sse-websockets-json-bhakti

  • 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131 Server Sent Events, Async Servlet, WebSockets and JSON; born to work together Bhakti Mehta Principal Member of Technical Staff Oracle Twitter: @bhakti_mehta
  • 2. Program Agenda §Introduction §Polling §Server Sent Events (SSE) §WebSockets §JSON-P §JAXRS 2.0 §AsyncServlet §Demo §Q&A
  • 3. Introduction §All new or improved in Java EE 7 §GlassFish trunk build is in-progress implementation of EE 7 §All sample codes work on latest GlassFish 4 :http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/
  • 4. Polling §Used by vast number of AJAX applications §Poll the server for data §Client --->request--> Server §If no data empty response is returned
  • 5. Polling Drawbacks §Http overhead §Long intervals result in delay in getting the latest data §Short intervals consume more resources §Not scalable for many many users in smaller farms
  • 6. Long Polling §Uses persistent or long-lasting HTTP connection between the server and the client §If server does not have data holds request open §COMET
  • 7. Long Polling Drawbacks §Missing error handling §Involves hacks by adding script tags to an infinite iframe §Hard to check the request state
  • 8. Server Sent Events §Client subscribe to event source §Events can be streamed from server to client when happens §Connection stays open §Unidirectional channel between server and client
  • 9. Server Sent Events and EventSource §Subscribing to event stream (JavaScript way) • create an EventSource object: eventSource = new EventSource(url); source.onmessage = function (event) { // a message arrived }; §Event Source is a URL of course. §Can setup handlers for source.onopen and source.onerror
  • 10. Server Sent Events and Message format §Plain text format §Response Content-Type is text/event-stream §The content follows the SSE format §The response should contain a "data:" line, followed by the message, followed by two "n" characters to end the stream: §Sample message format data: My messagenn
  • 11. Server Sent Events and JSON §Possible to send multiline texts §E.g. Sending JSON data: {n data: "name": "John Doe",n data: "id": 12345n data: }nn §On client side source.addEventListener('message', function(e) { var data = JSON.parse(e.data); //process the data }, false);
  • 12. Server Sent Events and Reconnection §If the connection drops, the EventSource fires an error event and automatically tries to reconnect. §The server can also control the timeout before the client tries to reconnect.
  • 13. Server Sent Events and Jersey 2.0 apis §Client apis in Jersey 2.0 Client client = ClientBuilder.newClient(); WebTarget webTarget= client.target(new URI(TARGET_URI)) ; § EventSource apis in Jersey 2.0 EventSource eventSource = new EventSource(webTarget) { @Override public void onEvent(InboundEvent inboundEvent) { //Get the data from the InboundEvent //Process it as needed. }
  • 14. Best practices for ServerSentEvents §Check that the data in question is of the expected format. §Limit the arriving messages per minute §Check if eventSource's origin attribute is the expected domain to get the messages from if (e.origin != 'http://foo.com') { alert('Origin was not http://foo.com'); return;
  • 15. Best practices for ServerSentEvents §Associating an ID with an event ● Each event has an unique ID as event.id ● EventSource uses the event.id when reconnecting ● Server knows how many pushed events the client has missed ● Good to resume a failed connection
  • 16. Polling vs Long Polling vs Server Sent Events §Polling: GET. If data, process data. GET... 1 GET = 1 HTTP response header and maybe a chunk of data. §Long-polling: GET. Wait. Process data. GET... 1 GET = 1 HTTP response header and chunks of data. §SSE: Subscribe to event stream. Wait. Process data. Wait. Process data. Wait.. 1 GET = 1 HTTP response header, many chunks of data
  • 17. WebSockets §Full duplex communication in either direction §A component of HTML5 §API under w3c, protocol under IETF(RFC 6455) §Good support by different browsers §Use existing infrastructure
  • 18. WebSockets Client Server Handshake §Client and Server upgrade from Http protocol to WebSocket protocol during initial handshake GET /text HTTP/1.1rn Upgrade: WebSocketrn Connection: Upgradern Host: www.websocket.orgrn …rn §Handshake from server looks like HTTP/1.1 101 WebSocket Protocol Handshakern Upgrade: WebSocketrn Connection: Upgradern …rn
  • 19. WebSockets Code Snippet §After the upgrade HTTP is completely out of the picture. §Messages are send bidirectional using WebSockets wire protocl §In JavaScript: var socket = new WebSocket("ws://localhost:8000/ws/wsst"); socket.onopen: When a socket has opened socket.onmessage: When a message has been received socket.onclose: When a socket has been closed §For example socket.onmessage = function(msg){ alert(msg); }
  • 20. WebSockets API JSR 356 §@ServerEndpoint signifies that the Java class it decorates is to be deployed as a WebSocket endpoint. §The following components can be annotated with @ServerEndpoint ● a stateless session EJB ● a singleton EJB ● a CDI managed bean
  • 21. WebSockets Annotations §Decorate methods on @ServerEndpoint annotated Java class with ● @OnMessage To specify the method processing the message ● @OnOpen to specify a handler when a connection is opened. ● @OnClose to specify the handler when connection is closed. ● @OnError To specify the handler when error happened
  • 22. WebSockets and security §WebSockets URI starts with ws/wss §Conform to the same security that already exists at container level
  • 23. Java API for Processing JSON (JSON-P) JSR 353 §Part of Java EE 7 §Streaming API to produce/consume JSON Similar to StAX API in XML world §Object model API to represent JSON Similar to DOM API in XML world
  • 24. Json Stream parsing API Main classes §JsonParser: Pull parser §JsonGenerator: Stream writer §JsonObject/JsonArray – JSON object and array structure §JsonString and JsonNumber for string and number value
  • 25. JsonParser class §JsonParser: Parses JSON in a streaming way from input sources §Similar to StAX’s XMLStreamReader, a pull parser §Parser state events : START_ARRAY, START_OBJECT, KEY_NAME, VALUE_STRING, VALUE_NUMBER, VALUE_TRUE, VALUE_FALSE, VALUE_NULL, END_OBJECT, END_ARRAY §Created using : javax.json.Json.createParser(…), Json.createParserFactory(...).createParser(…)
  • 26. JSON sample data { "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" }]} ] }
  • 27. JSonParser Iterator<Event> it = parser.iterator(); Event event = it.next(); // START_OBJECT event = it.next(); // KEY_NAME event = it.next(); // VALUE_STRING String name = parser.getString(); // "John”
  • 28. JsonGenerator §JsonGenerator: Generates JSON in a streaming way to output sources §Similar to StAX’s XMLStreamWriter §Created using : Json.createGenerator(…), Json.createGeneratorFactory(...).createGenerator(…)
  • 29. JsonGenerator generator.writeStartArray() [ .writeStartObject () { .write("type", "home”).add("number", "212 555-1234") "type": "home", "number": "212 555-1234" .writeEnd. } .writeStartObject() ,{ .write("type", "fax”).add("number", "646 555-4567") "type": "fax", "number": "646 555-4567" .writeEnd } .writeend(); generator.close(); ]
  • 30. Object Model API Main Classes §JsonBuilder – Builds JsonObject and JsonArray Programmatically §JsonReader – Reads JsonObject and JsonArray from input source §JsonWriter – Writes JsonObject and JsonArray to output source §JsonObject/JsonArray – JSON object and array structure §JsonString and JsonNumber for string and number value
  • 31. JsonReader §Reads JsonObject and JsonArray from input source §Uses pluggable JsonParser §Read a json object: JsonReader reader = new JsonReader(io) JsonObject obj = reader.readObject();
  • 32. JsonWriter §Writes JsonObject and JsonArray to output source §Uses pluggable JsonGenerator §Write a json object: JsonWriter writer = new JsonWriter(io) writer.writeObject(obj);
  • 33. JAX-RS 2.0 §New in JAX-RS 2.0 §Client API §Filters and Interceptors §Client-side and Server-side Asynchronous §Improved Connection Negotiation §Validation Alignment with JSR 330
  • 34. JAXRS 2.0 Client API §Code snippet: Client client = ClientBuilder.newClient(); WebTarget webTarget= client.target(new URI(TARGET_URI)) ; webTarget.request().post(Entity.text(message));
  • 35. JAXRS 2.0 and Asynchronous support @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(); // Suspend connection and return } … }
  • 36. JAXRS 2.0 and @Suspend annotation @Path("/async/longRunning") public class MyResource { @Context private ExecutionContext ctx; @GET @Produces("text/plain") @Suspend public void longRunningOp() { Executors.newSingleThreadExecutor().submit( new Runnable() { public void run() { Thread.sleep(10000); // Sleep 10 secs ctx.resume("Hello async world!"); } }); //ctx.suspend(); // Suspend connection and return } … }
  • 37. Async Servlet components §Thread Pool and Queue §AsyncContext §Runnable instance §Servlet/Filter chain
  • 38. DEMO
  • 39. Demo class diagram Gets data from twitter search apis Writes the message on the EventChannel Create EventSource ParseJson data Display in servlet
  • 40. AsyncServlet code sample protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(TIMEOUT); asyncContext.addListener(new AsyncListener() { // Override the methods for onComplete, onError, onAsyncStartup } Thread t = new Thread(new AsyncRequestProcessor(asyncContext)); t.start(); }
  • 41. AsyncServlet code sample class AsyncRequestProcessor implements Runnable { @Override public void run() { Client client = ClienttBuildernewClient(); webTarget = client.target(new URI(TARGET_URI)); EventSource eventSource = new EventSource(webTarget, executorService) { public void onEvent(InboundEvent inboundEvent) { try { //get the JSON data and parse it }
  • 42. Trying the sample Clone the sample from the following repo: https://github.com/kalali/jersey-sse-twitter-sample/ Follow the readme which involves: ● Do a mvn clean install ● Get latest GlassFish build ● Deploy the application ● Hit the http://localhost:8080/jersey-sse-twitter-sample/TestClient