• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
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!

on

  • 4,370 views

This session focuses on how Java EE 7 provides extensive set of new and enhanced features to support standards like HTML5, WebSockets, and Server Sent Events among others.In this session we will show ...

This session focuses on how Java EE 7 provides extensive set of new and enhanced features to support standards like HTML5, WebSockets, and Server Sent Events among others.In this session we will show how these new features are designed and matched to work together for developing lightweight solutions matching end users high expectation from a web application’s responsiveness. The session will cover best practices and design patterns governing application development using JAX-RS 2.0, Async Servlet, and JSON-P (among others) as well as iterating over the pitfalls that should be avoided. During the session we will show code snippets and block diagrams that clarify use of APIs coming from the demo application we will show at the end.

Statistics

Views

Total Views
4,370
Views on SlideShare
4,366
Embed Views
4

Actions

Likes
0
Downloads
56
Comments
0

2 Embeds 4

https://twitter.com 3
https://twimg0-a.akamaihd.net 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    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! Presentation Transcript

    • Server Sent Events, Async Servlet,WebSockets and JSON; born toworkMasoud Kalali: Principal Software Bhakti Mehta: Principal Member of TechnicalEngineer at ORACLE Staff at ORACLEBlog: Http://kalali.me Blog: http://www.java.net/blogs/bhaktimehtaTwitter: @MasoudKalali Twitter: @bhakti_mehta 1Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
    • Program Agenda § Introduction § Polling § Server Sent Events (SSE) § WebSockets § JSON-P § JAXRS 2.0 § AsyncServlet § Demo § Q&ACopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Polling § Used by vast majority of AJAX applications § Poll the server for data § Client --->request--> Server § If no data empty response is returnedCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Polling Drawbacks § Http overhead § Reducing the interval will consume more bandwidth and processing resources.Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Long Polling § Uses persistent or long-lasting HTTP connection between the server and the client § If server does not have data holds request open § COMETCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Long Polling Drawbacks § Missing error handling § Involves hacks by adding script tags to an infinite iframe § Hard to check the state of requestCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 happenCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 dataCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Server Sent Events and EventSource § Subscribing to event stream To 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:Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 messagennCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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": 12345n data: }nn § On client side source.addEventListener(message, function(e) { var data = JSON.parse(e.data);Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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.Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Best practices for ServerSentEvents § Check if eventSources 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;Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 computationsCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Best practices for ServerSentEvents § Associating an ID with an event Setting 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.Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 infrastructureCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 …rnCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 onerrorCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • WebSockets API JSR 356 § @WebSocketEndpoint signifies 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 beanCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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.Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • WebSockets and security § WebSockets URI starts with ws/wss § Conform to the same security that already exists at container levelCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 worldCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • JsonParser § 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 : Json.createParser(…), Json.createParserFactory(...).createParser(…)Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • JSON sample data { "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" }]} ] }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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”Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • JsonGenerator § JsonGenerator – Generates JSON in a streaming way to output sources § Similar to StAX’s XMLStreamWriter § Created using : Json.createGenerator(…), Json.createGeneratorFactory(...).createGenerator(…)Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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(); ]Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 sourceCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • JsonReader§ Reads JsonObject and JsonArray from input source§ Uses pluggable JsonParser try (JsonReader reader = new JsonReader(io)) { JsonObject obj = reader.readObject(); }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • JsonWriter§ Writes JsonObject and JsonArray to output source§ Uses pluggable JsonGenerator // Writes a JSON object try (JsonWriter writer = new JsonWriter(io)) { writer.writeObject(obj); }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 330Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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));Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 }…} Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 }…}Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Async Servlet components § Thread Pool and Queue § AsyncContext § Runnable instance § Servlet/Filter chainCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • DEMOCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Demo class diagram Create EventSource ParseJson data Display in servlet Writes the message Gets data from on the EventChanneltwitter search apis Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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(); }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 }Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • Trying the sampleClone 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 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 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 PMCopyright © 2012, Oracle and/or its affiliates. All rights reserved.
    • 43Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13