SlideShare ist ein Scribd-Unternehmen logo
1 von 43
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
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.
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.
Polling Drawbacks
        § Http overhead
        § Reducing the interval will consume more
             bandwidth and processing resources.




Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Async Servlet components
        § Thread Pool and Queue
        § AsyncContext
        § Runnable instance
        § Servlet/Filter chain




Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
DEMO


Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
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.
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.
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.
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.
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.
43Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 13

Weitere ähnliche Inhalte

Was ist angesagt?

OAuth and STUN, TURN in WebRTC context RFC7635
OAuth and STUN, TURN  in WebRTC context RFC7635OAuth and STUN, TURN  in WebRTC context RFC7635
OAuth and STUN, TURN in WebRTC context RFC7635
Mihály Mészáros
 

Was ist angesagt? (20)

Soap and Rest
Soap and RestSoap and Rest
Soap and Rest
 
OAuth and STUN, TURN in WebRTC context RFC7635
OAuth and STUN, TURN  in WebRTC context RFC7635OAuth and STUN, TURN  in WebRTC context RFC7635
OAuth and STUN, TURN in WebRTC context RFC7635
 
Bulk Export Tool for Alfresco
Bulk Export Tool for AlfrescoBulk Export Tool for Alfresco
Bulk Export Tool for Alfresco
 
Kafka Deep Dive
Kafka Deep DiveKafka Deep Dive
Kafka Deep Dive
 
Extending WSO2 API Manager's Key Management Capabilities - WSO2 API Manager C...
Extending WSO2 API Manager's Key Management Capabilities - WSO2 API Manager C...Extending WSO2 API Manager's Key Management Capabilities - WSO2 API Manager C...
Extending WSO2 API Manager's Key Management Capabilities - WSO2 API Manager C...
 
Deep Dive Into Kafka Tiered Storage With Satish Duggana | Current 2022
Deep Dive Into Kafka Tiered Storage With Satish Duggana | Current 2022Deep Dive Into Kafka Tiered Storage With Satish Duggana | Current 2022
Deep Dive Into Kafka Tiered Storage With Satish Duggana | Current 2022
 
Temporal-Joins in Kafka Streams and ksqlDB | Matthias Sax, Confluent
Temporal-Joins in Kafka Streams and ksqlDB | Matthias Sax, ConfluentTemporal-Joins in Kafka Streams and ksqlDB | Matthias Sax, Confluent
Temporal-Joins in Kafka Streams and ksqlDB | Matthias Sax, Confluent
 
Real-time Analytics with Upsert Using Apache Kafka and Apache Pinot | Yupeng ...
Real-time Analytics with Upsert Using Apache Kafka and Apache Pinot | Yupeng ...Real-time Analytics with Upsert Using Apache Kafka and Apache Pinot | Yupeng ...
Real-time Analytics with Upsert Using Apache Kafka and Apache Pinot | Yupeng ...
 
Why My Streaming Job is Slow - Profiling and Optimizing Kafka Streams Apps (L...
Why My Streaming Job is Slow - Profiling and Optimizing Kafka Streams Apps (L...Why My Streaming Job is Slow - Profiling and Optimizing Kafka Streams Apps (L...
Why My Streaming Job is Slow - Profiling and Optimizing Kafka Streams Apps (L...
 
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long PollingDifference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content Transformation
 
Oracle Service Bus 12c (12.2.1) What You Always Wanted to Know
Oracle Service Bus 12c (12.2.1) What You Always Wanted to KnowOracle Service Bus 12c (12.2.1) What You Always Wanted to Know
Oracle Service Bus 12c (12.2.1) What You Always Wanted to Know
 
Pinot: Enabling Real-time Analytics Applications @ LinkedIn's Scale
Pinot: Enabling Real-time Analytics Applications @ LinkedIn's ScalePinot: Enabling Real-time Analytics Applications @ LinkedIn's Scale
Pinot: Enabling Real-time Analytics Applications @ LinkedIn's Scale
 
Load testing Elasticsearch with Gatling
Load testing Elasticsearch with GatlingLoad testing Elasticsearch with Gatling
Load testing Elasticsearch with Gatling
 
카프카, 산전수전 노하우
카프카, 산전수전 노하우카프카, 산전수전 노하우
카프카, 산전수전 노하우
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
Apache Kafka’s Transactions in the Wild! Developing an exactly-once KafkaSink...
 
seven-ways-to-run-flink-on-aws.pdf
seven-ways-to-run-flink-on-aws.pdfseven-ways-to-run-flink-on-aws.pdf
seven-ways-to-run-flink-on-aws.pdf
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 
Kafka for Real-Time Replication between Edge and Hybrid Cloud
Kafka for Real-Time Replication between Edge and Hybrid CloudKafka for Real-Time Replication between Edge and Hybrid Cloud
Kafka for Real-Time Replication between Edge and Hybrid Cloud
 

Andere mochten auch

HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
Roger Kitain
 

Andere mochten auch (10)

REST, Web Sockets, Server-sent Events
REST, Web Sockets, Server-sent EventsREST, Web Sockets, Server-sent Events
REST, Web Sockets, Server-sent Events
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
Asynchroniczny PHP i komunikacja czasu rzeczywistego z wykorzystaniem websocketw
Asynchroniczny PHP i komunikacja czasu rzeczywistego z wykorzystaniem websocketwAsynchroniczny PHP i komunikacja czasu rzeczywistego z wykorzystaniem websocketw
Asynchroniczny PHP i komunikacja czasu rzeczywistego z wykorzystaniem websocketw
 
Server-Side Programming Primer
Server-Side Programming PrimerServer-Side Programming Primer
Server-Side Programming Primer
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?
 
What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)What's next for Java API for WebSocket (JSR 356)
What's next for Java API for WebSocket (JSR 356)
 
CON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To YouCON5898 What Servlet 4.0 Means To You
CON5898 What Servlet 4.0 Means To You
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
 

Ähnlich wie Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!

Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
Arun Gupta
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
David Delabassee
 
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur! Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
David Delabassee
 

Ähnlich wie Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together! (20)

Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
 
Con fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhaktiCon fess 2013-sse-websockets-json-bhakti
Con fess 2013-sse-websockets-json-bhakti
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun GuptaGetting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5
 
Java ee7 1hour
Java ee7 1hourJava ee7 1hour
Java ee7 1hour
 
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
Building HTML5 WebSocket Apps in Java at JavaOne Latin America 2012
 
Websocket 1.0
Websocket 1.0Websocket 1.0
Websocket 1.0
 
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
Java EE 7 Platform: Boosting Productivity and Embracing HTML5 - Arun Gupta (R...
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
 
HTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun GuptaHTML5 Websockets and Java - Arun Gupta
HTML5 Websockets and Java - Arun Gupta
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
Presente e Futuro: Java EE.next()
Presente e Futuro: Java EE.next()Presente e Futuro: Java EE.next()
Presente e Futuro: Java EE.next()
 
OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7OTN Tour 2013: What's new in java EE 7
OTN Tour 2013: What's new in java EE 7
 
Coherence 12.1.2 Live Events
Coherence 12.1.2 Live EventsCoherence 12.1.2 Live Events
Coherence 12.1.2 Live Events
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012
 
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
Project Avatar (Lyon JUG & Alpes JUG  - March 2014)Project Avatar (Lyon JUG & Alpes JUG  - March 2014)
Project Avatar (Lyon JUG & Alpes JUG - March 2014)
 
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur! Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
Java EE 7 et ensuite pourquoi pas JavaScript sur le serveur!
 

Mehr von Masoud Kalali

Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
Masoud Kalali
 

Mehr von Masoud Kalali (13)

Real world RESTful service development problems and solutions
Real world RESTful service development problems and solutionsReal world RESTful service development problems and solutions
Real world RESTful service development problems and solutions
 
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EECON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE
 
BOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectivelyBOF 2193 - How to work from home effectively
BOF 2193 - How to work from home effectively
 
Real-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and SolutionsReal-World RESTful Service Development Problems and Solutions
Real-World RESTful Service Development Problems and Solutions
 
How to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid themHow to avoid top 10 security risks in Java EE applications and how to avoid them
How to avoid top 10 security risks in Java EE applications and how to avoid them
 
Java EE 7 overview
Java EE 7 overviewJava EE 7 overview
Java EE 7 overview
 
Confess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practiceConfess 2013: OWASP Top 10 and Java EE security in practice
Confess 2013: OWASP Top 10 and Java EE security in practice
 
Utilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE SecurityUtilize the Full Power of GlassFish Server and Java EE Security
Utilize the Full Power of GlassFish Server and Java EE Security
 
Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881Slides for the #JavaOne Session ID: CON11881
Slides for the #JavaOne Session ID: CON11881
 
Security in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missingSecurity in java ee platform: what is included, what is missing
Security in java ee platform: what is included, what is missing
 
An Overview of RUP methodology
An Overview of RUP methodologyAn Overview of RUP methodology
An Overview of RUP methodology
 
An overview of software development methodologies.
An overview of software development methodologies.An overview of software development methodologies.
An overview of software development methodologies.
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the future
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

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.
  • 37. DEMO 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