Con fess 2013-sse-websockets-json-bhakti

44
Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13 1 Server Sent Events, Async Servlet, WebSockets and JSON; born to work together Bhakti Mehta Principal Member of Technical Staff Oracle Twitter: @bhakti_mehta

Transcript of Con fess 2013-sse-websockets-json-bhakti

Page 1: Con fess 2013-sse-websockets-json-bhakti

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 MehtaPrincipal Member of Technical StaffOracleTwitter: @bhakti_mehta

Page 2: Con fess 2013-sse-websockets-json-bhakti

Program Agenda

§Introduction§Polling§Server Sent Events (SSE)§WebSockets§JSON-P§JAXRS 2.0

§AsyncServlet§Demo§Q&A

Page 3: Con fess 2013-sse-websockets-json-bhakti

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/

Page 4: Con fess 2013-sse-websockets-json-bhakti

Polling

§Used by vast number of AJAX applications§Poll the server for data§Client --->request--> Server§If no data empty response is returned

Page 5: Con fess 2013-sse-websockets-json-bhakti

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

Page 6: Con fess 2013-sse-websockets-json-bhakti

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

Page 7: Con fess 2013-sse-websockets-json-bhakti

Long Polling Drawbacks

§Missing error handling§Involves hacks by adding script tags to an infinite iframe§Hard to check the request state

Page 8: Con fess 2013-sse-websockets-json-bhakti

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

Page 9: Con fess 2013-sse-websockets-json-bhakti

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

Page 10: Con fess 2013-sse-websockets-json-bhakti

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 message\n\n

Page 11: Con fess 2013-sse-websockets-json-bhakti

Server Sent Events and JSON

§Possible to send multiline texts§E.g. Sending JSON 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);

//process the data

}, false);

Page 12: Con fess 2013-sse-websockets-json-bhakti

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.

Page 13: Con fess 2013-sse-websockets-json-bhakti

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.

}

Page 14: Con fess 2013-sse-websockets-json-bhakti

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;

Page 15: Con fess 2013-sse-websockets-json-bhakti

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

Page 16: Con fess 2013-sse-websockets-json-bhakti

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

Page 17: Con fess 2013-sse-websockets-json-bhakti

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

Page 18: Con fess 2013-sse-websockets-json-bhakti

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\n

§Handshake from server looks like HTTP/1.1 101 WebSocket Protocol Handshake\r\n

Upgrade: WebSocket\r\n

Connection: Upgrade\r\n …\r\n

Page 19: Con fess 2013-sse-websockets-json-bhakti

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);

}

Page 20: Con fess 2013-sse-websockets-json-bhakti

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

Page 21: Con fess 2013-sse-websockets-json-bhakti

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

Page 22: Con fess 2013-sse-websockets-json-bhakti

WebSockets and security

§WebSockets URI starts with ws/wss §Conform to the same security that already exists at container level

Page 23: Con fess 2013-sse-websockets-json-bhakti

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

Page 24: Con fess 2013-sse-websockets-json-bhakti

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

Page 25: Con fess 2013-sse-websockets-json-bhakti

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(…)

Page 26: Con fess 2013-sse-websockets-json-bhakti

JSON sample data

{

"firstName": "John", "lastName": "Smith", "age": 25,

"phoneNumber": [

{ "type": "home", "number": "212 555-1234" },

{ "type": "fax", "number": "646 555-4567" }]}

]

}

Page 27: Con fess 2013-sse-websockets-json-bhakti

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”

Page 28: Con fess 2013-sse-websockets-json-bhakti

JsonGenerator

§JsonGenerator: Generates JSON in a streaming way to output sources

§Similar to StAX’s XMLStreamWriter§Created using : Json.createGenerator(…),

Json.createGeneratorFactory(...).createGenerator(…)

Page 29: Con fess 2013-sse-websockets-json-bhakti

JsonGeneratorgenerator.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(); ]

Page 30: Con fess 2013-sse-websockets-json-bhakti

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

Page 31: Con fess 2013-sse-websockets-json-bhakti

JsonReader

§Reads JsonObject and JsonArray from input source§Uses pluggable JsonParser§Read a json object:

JsonReader reader = new JsonReader(io)

JsonObject obj = reader.readObject();

Page 32: Con fess 2013-sse-websockets-json-bhakti

JsonWriter

§Writes JsonObject and JsonArray to output source§Uses pluggable JsonGenerator§Write a json object:

JsonWriter writer = new JsonWriter(io)

writer.writeObject(obj);

Page 33: Con fess 2013-sse-websockets-json-bhakti

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

Page 34: Con fess 2013-sse-websockets-json-bhakti

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));

Page 35: Con fess 2013-sse-websockets-json-bhakti

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

} … }

Page 36: Con fess 2013-sse-websockets-json-bhakti

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

} … }

Page 37: Con fess 2013-sse-websockets-json-bhakti

Async Servlet components

§Thread Pool and Queue§AsyncContext§Runnable instance§Servlet/Filter chain

Page 38: Con fess 2013-sse-websockets-json-bhakti

DEMO

Page 39: Con fess 2013-sse-websockets-json-bhakti

Demo class diagram

Gets data from twitter search apis

Writes the message on the EventChannel

Create EventSourceParseJson data

Display in servlet

Page 40: Con fess 2013-sse-websockets-json-bhakti

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();

}

Page 41: Con fess 2013-sse-websockets-json-bhakti

AsyncServlet code sampleclass 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

}

Page 42: Con fess 2013-sse-websockets-json-bhakti

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

Page 43: Con fess 2013-sse-websockets-json-bhakti

43

Questions?

Page 44: Con fess 2013-sse-websockets-json-bhakti