Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!

download Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!

If you can't read please download the document

Transcript of Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!

Server Sent Events, Async Servlet, WebSockets and JSON; born to work

Masoud Kalali: Principal Software Engineer at ORACLEBlog: Http://kalali.meTwitter: @MasoudKalali

Bhakti Mehta: Principal Member of Technical Staff at ORACLEBlog: http://www.java.net/blogs/bhaktimehtaTwitter: @bhakti_mehta

Program Agenda

Introduction

Polling

Server Sent Events (SSE)

WebSockets

JSON-P

JAXRS 2.0

AsyncServlet

Demo

Q&A

Polling

Used by vast majority of AJAX applications

Poll the server for data

Client --->request--> Server

If no data empty response is returned

Polling Drawbacks

Http overhead

Reducing the interval will consume morebandwidth and processing resources.

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 state of request

Server Sent Events

Unidirectional channel between server and client

Server pushes data to your app when it wants

No need to make initial request

Updates can be streamed froms server to client as they happen

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

Server Sent Events and EventSource

Subscribing to event streamTo subscribe to an event stream, create an EventSource object and pass it the URL of your stream:

Example in javascript eventSource = new EventSource(url); eventSource.onmessage = function (event) { }

Setting up handlers for events You can optionally listen for onopen and onerror:

Server Sent Events and Message format

Sending an event stream

Construct a plaintext response, served with a text/event-stream Content-Type, that follows the SSE format.

The response should contain a "data:" line, followed by your message, followed by two "\n" characters to end the stream:

Sample message format

data: My message\n\n

Server Sent Events and JSON

Sending JSON You can send multiple lines without breaking JSON format by sending messages like this

data: {\n data: "name": "John Doe",\n data: "id": 12345\n data: }\n\n

On client side source.addEventListener('message', function(e) { var data = JSON.parse(e.data);

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 = ClientFactory.newClient(); WebTarget webTarget= client.target(new URI(TARGET_URI)) ; EventSource apis in Jersey 2.0

EventSource eventSource = new EventSource(webTarget, executorService) { @Override public void onEvent(InboundEvent inboundEvent) { // get the data from the InboundEvent }

Best practices for ServerSentEvents

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

Check that the data in question is of the expected format..

Only accept a certain number of messages per minute to avoid DOS

This will avoid cases where attackers can send high volume of messages and receiving page does expensive computations

Best practices for ServerSentEvents

Associating an ID with an eventSetting an ID lets the browser keep track of the last event fired Incase connection is dropped a special Last-Event-ID is set with new request

This lets the browser determine which event is appropriate to fire. The message event contains a e.lastEventId property.

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.1\r\n Upgrade: WebSocket\r\n Connection: Upgrade\r\n Host: www.websocket.org\r\n \r\nHandshake from server looks like

HTTP/1.1 101 WebSocket Protocol Handshake\r\n Upgrade: WebSocket\r\n Connection: Upgrade\r\n \r\n

WebSockets Code Snippet

After the upgrade HTTP is completely out of the picture at this point.

Using the lightweight WebSocket wire protocol, messages can now be sent or received by either endpoint at any time.

Creating a Websocket ws = new WebSocket("ws://localhost:8080/../WebSocketChat");

You can set handlers for events onopen or onerror

WebSockets API JSR 356

@WebSocketEndpointsignies that the Java class it decorates is to be deployed as a WebSocket endpoint.

Additionally the following components can be annotated with @WebServiceEndpoint a stateless session EJB

a singleton EJB

a CDI managed bean

WebSockets Annotations

Decorate methods on @WebSocketEndpoint annotated Java class with@WebSocketOpen to specify when the resulting endpoint receives a new connection

@WebSocketClose to specify when the connection is closed.

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

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

JsonParser

JsonParser Parses JSON in a streaming way from input sources

Similar to StAXs 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_ARRAYCreated using :

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 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 StAXs XMLStreamWriter

Created using :

Json.createGenerator(), Json.createGeneratorFactory(...).createGenerator()

JsonGenerator

JsonArray address= Json.createGenerator().beginArray() [ .beginObject() { .add("type", "home).add("number", "212 555-1234") "type": "home", "number": "212 555-1234" .endObject() } .beginObject() ,{ .add("type", "fax).add("number", "646 555-4567") "type": "fax", "number": "646 555-4567" .endObject() } .endArray(); ]

Object Model API

JsonObject/JsonArray JSON object and array structure

JsonString and JsonNumber for string and number value

JsonBuilder Builds JsonObject and JsonArray Programmatically

JsonReader Reads JsonObject and JsonArray from input source

JsonWriter Writes JsonObject and JsonArray to output source

JsonReader

Reads JsonObject and JsonArray from input source

Uses pluggable JsonParser

try (JsonReader reader = new JsonReader(io)) { JsonObject obj = reader.readObject(); }

JsonWriter

Writes JsonObject and JsonArray to output source

Uses pluggable JsonGenerator

// Writes a JSON object try (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 = ClientFactory.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 EventChannelCreate EventSourceParseJson dataDisplay 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 = ClientFactory.newClient(); 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

Related sessions at JavaOne

HOL4461: Developing JAX-RS Web Applications Utilizing Server-Sent Events and WebSocket Tuesday, Oct 2, 4:30 PM - 6:30 PM

CON4435: JAX-RS 2.0: New and Noteworthy in the RESTful Web Services API Tuesday, Oct 2, 1:00 PM - 2:00 PM

CON3566: JSR 353: Java API for JSON Processing Wednesday, Oct 3, 10:00 AM - 11:00 AM

CON7001: HTML5 WebSocket and Java Wednesday, Oct 3, 4:30 PM - 5:30 PM

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the title text formatClick to edit title

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the title text formatClick to edit Master title style

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Click to edit the title text formatClick to edit Master title style

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Second level

Third level

Fourth level

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the title text formatClick to edit text

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the title text formatClick to edit text

Insert Picture Here

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelCLICK TO EDIT
MASTER TEXT

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Click to edit the title text formatClick to edit Master title style

Insert Picture Here

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Insert Picture HereClick to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelMaster Text

Click to edit the title text formatClick to edit Master title style

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit Master text styles

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit name

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit title

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Insert Information Protection Policy Classification from Slide 13

Click to edit the outline text formatSecond Outline LevelThird Outline LevelFourth Outline LevelFifth Outline LevelSixth Outline LevelSeventh Outline LevelEighth Outline Level

Ninth Outline LevelClick to edit master text

Insert Chart HereClick to edit the title text formatClick to edit Master title style