Con fess 2013-sse-websockets-json-bhakti


Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Con fess 2013-sse-websockets-json-bhakti

  1. 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 131Server Sent Events, Async Servlet,WebSockets and JSON; born to worktogetherBhakti MehtaPrincipal Member of Technical StaffOracleTwitter: @bhakti_mehta
  2. 2. Program Agenda§Introduction§Polling§Server Sent Events (SSE)§WebSockets§JSON-P§JAXRS 2.0§AsyncServlet§Demo§Q&A
  3. 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:
  4. 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. 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. 6. Long Polling§Uses persistent or long-lasting HTTP connection between the serverand the client§If server does not have data holds request open§COMET
  7. 7. Long Polling Drawbacks§Missing error handling§Involves hacks by adding script tags to an infinite iframe§Hard to check the request state
  8. 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. 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. 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 formatdata: My messagenn
  11. 11. Server Sent Events and JSON§Possible to send multiline texts§E.g. Sending JSONdata: {ndata: "name": "John Doe",ndata: "id": 12345ndata: }nn§On client sidesource.addEventListener(message, function(e) {var data = JSON.parse(;//process the data}, false);
  12. 12. Server Sent Events and Reconnection§If the connection drops, the EventSource fires an error event andautomatically tries to reconnect.§The server can also control the timeout before the client tries toreconnect.
  13. 13. Server Sent Events and Jersey 2.0 apis§Client apis in Jersey 2.0Client client = ClientBuilder.newClient();WebTarget webTarget= URI(TARGET_URI)) ;§ EventSource apis in Jersey 2.0EventSource eventSource = new EventSource(webTarget) {@Overridepublic void onEvent(InboundEvent inboundEvent) {//Get the data from the InboundEvent//Process it as needed.}
  14. 14. Best practices for ServerSentEvents§Check that the data in question is of the expected format.§Limit the arriving messages per minute§Check if eventSources origin attribute is the expecteddomain to get the messages fromif (e.origin != {alert(Origin was not;return;
  15. 15. Best practices for ServerSentEvents§Associating an ID with an event●Each event has an unique ID as●EventSource uses the when reconnecting●Server knows how many pushed events the client has missed●Good to resume a failed connection
  16. 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. Processdata. Wait..1 GET = 1 HTTP response header, many chunks of data
  17. 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. 18. WebSockets Client Server Handshake§Client and Server upgrade from Http protocol to WebSocket protocolduring initial handshakeGET /text HTTP/1.1rnUpgrade: WebSocketrnConnection: UpgradernHost: www.websocket.orgrn …rn§Handshake from server looks likeHTTP/1.1 101 WebSocket Protocol HandshakernUpgrade: WebSocketrnConnection: Upgradern …rn
  19. 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 openedsocket.onmessage: When a message has been receivedsocket.onclose: When a socket has been closed§For examplesocket.onmessage = function(msg){alert(msg);}
  20. 20. WebSockets API JSR 356§@ServerEndpointsignifies that the Java class it decorates is to be deployed asa WebSocket endpoint.§The following components can be annotated with @ServerEndpoint●a stateless session EJB●a singleton EJB●a CDI managed bean
  21. 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. 22. WebSockets and security§WebSockets URI starts with ws/wss§Conform to the same security that already exists at container level
  23. 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 XMLworld§Object model API to represent JSON Similar to DOM API in XMLworld
  24. 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. 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. 26. JSON sample data{"firstName": "John", "lastName": "Smith", "age": 25,"phoneNumber": [{ "type": "home", "number": "212 555-1234" },{ "type": "fax", "number": "646 555-4567" }]}]}
  27. 27. JSonParserIterator<Event> it = parser.iterator();Event event =; // START_OBJECTevent =; // KEY_NAMEevent =; // VALUE_STRINGString name = parser.getString(); // "John”
  28. 28. JsonGenerator§JsonGenerator: Generates JSON in a streaming way to outputsources§Similar to StAX’s XMLStreamWriter§Created using :Json.createGenerator(…),Json.createGeneratorFactory(...).createGenerator(…)
  29. 29. 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(); ]
  30. 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. 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. 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. 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. 34. JAXRS 2.0 Client API§Code snippet:Client client = ClientBuilder.newClient();WebTarget webTarget= URI(TARGET_URI)) ;webTarget.request().post(Entity.text(message));
  35. 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 secsctx.resume("Hello async world!");} }); ctx.suspend(); // Suspend connection and return} … }
  36. 36. JAXRS 2.0 and @Suspend annotation@Path("/async/longRunning")public class MyResource {@Context private ExecutionContext ctx;@GET @Produces("text/plain") @Suspendpublic void longRunningOp() {Executors.newSingleThreadExecutor().submit( new Runnable() {public void run() {Thread.sleep(10000); // Sleep 10 secsctx.resume("Hello async world!");} });//ctx.suspend(); // Suspend connection and return} … }
  37. 37. Async Servlet components§Thread Pool and Queue§AsyncContext§Runnable instance§Servlet/Filter chain
  38. 38. DEMO
  39. 39. Demo class diagramGets data fromtwitter searchapisWrites the messageon the EventChannelCreate EventSourceParseJson dataDisplay in servlet
  40. 40. AsyncServlet code sampleprotected 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. 41. AsyncServlet code sampleclass AsyncRequestProcessor implements Runnable {@Overridepublic void run() {Client client = ClienttBuildernewClient();webTarget = URI(TARGET_URI));EventSource eventSource = new EventSource(webTarget, executorService) {public void onEvent(InboundEvent inboundEvent) {try {//get the JSON data and parse it}
  42. 42. Trying the sampleClone the sample from the following repo: 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. 43. 43Questions?