Successfully reported this slideshow.
Fight the empire light weightly with
HTML5, WebSockets, Server-sent
Events and others
Bhakti Mehta
Twitter: @bhakti_mehta
Introduction
• Currently working as a Senior Software Engineer at
Blue Jeans Network. Bluejeans.com
• Worked at Sun Micros...
Fight the empire!
Copyright 2013, Bhakti Mehta all rights reserved
Agenda
 Introduction
 Polling
 Server- sent Events (SSE)
 WebSockets
 JAXRS 2.0
 JSON-P
Copyright 2013, Bhakti Mehta...
Polling
 Used by vast majority of AJAX applications
 Poll the server for data
 Client --->request--> Server
 If no dat...
Polling
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
Response 200 OK: empty
Request ...
Polling Drawbacks
 Http overhead
 Reducing the interval will consume more bandwidth
and processing resources for nothing...
Long Polling
 If server does not have data holds request open
 COMET
 Chunked transfer encoding can be used to send
chu...
Long Polling
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
Response 200 OK: message b...
Long Polling Drawbacks
• One-way communication
• No standard data format or message format when
used in chunked transfer e...
Server-sent events
Copyright 2013, Bhakti Mehta all rights reserved
 Unidirectional channel between server and client
 S...
Server-sent Events
Copyright 2013, Bhakti Mehta all rights reserved
Client Server
Request (client_id)
….
….
….
SSE message...
Server-sent Events
 Subscribing to event stream
To subscribe to an event stream, create an EventSource
object and pass it...
Message format for SSE
 Sending an event stream
 Construct a plaintext response, served with a
text/event-stream Content...
Server-sent Events and
JSON
 Sending JSON
You can send multiple lines without breaking JSON
format by sending messages li...
Associating event names
with SSE
event: order66Issuedn
data: {“issuer” : “Chancellor Palpatine”}nn
event: jedisPurgedn
dat...
Associating ids with SSE
Associating ids with events can help with fault
tolerance in SSE
id: 123 n
data: Battle of droids...
Connection loss and
retries
• Browsers that support SSE can try reconnecting to
the server in case the connection between ...
Server-sent Events and
reconnection
 If the connection drops, the EventSource fires an
error event and automatically trie...
Best practices for Server-
sent Events
 Check if eventSource's origin attribute is the
expected domain to get the message...
Best practices for Server-
sent Events
 Associating an ID with an event
Setting an ID lets the browser keep track of the ...
Comparing Polling vs
Long Polling vs SSE
 Polling: GET. If data, process data. GET...
1 GET = 1 HTTP response header and ...
WebSockets
 Full duplex communication in either direction
 Data is framed with 2 bytes
 In the case of text frames, eac...
WebSockets
 Client and Server upgrade from Http protocol to
WebSocket protocol during initial handshake
GET /text HTTP/1....
WebSockets Handshake
Copyright 2013, Bhakti Mehta all rights reserved
WebSockets
 After the upgrade HTTP is completely out of the
picture at this point.
 Using the lightweight WebSocket wire...
WebSockets JSR 356
 @ServerEndpoint
signifies that the Java class it decorates is to be
deployed as WebSocket endpoint
 A...
WebSockets and Security
 A web socket which is mapped to a given ws://
URI is protected in the deployment descriptor with...
Comparisons
Subject SSE WebSockets Long Polling
Error Handling Built in support Built in support Almost no error
handling ...
Comparisons
Subject SSE WebSockets Long Polling
Implementation
complexity
Easy Requires
websocket
support
Easiest
Browser ...
Best practices for
WebSockets
• Throttling the rate of sending data
• The WebSockets has a bufferedAmount attribute
which ...
Best practices for
WebSockets
• Controlling the maximum size of the message
• Use the maxMessageSize attribute on @OnMessa...
Best practices for
WebSockets
• Use wss protocol with Proxy servers
• Proxy servers may not allow unencrypted Web
Socket t...
Best practices for
WebSockets
Copyright 2013, Bhakti Mehta all rights reserved
Client1
Client2
Client3
RESTful Webservices
• Key principles of REST
• Associating IDs to resources
• Using standard HTTP methods
• Multiple forma...
RESTful WebServices
• GET: The GET request retrieves a representation of a
resource from server to client.
• POST: The POS...
RESTful WebServices
• Safety
o Invoking a method does not change the
resource on server
o GET, HEAD are safe
o PUT, DELETE...
JAX-RS 2.0
Defines how to expose POJOs as web resources,
using HTTP as the network protocol.
Applications using these APIs...
Resources and JAX-RS
1.Define a root resource
@Path(”jedis")
public class JediResource {
}
2. Define methods for resource ...
SubResources and JAX-RS
1.Define a sub resource
@Path("/jedis")
public class JediResource {
@Path(”/jedi/{name}")
public J...
SubResources and JAX-RS
• If request is GET /jedis/Yodas
• The JediResource.getJedi() method will be invoked.
• If a clien...
Client API for JAX-RS 2.0
• Client client = ClientBuilder.newClient();
• WebTarget target = client.target(URI);
• String j...
JAX-RS 2.0
 Client API
 Filters and Interceptors
 Client-side and Server-side Asynchronous
 Improved Connection Negoti...
Java API for JSON
Processing JSON-P
 Streaming API to produce/consume JSON
 Similar to StAX API in XML world
 Object mo...
JsonParser
 JsonParser – Parses JSON in a streaming way from
input sources
 Similar to StAX’s XMLStreamReader, a pull pa...
JsonGenerator
 JsonGenerator – Generates JSON in a streaming
way to output sources
 Similar to StAX’s XMLStreamWriter
 ...
JsonReader
 Reads JsonObject and JsonArray from
input source
 Uses pluggable JsonParser
try (JsonReader reader = new Jso...
JsonWriter
 Writes JsonObject and JsonArray to
output source
 Uses pluggable JsonGenerator
// Writes a JSON object
try (...
JSON sample data
{
”name": "Jar Jar Binks”, ”home": “Naboo”,
”affilitation": [
{ "type": ”primary", "name": ”Royal
House o...
Call for action
• Download GlassFish 4.0 from glassfish.dev.java.net
• File issues, contribute patches
• Email users@glass...
Questions
• Twitter: @bhakti_mehta
• Blog https://www.java.net//blogs/bhaktimehta
• LinkedIn: http://www.linkedin.com/in/b...
Copyright 2013, Bhakti Mehta all
rights reserved
Upcoming SlideShare
Loading in …5
×

Fight empire-html5

723 views

Published on

Based on the Star Wars theme, this session focuses on how Java EE 7 provides an extensive set of new and enhanced features to support standards such as HTML5, WebSocket, and Server-sent events, among others. The session shows how these new features are designed and matched to work together for developing lightweight solutions matching end users’ high expectations for Web application responsiveness. It covers best practices and design patterns associating the technologies with analogies from Star Wars. So join me in this fun filled talk where technology meets science and innovation..
May the force be with you!

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Fight empire-html5

  1. 1. Fight the empire light weightly with HTML5, WebSockets, Server-sent Events and others Bhakti Mehta Twitter: @bhakti_mehta
  2. 2. Introduction • Currently working as a Senior Software Engineer at Blue Jeans Network. Bluejeans.com • Worked at Sun Microsystems/Oracle for 13 years • Committer to numerous open source projects • Author of Developing RESTful Services with JAX-RS 2.0, WebSockets and JSON Copyright 2013, Bhakti Mehta all rights reserved
  3. 3. Fight the empire! Copyright 2013, Bhakti Mehta all rights reserved
  4. 4. Agenda  Introduction  Polling  Server- sent Events (SSE)  WebSockets  JAXRS 2.0  JSON-P Copyright 2013, Bhakti Mehta all rights reserved
  5. 5. Polling  Used by vast majority of AJAX applications  Poll the server for data  Client --->request--> Server  If no data empty response is returned Copyright 2013, Bhakti Mehta all rights reserved
  6. 6. Polling Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) Response 200 OK: empty Request (client_id) …. …. …. …. Response 200 OK: message body
  7. 7. Polling Drawbacks  Http overhead  Reducing the interval will consume more bandwidth and processing resources for nothing. Copyright 2013, Bhakti Mehta all rights reserved
  8. 8. Long Polling  If server does not have data holds request open  COMET  Chunked transfer encoding can be used to send chunks of data as part of response body which is opened as a stream.  Chunks can be javascript tags loaded in hidden iframe and executed in order of arrival Copyright 2013, Bhakti Mehta all rights reserved
  9. 9. Long Polling Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) Response 200 OK: message body Request (client_id) …. …. …. Response 200 OK: message body …. ….
  10. 10. Long Polling Drawbacks • One-way communication • No standard data format or message format when used in chunked transfer encoding mode • Each connection initiation has the initiation cost. • No caching between clients and server, which impacts the server performance instead of reading some contents from the cache. Copyright 2013, Bhakti Mehta all rights reserved
  11. 11. Server-sent events Copyright 2013, Bhakti Mehta all rights reserved  Unidirectional channel between server and client  Server pushes data to your app when it wants  Updates can be streamed from server to client as they happen
  12. 12. Server-sent Events Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) …. …. …. SSE message …. …. SSE message
  13. 13. Server-sent Events  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() functions Copyright 2013, Bhakti Mehta all rights reserved
  14. 14. Message format for SSE  Sending an event stream  Construct a plaintext response, served with a text/event-stream Content-Type.  Sample message format  data: Help me Obi Wan-Kenobi you are my only hopenn Copyright 2013, Bhakti Mehta all rights reserved
  15. 15. Server-sent Events and JSON  Sending JSON You can send multiple lines without breaking JSON format by sending messages like this data: {nn data: "name": Luke Skywalker",nn data: ”home": Tatooinenn data: }nn  On client side source.addEventListener('message', function(e) { var data = JSON.parse(e.data); Copyright 2013, Bhakti Mehta all rights reserved
  16. 16. Associating event names with SSE event: order66Issuedn data: {“issuer” : “Chancellor Palpatine”}nn event: jedisPurgedn data: {“survivor” :”Obi-Wan Kenobi, Yoda”}nn Copyright 2013, Bhakti Mehta all rights reserved
  17. 17. Associating ids with SSE Associating ids with events can help with fault tolerance in SSE id: 123 n data: Battle of droids deployed at Naboonn Copyright 2013, Bhakti Mehta all rights reserved
  18. 18. Connection loss and retries • Browsers that support SSE can try reconnecting to the server in case the connection between browser and server is severed. The default retry interval is 3000 milliseconds but it can be adjusted by including the retry directive in the messages that server sends to the client. • For example to increase the retry interval to 5000 milliseconds SSE message that server sends can be similar to the following listing: retry: 5000n data: This is a single line datann Copyright 2013, Bhakti Mehta all rights reserved
  19. 19. 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 2013, Bhakti Mehta all rights reserved
  20. 20. Best practices for Server- sent Events  Check if eventSource's origin attribute is the expected domain to get the message if (e.origin != 'http://foo.com') { alert('Origin was not http://foo.com'); return; Copyright 2013, Bhakti Mehta all rights reserved
  21. 21. Best practices for Server- sent Events  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 2013, Bhakti Mehta all rights reserved
  22. 22. Comparing Polling vs Long Polling vs SSE  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: GET. Wait. Process data. Wait. Process data. Wait... 1 GET = 1 HTTP response header and chunks of data with small headers Copyright 2013, Bhakti Mehta all rights reserved
  23. 23. WebSockets  Full duplex communication in either direction  Data is framed with 2 bytes  In the case of text frames, each frame starts with a 0x00 byte, ends with a 0xFF byte, and contains UTF-8 data in between. Copyright 2013, Bhakti Mehta all rights reserved
  24. 24. WebSockets  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 …rn Copyright 2013, Bhakti Mehta all rights reserved
  25. 25. WebSockets Handshake Copyright 2013, Bhakti Mehta all rights reserved
  26. 26. WebSockets  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 Copyright 2013, Bhakti Mehta all rights reserved
  27. 27. WebSockets JSR 356  @ServerEndpoint signifies that the Java class it decorates is to be deployed as WebSocket endpoint  Additionally the following components can be annotated with @ServerEndpoint  a stateless session EJB  a singleton EJB  a CDI managed bean Copyright 2013, Bhakti Mehta all rights reserved
  28. 28. WebSockets and Security  A web socket which is mapped to a given ws:// URI is protected in the deployment descriptor with a listing to a http:// URI with same hostname, port and path since this is the URL of its opening handshake Copyright 2013, Bhakti Mehta all rights reserved
  29. 29. Comparisons Subject SSE WebSockets Long Polling Error Handling Built in support Built in support Almost no error handling in chunked transfer Performance Better than long polling and inferior to WebSockets Best performance Small CPU resource but idle process/thread per client connection limits scalability Communication channel HTTP unidirectional WebSockets bidirectional Http unidirectional Copyright 2013, Bhakti Mehta all rights reserved
  30. 30. Comparisons Subject SSE WebSockets Long Polling Implementation complexity Easy Requires websocket support Easiest Browser Support Firefox,Chrome Safari, Opera For RFC 6455: IE 10, Firefox 11, Chrome 16, Safari 6, Opera 12.10 All current browsers Copyright 2013, Bhakti Mehta all rights reserved
  31. 31. Best practices for WebSockets • Throttling the rate of sending data • The WebSockets has a bufferedAmount attribute which can be used to control the rate of sending data. Using the bufferedAmount attribute you can check the number of bytes that have been queue but not yet sent to the server. if (webSocket.bufferedAmount < THRESHOLD) webSocket.send(someData); }; Copyright 2013, Bhakti Mehta all rights reserved
  32. 32. Best practices for WebSockets • Controlling the maximum size of the message • Use the maxMessageSize attribute on @OnMessage annotation • If the incoming message exceeds the maximum size then the connection is closed. This is a good practice to control the maximum size of a message so that the client does not deplete its resources trying to handle a message, which it can’t process. Copyright 2013, Bhakti Mehta all rights reserved
  33. 33. Best practices for WebSockets • Use wss protocol with Proxy servers • Proxy servers may not allow unencrypted Web Socket traffic to flow through. Since the traffic is encrypted there is a greater chance to pass through the proxy server. • Then the CONNECT statements will work and there will be an end-to-end encrypted tunnel for web sockets. Copyright 2013, Bhakti Mehta all rights reserved
  34. 34. Best practices for WebSockets Copyright 2013, Bhakti Mehta all rights reserved Client1 Client2 Client3
  35. 35. RESTful Webservices • Key principles of REST • Associating IDs to resources • Using standard HTTP methods • Multiple formats data sent by a resource • Statelessness Copyright 2013, Bhakti Mehta all rights reserved
  36. 36. RESTful WebServices • GET: The GET request retrieves a representation of a resource from server to client. • POST: The POST request is used to create a resource on the server based on the representation that the client sends. • PUT: The PUT request is used to update or create a reference to a resource on server. • DELETE: The DELETE request can delete a resource on server. • HEAD: The HEAD requests checks for a resource without retrieving it. Copyright 2013, Bhakti Mehta all rights reserved
  37. 37. RESTful WebServices • Safety o Invoking a method does not change the resource on server o GET, HEAD are safe o PUT, DELETE, POST are not safe • Idempotence o Calling a method multiple times will not change the result o GET, HEAD, PUT,DELETE are idempotent o POST is not idempotent Copyright 2013, Bhakti Mehta all rights reserved
  38. 38. JAX-RS 2.0 Defines how to expose POJOs as web resources, using HTTP as the network protocol. Applications using these APIs can be deployed to an application server in a portable manner. Copyright 2013, Bhakti Mehta all rights reserved
  39. 39. Resources and JAX-RS 1.Define a root resource @Path(”jedis") public class JediResource { } 2. Define methods for resource and mime type @GET @Produces(“text/plain”) public String getRank() { return rank; // for eg Youngling, Padawan, Jedi Knight or Jedi Master } Copyright 2013, Bhakti Mehta all rights reserved
  40. 40. SubResources and JAX-RS 1.Define a sub resource @Path("/jedis") public class JediResource { @Path(”/jedi/{name}") public Jedi getJedi(@PathParam(”name") String name){ //return Jedi } public class Jedi { @Path(”/apprentice") public String getApprentice(){ } } Copyright 2013, Bhakti Mehta all rights reserved
  41. 41. SubResources and JAX-RS • If request is GET /jedis/Yodas • The JediResource.getJedi() method will be invoked. • If a client sends a request using the URI • GET /jedis/Yoda/apprentice • Jedi object is returned and getApprentice() method is invoked Copyright 2013, Bhakti Mehta all rights reserved
  42. 42. Client API for JAX-RS 2.0 • Client client = ClientBuilder.newClient(); • WebTarget target = client.target(URI); • String jedi = target.request().get(String.class); Copyright 2013, Bhakti Mehta all rights reserved
  43. 43. JAX-RS 2.0  Client API  Filters and Interceptors  Client-side and Server-side Asynchronous  Improved Connection Negotiation  Alignment with JSR 330 Copyright 2013, Bhakti Mehta all rights reserved
  44. 44. Java API for JSON Processing JSON-P  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 Copyright 2013, Bhakti Mehta all rights reserved
  45. 45. JsonParser  JsonParser – Parses JSON in a streaming way from input sources  Similar to StAX’s XMLStreamReader, a pull parser  Created  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 2013, Bhakti Mehta all rights reserved
  46. 46. JsonGenerator  JsonGenerator – Generates JSON in a streaming way to output sources  Similar to StAX’s XMLStreamWriter  Created using : Json.createGenerator(…), Json.createGeneratorFactory().createGenerator(…) Copyright 2013, Bhakti Mehta all rights reserved
  47. 47. JsonReader  Reads JsonObject and JsonArray from input source  Uses pluggable JsonParser try (JsonReader reader = new JsonReader(io)) { JsonObject obj = reader.readObject(); } Copyright 2013, Bhakti Mehta all rights reserved
  48. 48. 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 2013, Bhakti Mehta all rights reserved
  49. 49. JSON sample data { ”name": "Jar Jar Binks”, ”home": “Naboo”, ”affilitation": [ { "type": ”primary", "name": ”Royal House of Naboo" }, { "type": ”secondary", "name": ”Galactic republic" }]} ] } Copyright 2013, Bhakti Mehta all rights reserved
  50. 50. Call for action • Download GlassFish 4.0 from glassfish.dev.java.net • File issues, contribute patches • Email users@glassfish.dev.java.net Copyright 2013, Bhakti Mehta all rights reserved
  51. 51. Questions • Twitter: @bhakti_mehta • Blog https://www.java.net//blogs/bhaktimehta • LinkedIn: http://www.linkedin.com/in/bhaktihmehta • May the force be with you!! Copyright 2013, Bhakti Mehta all rights reserved
  52. 52. Copyright 2013, Bhakti Mehta all rights reserved

×