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
:http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/
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. 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. Long Polling
§Uses persistent or long-lasting HTTP connection between the server
and the client
§If server does not have data holds request open
§COMET
7. Long Polling Drawbacks
§Missing error handling
§Involves hacks by adding script tags to an infinite iframe
§Hard to check the request state
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. 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. 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 format
data: My messagenn
11. Server Sent Events and JSON
§Possible to send multiline texts
§E.g. Sending JSON
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);
//process the data
}, false);
12. 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.
13. Server Sent Events and Jersey 2.0 apis
§Client apis in Jersey 2.0
Client client = ClientBuilder.newClient();
WebTarget webTarget= client.target(new URI(TARGET_URI)) ;
§ EventSource apis in Jersey 2.0
EventSource eventSource = new EventSource(webTarget) {
@Override
public void onEvent(InboundEvent inboundEvent) {
//Get the data from the InboundEvent
//Process it as needed.
}
14. Best practices for ServerSentEvents
§Check that the data in question is of the expected format.
§Limit the arriving messages per minute
§Check if eventSource's 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;
15. Best practices for ServerSentEvents
§Associating an ID with an event
●
Each event has an unique ID as event.id
●
EventSource uses the event.id when reconnecting
●
Server knows how many pushed events the client has missed
●
Good to resume a failed connection
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. Process
data. Wait..
1 GET = 1 HTTP response header, many chunks of data
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. 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 …rn
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 opened
socket.onmessage: When a message has been received
socket.onclose: When a socket has been closed
§For example
socket.onmessage = function(msg){
alert(msg);
}
20. WebSockets API JSR 356
§@ServerEndpoint
signifies that the Java class it decorates is to be deployed as
a WebSocket endpoint.
§The following components can be annotated with @ServerEndpoint
●
a stateless session EJB
●
a singleton EJB
●
a CDI managed bean
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
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 XML
world
§Object model API to represent JSON Similar to DOM API in XML
world
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. 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(…)
28. JsonGenerator
§JsonGenerator: Generates JSON in a streaming way to output
sources
§Similar to StAX’s XMLStreamWriter
§Created using :
Json.createGenerator(…),
Json.createGeneratorFactory(...).createGenerator(…)
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. 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. JsonWriter
§Writes JsonObject and JsonArray to output source
§Uses pluggable JsonGenerator
§Write a json object:
JsonWriter writer = new JsonWriter(io)
writer.writeObject(obj);
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
39. Demo class diagram
Gets data from
twitter search
apis
Writes the message
on the EventChannel
Create EventSource
ParseJson data
Display in servlet
40. 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();
}
41. AsyncServlet code sample
class AsyncRequestProcessor implements Runnable {
@Override
public void run() {
Client client = ClienttBuildernewClient();
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
}
42. Trying the sample
Clone 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