con fess 2013-sse-websockets-json-bhakti

Post on 06-Jun-2015

307 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

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

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

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.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

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

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

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 EventSourceParseJson 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 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

}

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?

top related