Weitere ähnliche Inhalte Ähnlich wie Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together! (20) Mehr von Masoud Kalali (13) Kürzlich hochgeladen (20) Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!1. Server Sent Events, Async Servlet,
WebSockets and JSON; born to
work
Masoud Kalali: Principal Software Bhakti Mehta: Principal Member of Technical
Engineer at ORACLE Staff at ORACLE
Blog: Http://kalali.me Blog: http://www.java.net/blogs/bhaktimehta
Twitter: @MasoudKalali Twitter: @bhakti_mehta
1Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13
2. Program Agenda
§ Introduction
§ Polling
§ Server Sent Events (SSE)
§ WebSockets
§ JSON-P
§ JAXRS 2.0
§ AsyncServlet
§ Demo
§ Q&A
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
3. Polling
§ Used by vast majority of AJAX applications
§ Poll the server for data
§ Client --->request--> Server
§ If no data empty response is returned
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
4. Polling Drawbacks
§ Http overhead
§ Reducing the interval will consume more
bandwidth and processing resources.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
5. 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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
6. Long Polling Drawbacks
§ Missing error handling
§ Involves hacks by adding script tags to an infinite iframe
§ Hard to check the state of request
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
7. 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 happen
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
8. 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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
9. 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.
10. 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 messagenn
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
11. 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.
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
13. 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.
14. Best practices for ServerSentEvents
§ 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;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
15. 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 computations
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
16. 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.
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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
19. 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 onerror
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
20. 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 bean
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
21. 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.
22. WebSockets and security
§ WebSockets URI starts with ws/wss
§ Conform to the same security that already exists at container level
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
23. 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 world
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
24. 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.
25. 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.
26. 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.
27. 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.
28. 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.
29. 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 source
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
30. 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.
31. 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.
32. 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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
33. 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.
34. 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.
35. 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.
36. Async Servlet components
§ Thread Pool and Queue
§ AsyncContext
§ Runnable instance
§ Servlet/Filter chain
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
38. Demo class diagram
Create EventSource
ParseJson data
Display in servlet
Writes the message
Gets data from on the EventChannel
twitter search
apis
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
39. 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.
40. 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.
41. 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
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
42. 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 PM
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
43. 43Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 13