• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Fight empire-html5
 

Fight empire-html5

on

  • 382 views

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

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!

Statistics

Views

Total Views
382
Views on SlideShare
368
Embed Views
14

Actions

Likes
0
Downloads
3
Comments
0

2 Embeds 14

http://www.linkedin.com 11
https://www.linkedin.com 3

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

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

    Fight empire-html5 Fight empire-html5 Presentation Transcript

    • 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 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
    • 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 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 returned Copyright 2013, Bhakti Mehta all rights reserved
    • 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
    • Polling Drawbacks  Http overhead  Reducing the interval will consume more bandwidth and processing resources for nothing. Copyright 2013, Bhakti Mehta all rights reserved
    • 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
    • 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 …. ….
    • 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
    • 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
    • Server-sent Events Copyright 2013, Bhakti Mehta all rights reserved Client Server Request (client_id) …. …. …. SSE message …. …. SSE message
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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 formats data sent by a resource • Statelessness Copyright 2013, Bhakti Mehta all rights reserved
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • 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
    • Copyright 2013, Bhakti Mehta all rights reserved