fight empire-html5

52
Fight the empire light weightly with HTML5, WebSockets, Server-sent Events and others Bhakti Mehta Twitter: @bhakti_mehta

Upload: bhakti-mehta

Post on 11-May-2015

322 views

Category:

Technology


1 download

DESCRIPTION

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!

TRANSCRIPT

Page 1: Fight empire-html5

Fight the empire light weightly with HTML5, WebSockets,

Server-sent Events and othersBhakti MehtaTwitter: @bhakti_mehta

Page 2: Fight empire-html5

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

Page 3: Fight empire-html5

Fight the empire!

Copyright 2013, Bhakti Mehta all rights reserved

Page 4: Fight empire-html5

Agenda Introduction Polling Server- sent Events (SSE) WebSockets JAXRS 2.0 JSON-P

Copyright 2013, Bhakti Mehta all rights reserved

Page 5: Fight empire-html5

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

Page 6: Fight empire-html5

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

Page 7: Fight empire-html5

Polling Drawbacks Http overhead Reducing the interval will consume more

bandwidth and processing resources for nothing.

Copyright 2013, Bhakti Mehta all rights reserved

Page 8: Fight empire-html5

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

Page 9: Fight empire-html5

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

….….

Page 10: Fight empire-html5

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

Page 11: Fight empire-html5

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

Page 12: Fight empire-html5

Server-sent Events

Copyright 2013, Bhakti Mehta all rights reserved

Client Server

Request (client_id)

….….….

SSE message

….….

SSE message

Page 13: Fight empire-html5

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

Page 14: Fight empire-html5

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

hope\n\n

Copyright 2013, Bhakti Mehta all rights reserved

Page 15: Fight empire-html5

Server-sent Events and JSON

Sending JSON

You can send multiple lines without breaking JSON format by sending messages like this

data: {\n\n

data: "name": Luke Skywalker",\n\n

data: ”home": Tatooine\n\n

data: }\n\n

On client side source.addEventListener('message', function(e) {

var data = JSON.parse(e.data);

Copyright 2013, Bhakti Mehta all rights reserved

Page 16: Fight empire-html5

Associating event names with SSE

event: order66Issued\ndata: {“issuer” : “Chancellor Palpatine”}\n\nevent: jedisPurged\ndata: {“survivor” :”Obi-Wan Kenobi, Yoda”}\n\n

Copyright 2013, Bhakti Mehta all rights reserved

Page 17: Fight empire-html5

Associating ids with SSE

Associating ids with events can help with fault tolerance in SSEid: 123 \ndata: Battle of droids deployed at Naboo\n\n

Copyright 2013, Bhakti Mehta all rights reserved

Page 18: Fight empire-html5

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: 5000\n data: This is a single line data\n\n

Copyright 2013, Bhakti Mehta all rights reserved

Page 19: Fight empire-html5

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

Page 20: Fight empire-html5

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

Page 21: Fight empire-html5

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

Page 22: Fight empire-html5

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

Page 23: Fight empire-html5

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

Page 24: Fight empire-html5

WebSockets 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

Copyright 2013, Bhakti Mehta all rights reserved

Page 25: Fight empire-html5

WebSockets Handshake

Copyright 2013, Bhakti Mehta all rights reserved

Page 26: Fight empire-html5

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

Page 27: Fight empire-html5

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

Page 28: Fight empire-html5

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

Page 29: Fight empire-html5

ComparisonsSubject 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

Page 30: Fight empire-html5

ComparisonsSubject 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

Page 31: Fight empire-html5

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

Page 32: Fight empire-html5

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

Page 33: Fight empire-html5

Copyright 2013, Bhakti Mehta all rights reserved

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. 

Page 34: Fight empire-html5

Best practices for WebSockets

Copyright 2013, Bhakti Mehta all rights reserved

Client1

Client2

Client3

Page 35: Fight empire-html5

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

Page 36: Fight empire-html5

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

Page 37: Fight empire-html5

RESTful WebServices• Safety

o Invoking a method does not change the resource on server

o GET, HEAD are safeo PUT, DELETE, POST are not safe

• Idempotenceo Calling a method multiple times will not

change the resulto GET, HEAD, PUT,DELETE are idempotento POST is not idempotent

Copyright 2013, Bhakti Mehta all rights reserved

Page 38: Fight empire-html5

JAX-RS 2.0Defines 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

Page 39: Fight empire-html5

Resources and JAX-RS1.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

Page 40: Fight empire-html5

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

Page 41: Fight empire-html5

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

Page 42: Fight empire-html5

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

Page 43: Fight empire-html5

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

Page 44: Fight empire-html5

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

Page 45: Fight empire-html5

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

Page 46: Fight empire-html5

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

Page 47: Fight empire-html5

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

Page 48: Fight empire-html5

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

Page 49: Fight empire-html5

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

Page 50: Fight empire-html5

Call for action• Download GlassFish 4.0 from

glassfish.dev.java.net• File issues, contribute patches• Email [email protected]

Copyright 2013, Bhakti Mehta all rights reserved

Page 51: Fight empire-html5

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

Page 52: Fight empire-html5

Copyright 2013, Bhakti Mehta all rights reserved