SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
Writing Comet
Web Application using
GlassFish



 Jeanfrancois Arcand
 Sun Microsystems

                        1
Agenda
• What is Comet (aka Ajax Push)
• What is Grizzly Comet Framework
• Demo screan cast
• What is Atmosphere
• Summary
• More info
  > Tutorials
  > Project Grizzly



                                    2
What is Ajax Push, exactly?
Bending the rules of HTTP.




                              3
Ajax Poll vs Ajax Push
Bending the rules of HTTP.
•  Poll:
   > Send a request to the server every X seconds.
   > The response is “empty” if there is no update.
•  Long Poll:
   > Send a request to the server, wait for an event to happen, then send the
     response.
   > The response is never empty.
   > HTTP specification satisfied: indistinguishable from “slow” server
•  Http Streaming:
   > Send a request, wait for events, stream multi-part/chunked response, and
      then wait for the events.
   > The response is continually appended to.
                                                                                4
Comet on GlassFish




                     5
Introduction to Grizzly Comet
• Grizzly Comet is a framework that ship with
  GlassFish v2 and v3, and can also be embedded
  into any application using the Grizzly Embed
  interface
• The Grizzly Comet Framework includes a set of
  components that can be used for building Comet
  based application:
  > Grizzly Comet, Continuation, Grizzlet, Messages Bus,
• It also support the JSON based Bayeux Protocol
  (aka Comet)
                                                           6
Grizzly Comet Framework
• The Framework contains the classes required to add
  support for Comet in a Web Application
• Main classes to interact with (details next):
  > CometContext
  > CometHandler
  > NotificationHandler




                                                       7
Grizzly Comet Framework
How it works
                   send




                                    push
                          filters
     send
            Push data




                                           8
Grizzly Comet in 3 steps
 •  Suspend:
   >  addCometHandler(CometHandler)
 •  Push:
   >  notify(<? extends Object>) // All suspended responses
   >  notify(<? extends Object>, CometHandler) // Only one
 •  Write: Inside CometHandler.onEvent()
   >  PrintWriter.write(CometEvent.attachment());
 •  Resume:
   >  resumeCometHandler(CometHandler)


                                                              9
CometContext
 •  A CometContext is a distribution mechanism for
    pushing messages that are delivered to multiple
    subscribers called CometHandler (a la JMS Queue/
    Topic).
 •  All http response registered to a CometContext
    automatically becomes suspended, waiting for an event
    (a push) to happens.
 •  A browser receives only those messages published
    after the client suspend its response via CometContext.


                                                              10
CometContext – 5 APIs to
remember
 •  addCometHandler: Suspend the current response,
    await for data to be transformed.
 •  resumeCometHandler: Resume the current response,
    and re-enable the normal http keep-alive mechanism.
 •  notify(..): Dispatch data to the suspended response.
 •  registerAsyncRead: Allow a suspended response to
    read asynchronously bytes. e.g avoid blocking waiting
    for the client to send all the bytes.
 •  registerAsyncWrite: Allow a suspended response to
    write asynchronously bytes.
                                                            11
Creating a CometContext

 /**
    * Create a {@link CometContext}
    * @param id - The topic associated with the {@link CometContext}
    * @return {@link CometContext}
    */
   private CometContext createCometContext(String id){
       CometEngine cometEngine = CometEngine.getEngine();
       CometContext ctx = cometEngine.register(id);
       ctx.setExpirationDelay(idleTimeBeforeForcingResume);
       return ctx;
   }




                                                                       12
Suspending an Http Response


   // Create a CometContext based on this session id.
     twitterContext =
           createCometContext(sessionId);

    // Create and register a CometHandler.
    ReflectorCometHandler handler = new ReflectorCometHandler
          (true,startingMessage,endingMessage);

   // Pass the ‘suspended’ PrintWriter that can be used to write response
   // back to the client
    handler.attach(response.getWriter());
    twitterContext.addCometHandler(handler);




                                                                            13
Resuming an Http Response

   if (event.getType() != CometEvent.READ) {
        printWriter.println(event.attachment());
        printWriter.flush();

        // long polling will resume automatically after the first event,
        // streaming will kept the response suspended
         if (!useStreaming){
             event.getCometContext().resumeCometHandler(this);
         }
    }




                                                                           14
Sharing data between suspended
responses
    twitterContext.notify(BEGIN_SCRIPT_TAG
            + toJsonp(quot;You are now following quot;, message)
            + END_SCRIPT_TAG, CometEvent.NOTIFY, ch);

     CometHandler twitterHandler =
           (CometHandler)followerContext.getAttribute(quot;twitterHandlerquot;);
     followerContext.notify(BEGIN_SCRIPT_TAG
           + toJsonp(name, quot; is now following quot; + message)
           + END_SCRIPT_TAG, CometEvent.NOTIFY, twitterHandler);



     // Notify other registered CometHandler.
    twitterContext.notify(quot;<script id='comet_quot; + counter++ + quot;'>quot;
          + quot;window.parent.quot; + callback + quot;(quot; + message + quot;);</script>quot;);



                                                                            15
Writing data to a suspended
response
public void onEvent(CometEvent event) throws IOException {
     try {
        if (event.getType() != CometEvent.READ) {
            printWriter.println(event.attachment());
            printWriter.flush();

          if (!useStreaming){
              event.getCometContext().resumeCometHandler(this);
          }
         }
      } catch (Throwable t) {
         throw new IOException(t.getMessage());
      }
  }




                                                                  16
CometHandler
• The CometHandler is the master piece of a Grizzly
  Comet based application.
• A CometHandler contains the business logic of what
  will be pushed back to the browser.
• A CometHandler might be invoked by the Container:
  > When the response is suspended or resumed
  > When a push operation happens
  > When a I/O operations are ready to be process
    (asynchronous read or write)
  > When the browser close the connection.
                                                       17
CometHandler API

 //Invoked when CometContext.notify() is called
  public void onEvent(CometEvent ce);

 // Invoked when the browser close a suspended
 // connection or when the suspend timeout expire.
 public void onInterrupt(CometEvent ce);

 // Invoked when the request is suspended
  public void onInitialize(CometEvent ce);

 // Invoked when the request is resumed
  public void onTerminate(CometEvent ce);




                                                     18
Example: ReflectorCometHandler
 /**
  * Write {@link CometEvent#attachment} and resume the connection if
  * {@link ReflectorCometHandler#useStreaming} is <tt>false</tt>
  * @param event
  * @throws java.io.IOException
  */
 public void onEvent(CometEvent event) throws IOException {
     try {
        if (event.getType() != CometEvent.READ) {
            printWriter.println(event.attachment());
            printWriter.flush();

         if (!useStreaming){
             event.getCometContext().resumeCometHandler(this);
         }
        }
     } catch (Throwable t) {
        throw new IOException(t.getMessage());
     }
 }
                                                                       19
NotificationHandler
•  The NotificationHandler object is the life saver when writing Comet
   application
•  This is inside that object that you will decide to what to do with
   the push operation:
       – Throttle: If too many push occurs simultaneously, should we delay
         them?
       – Aggregate: Should we cache push operations and aggregate them to
         avoid overloading the network?
       – Filter: Should all messages by pushed back to the client.
       – Should a thread pool be used to improve the push speed operation?
         Should a JMS backed be used to deliver the message?
•  The DefaultNotificationHandler push all messages.


                                                                             20
NotificationHandler – Main API
/**
      * Set to <tt>true</tt> if the invoker of notify() should block when
      * notifying Comet Handlers.
      */
      public void setBlockingNotification(boolean blockingNotification);


      /**
       * Notify all {@link CometHandler}.
       * @param cometEvent the CometEvent used to notify CometHandler
       * @param iteratorHandlers An iterator over a list of CometHandler
       */
      public void notify(CometEvent cometEvent,Iterator<CometHandler> iteratorHandlers)
           throws IOException;




                                                                                          21
NotificationHandler - Filtering

  public void notify(CometEvent<String>
                      ce,List<CometHandler> l){

      escape(ce);


      discard(ce);

  }




                                                  22
NotificationHandler - Clustering
 @Override
   public void notify(CometEvent cometEvent, Iterator<CometHandler> iteratorHandlers)
throws IOException {
     try {
        // Push to the cluster
         ObjectMessage message = jmsSession.createObjectMessage(cometEvent);
         messageproducer.send(message);

        // Push locally
         super.notify(cometEvent,iteratorHandlers);
      } catch (JMSException ex) {
         throw new IOException(quot;comet JMS send failed quot;, ex);
      }
  }




                                                                                        23
Demo




       24
How the client looks like?
• The client open a single connection to the server
  > Use http-streaming
• The Flickr Letters are powered by the a jMaki library
  which use http-streaming.
• The Follower/Following updates are made using a
  long poll connection, powered by the behavior.js
  framework.



                                                          25
How the client looks like?
• The client open a single connection to the server
  > Use http-streaming
• The Flickr Letters are powered by the a jMaki library
  which use http-streaming.
• The Follower/Following updates are made using a
  long poll connection, powered by the behavior.js and
  prototype.js framework.



                                                          26
What is Project Atmosphere
The state of Comet (Ajax Push) right now
•  Since July 2006 the Grizzly Comet Framework and its extensions’
   popularity keep increasing.
   >  Among the most popular framework right now.
•  Comet techniques aren't standardized among Web Container
   >  Grizzly Comet applications aren't portable (cannot run on Tomcat nor Jetty)‫‏‬
•  Servlet 3.0 will supports only a subset of Comet
   >  No async I/O, No pushing functionalities
   >  Way too complicated (this is my personal opinion )
   >  Support will takes time (Spec to be finalized)‫‏‬



                                                                                     27
What is Project Atmosphere (con't)‫‏‬
So...
• Atmosphere is a POJO based framework using
  Inversion of Control (IoC) to bring Comet to the
  masses.
• A framework which can run on any Java based Web
  Server.....without having to wait for Servlet 3.0 or
  without the needs to learn how Comet support has
  been differently implemented by current Web Server
  supporting Comet
• Run on top of Servlet 2.5 compliant Web Server
                                                         28
What is Project Atmosphere (con't)‫‏‬
Extends and improve the Grizzlet concept....
• Grizzlet is a POJO based approach for writing
  Comet application.
  > Grizzlet only runs on top of the Grizzly Comet
    Framework right now
  > Grizzly community asked many times to have the
    concept ported to other Web Server
• Evolve the Grizzlet...and make it the core of Project
  Atmosphere.
• Currently at version 0.1, with support for GlassFish,
  Tomcat and Jetty.
                                                          29
Architecture
Reuse experience and code...from Grizzly
Comet to Jersey!

            Grizzlet                               Atmosphere re-usable
       (Atmosphere POJO)‫‏‬                           Components library


              Jersey's Injection Provider, IoC Support, and more....


                      Atmosphere Servlet Runtime Engine


  Tomcat Comet                                Jetty Comet              Blocking WS
                      Grizzly Comet


             User defined              Atmosphere Component


                                                                                     30
Example
Easy of use of Jersey, power of Grizzly Comet
@Grizzlet(Grizzlet.Scope.APPLICATION)‫‏‬
@Path(quot;myGrizzletquot;)‫‏‬

public class MyGrizzlet{

  @Suspend(6000)‫‏‬

  @GET

  @Push

  public String onGet(){

      return quot;Suspending the connectionquot;;

  }

  @POST

  @Push

  public String onPost(@Context HttpServletRequest req,

                            @Context HttpServletResponse res) throws IOException{

      res.setStatus(200);

      res.getWriter().println(quot;OK, info pushedquot;);

      return req.getParameter(quot;chatMessagequot;);

  }                                                                                 31
Demo




       32
Summary
The Asynchronous Web Revolution is Now

•  The Asynchronous Web will revolutionize human
   interaction
•  Writing Comet application with GlassFish is easy!




                                                       33
For More Information
http://twitter.com/project_grizzly
•  Getting Started with Grizzly Comet Framework on GlassFish
   >  http://weblogs.java.net/blog/jfarcand/archive/2008/11/writing_a_twitt.html
   >  http://weblogs.java.net/blog/jfarcand/archive/2008/04/the_hitchhikers.html
   >  http://weblogs.java.net/blog/jfarcand/archive/2006/10/writting_a_come.html

•  GlassFish’s Comet Official Documentation:
   >  http://docs.sun.com/app/docs/doc/820-4496/ggrgy

•  GlassFish: http://glassfish.dev.java.net
•  Grizzly: http://grizzly.dev.java.net




                                                                                   34
What is Project Grizzly
•  Suite of embeddable components, which include:  
   >  Framework: A Framework for building network I/O applications  
   >  Http: A Framework for building HTTP based applications  
   >  Comet: A Framework for building AjaxPush/Comet applications  
   >  Cometd/Bayeux: The JSON based Bayeux protocol.  
   >  Servlet: A tiny Servlet Container with a programmatic API (not compliant)  
   >  HttpService OSGi implementation: OSGi enabled WebServer
•  Components only available for via GlassFish Enterprise (not OSS)  
   >  Cluster Comet: Grizzly Comet cluster enabled.

•  Who is using Grizzly:
    GlassFish v2, GlassFish v3 (JRuby, Grails, Admin, Servlet Container, V3 kernel build on top of it), Jetty, Jersey,
        JXTA, Netbeans, RESTlet, JXTA, Phobos, OpenESB, Sailfin, Futjisu, Sun Shared Shell, 4Home,
        Convergence, Ericsson, Nortel, Eventgnosis…and many many more!




                                                                                                                         35

Weitere ähnliche Inhalte

Was ist angesagt?

Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
MongoDB
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
Òscar Vilaplana
 

Was ist angesagt? (20)

JavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloadingJavaOne 2017 - The hitchhiker’s guide to Java class reloading
JavaOne 2017 - The hitchhiker’s guide to Java class reloading
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Guice gin
Guice ginGuice gin
Guice gin
 
Maintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood StyleMaintaining Your Code Clint Eastwood Style
Maintaining Your Code Clint Eastwood Style
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
 
Swift on Raspberry Pi
Swift on Raspberry PiSwift on Raspberry Pi
Swift on Raspberry Pi
 
Netty from the trenches
Netty from the trenchesNetty from the trenches
Netty from the trenches
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Swift hardware hacking @ try! Swift
Swift hardware hacking @ try! SwiftSwift hardware hacking @ try! Swift
Swift hardware hacking @ try! Swift
 
Streaming twitter data using kafka
Streaming twitter data using kafkaStreaming twitter data using kafka
Streaming twitter data using kafka
 
Mobile Programming - 3 UDP
Mobile Programming - 3 UDPMobile Programming - 3 UDP
Mobile Programming - 3 UDP
 
Testing microservices: Tools and Frameworks
Testing microservices: Tools and FrameworksTesting microservices: Tools and Frameworks
Testing microservices: Tools and Frameworks
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
 
Mobile Programming - Network Universitas Budi Luhur
Mobile Programming - Network Universitas Budi LuhurMobile Programming - Network Universitas Budi Luhur
Mobile Programming - Network Universitas Budi Luhur
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196The Ring programming language version 1.7 book - Part 75 of 196
The Ring programming language version 1.7 book - Part 75 of 196
 
Tornado web
Tornado webTornado web
Tornado web
 
The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202The Ring programming language version 1.8 book - Part 77 of 202
The Ring programming language version 1.8 book - Part 77 of 202
 

Ähnlich wie 20090315 Comet

Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talk
rajivmordani
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
jobandesther
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
deimos
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
Droidcon Berlin
 
#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run
Frederik De Bruyne
 

Ähnlich wie 20090315 Comet (20)

Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talk
 
Going Live! with Comet
Going Live! with CometGoing Live! with Comet
Going Live! with Comet
 
Time for Comet?
Time for Comet?Time for Comet?
Time for Comet?
 
Grizzly 20080925 V2
Grizzly 20080925 V2Grizzly 20080925 V2
Grizzly 20080925 V2
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Grizzly Comet Aquarium Paris
Grizzly Comet Aquarium ParisGrizzly Comet Aquarium Paris
Grizzly Comet Aquarium Paris
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
gRPC in Go
gRPC in GogRPC in Go
gRPC in Go
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
GWT
GWTGWT
GWT
 
Gooogle Web Toolkit
Gooogle Web ToolkitGooogle Web Toolkit
Gooogle Web Toolkit
 
Magento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 SummaryMagento 2 Seminar - Anton Kril - Magento 2 Summary
Magento 2 Seminar - Anton Kril - Magento 2 Summary
 
DWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A TutorialDWR, Hibernate and Dojo.E - A Tutorial
DWR, Hibernate and Dojo.E - A Tutorial
 
Device Simulator with Akka
Device Simulator with AkkaDevice Simulator with Akka
Device Simulator with Akka
 
Camel one v3-6
Camel one v3-6Camel one v3-6
Camel one v3-6
 
#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run#win8aca : How and when metro style apps run
#win8aca : How and when metro style apps run
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享
 

Mehr von Eduardo Pelegri-Llopart

Mehr von Eduardo Pelegri-Llopart (20)

Juggling at freenome
Juggling   at freenomeJuggling   at freenome
Juggling at freenome
 
Csumb capstone-fall2016
Csumb capstone-fall2016Csumb capstone-fall2016
Csumb capstone-fall2016
 
Digital activitymanagement
Digital activitymanagementDigital activitymanagement
Digital activitymanagement
 
Progress next iot_pelegri
Progress next iot_pelegriProgress next iot_pelegri
Progress next iot_pelegri
 
Pelegri Desarrollando en una nueva era de software
Pelegri   Desarrollando en una nueva era de software Pelegri   Desarrollando en una nueva era de software
Pelegri Desarrollando en una nueva era de software
 
Market trends in IT - exchange cala - October 2015
Market trends in IT - exchange cala - October 2015Market trends in IT - exchange cala - October 2015
Market trends in IT - exchange cala - October 2015
 
The impact of IOT - exchange cala - 2015
The impact of IOT - exchange cala - 2015The impact of IOT - exchange cala - 2015
The impact of IOT - exchange cala - 2015
 
IOT - Presentation to PEP @ Progress
IOT - Presentation to PEP @ ProgressIOT - Presentation to PEP @ Progress
IOT - Presentation to PEP @ Progress
 
Node.js as an IOT Bridge
Node.js as an IOT BridgeNode.js as an IOT Bridge
Node.js as an IOT Bridge
 
What is IoT and how Modulus and Pacific can Help - Featuring Node.js and Roll...
What is IoT and how Modulus and Pacific can Help - Featuring Node.js and Roll...What is IoT and how Modulus and Pacific can Help - Featuring Node.js and Roll...
What is IoT and how Modulus and Pacific can Help - Featuring Node.js and Roll...
 
What is the Internet of Things and How it Impacts You
What is the Internet of Things and How it Impacts YouWhat is the Internet of Things and How it Impacts You
What is the Internet of Things and How it Impacts You
 
Community Update 25 Mar2010 - English
Community Update 25 Mar2010 - EnglishCommunity Update 25 Mar2010 - English
Community Update 25 Mar2010 - English
 
GlassFish Community Update 25 Mar2010
GlassFish Community Update 25 Mar2010GlassFish Community Update 25 Mar2010
GlassFish Community Update 25 Mar2010
 
Glass Fish Portfolio C1 West V3.Mini
Glass Fish Portfolio C1 West V3.MiniGlass Fish Portfolio C1 West V3.Mini
Glass Fish Portfolio C1 West V3.Mini
 
Virtual Box Aquarium May09
Virtual Box Aquarium May09Virtual Box Aquarium May09
Virtual Box Aquarium May09
 
Introduction To Web Beans
Introduction To Web BeansIntroduction To Web Beans
Introduction To Web Beans
 
Ehcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage PatternsEhcache Architecture, Features And Usage Patterns
Ehcache Architecture, Features And Usage Patterns
 
OpenDS Primer Aquarium
OpenDS Primer AquariumOpenDS Primer Aquarium
OpenDS Primer Aquarium
 
Fuji Overview
Fuji OverviewFuji Overview
Fuji Overview
 
Nuxeo 5.2 Glassfish
Nuxeo 5.2 GlassfishNuxeo 5.2 Glassfish
Nuxeo 5.2 Glassfish
 

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)

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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+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...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

20090315 Comet

  • 1. Writing Comet Web Application using GlassFish Jeanfrancois Arcand Sun Microsystems 1
  • 2. Agenda • What is Comet (aka Ajax Push) • What is Grizzly Comet Framework • Demo screan cast • What is Atmosphere • Summary • More info > Tutorials > Project Grizzly 2
  • 3. What is Ajax Push, exactly? Bending the rules of HTTP. 3
  • 4. Ajax Poll vs Ajax Push Bending the rules of HTTP. •  Poll: > Send a request to the server every X seconds. > The response is “empty” if there is no update. •  Long Poll: > Send a request to the server, wait for an event to happen, then send the response. > The response is never empty. > HTTP specification satisfied: indistinguishable from “slow” server •  Http Streaming: > Send a request, wait for events, stream multi-part/chunked response, and then wait for the events. > The response is continually appended to. 4
  • 6. Introduction to Grizzly Comet • Grizzly Comet is a framework that ship with GlassFish v2 and v3, and can also be embedded into any application using the Grizzly Embed interface • The Grizzly Comet Framework includes a set of components that can be used for building Comet based application: > Grizzly Comet, Continuation, Grizzlet, Messages Bus, • It also support the JSON based Bayeux Protocol (aka Comet) 6
  • 7. Grizzly Comet Framework • The Framework contains the classes required to add support for Comet in a Web Application • Main classes to interact with (details next): > CometContext > CometHandler > NotificationHandler 7
  • 8. Grizzly Comet Framework How it works send push filters send Push data 8
  • 9. Grizzly Comet in 3 steps •  Suspend: >  addCometHandler(CometHandler) •  Push: >  notify(<? extends Object>) // All suspended responses >  notify(<? extends Object>, CometHandler) // Only one •  Write: Inside CometHandler.onEvent() >  PrintWriter.write(CometEvent.attachment()); •  Resume: >  resumeCometHandler(CometHandler) 9
  • 10. CometContext •  A CometContext is a distribution mechanism for pushing messages that are delivered to multiple subscribers called CometHandler (a la JMS Queue/ Topic). •  All http response registered to a CometContext automatically becomes suspended, waiting for an event (a push) to happens. •  A browser receives only those messages published after the client suspend its response via CometContext. 10
  • 11. CometContext – 5 APIs to remember •  addCometHandler: Suspend the current response, await for data to be transformed. •  resumeCometHandler: Resume the current response, and re-enable the normal http keep-alive mechanism. •  notify(..): Dispatch data to the suspended response. •  registerAsyncRead: Allow a suspended response to read asynchronously bytes. e.g avoid blocking waiting for the client to send all the bytes. •  registerAsyncWrite: Allow a suspended response to write asynchronously bytes. 11
  • 12. Creating a CometContext /** * Create a {@link CometContext} * @param id - The topic associated with the {@link CometContext} * @return {@link CometContext} */ private CometContext createCometContext(String id){ CometEngine cometEngine = CometEngine.getEngine(); CometContext ctx = cometEngine.register(id); ctx.setExpirationDelay(idleTimeBeforeForcingResume); return ctx; } 12
  • 13. Suspending an Http Response // Create a CometContext based on this session id. twitterContext = createCometContext(sessionId); // Create and register a CometHandler. ReflectorCometHandler handler = new ReflectorCometHandler (true,startingMessage,endingMessage); // Pass the ‘suspended’ PrintWriter that can be used to write response // back to the client handler.attach(response.getWriter()); twitterContext.addCometHandler(handler); 13
  • 14. Resuming an Http Response if (event.getType() != CometEvent.READ) { printWriter.println(event.attachment()); printWriter.flush(); // long polling will resume automatically after the first event, // streaming will kept the response suspended if (!useStreaming){ event.getCometContext().resumeCometHandler(this); } } 14
  • 15. Sharing data between suspended responses twitterContext.notify(BEGIN_SCRIPT_TAG + toJsonp(quot;You are now following quot;, message) + END_SCRIPT_TAG, CometEvent.NOTIFY, ch); CometHandler twitterHandler = (CometHandler)followerContext.getAttribute(quot;twitterHandlerquot;); followerContext.notify(BEGIN_SCRIPT_TAG + toJsonp(name, quot; is now following quot; + message) + END_SCRIPT_TAG, CometEvent.NOTIFY, twitterHandler); // Notify other registered CometHandler. twitterContext.notify(quot;<script id='comet_quot; + counter++ + quot;'>quot; + quot;window.parent.quot; + callback + quot;(quot; + message + quot;);</script>quot;); 15
  • 16. Writing data to a suspended response public void onEvent(CometEvent event) throws IOException { try { if (event.getType() != CometEvent.READ) { printWriter.println(event.attachment()); printWriter.flush(); if (!useStreaming){ event.getCometContext().resumeCometHandler(this); } } } catch (Throwable t) { throw new IOException(t.getMessage()); } } 16
  • 17. CometHandler • The CometHandler is the master piece of a Grizzly Comet based application. • A CometHandler contains the business logic of what will be pushed back to the browser. • A CometHandler might be invoked by the Container: > When the response is suspended or resumed > When a push operation happens > When a I/O operations are ready to be process (asynchronous read or write) > When the browser close the connection. 17
  • 18. CometHandler API //Invoked when CometContext.notify() is called public void onEvent(CometEvent ce); // Invoked when the browser close a suspended // connection or when the suspend timeout expire. public void onInterrupt(CometEvent ce); // Invoked when the request is suspended public void onInitialize(CometEvent ce); // Invoked when the request is resumed public void onTerminate(CometEvent ce); 18
  • 19. Example: ReflectorCometHandler /** * Write {@link CometEvent#attachment} and resume the connection if * {@link ReflectorCometHandler#useStreaming} is <tt>false</tt> * @param event * @throws java.io.IOException */ public void onEvent(CometEvent event) throws IOException { try { if (event.getType() != CometEvent.READ) { printWriter.println(event.attachment()); printWriter.flush(); if (!useStreaming){ event.getCometContext().resumeCometHandler(this); } } } catch (Throwable t) { throw new IOException(t.getMessage()); } } 19
  • 20. NotificationHandler •  The NotificationHandler object is the life saver when writing Comet application •  This is inside that object that you will decide to what to do with the push operation: – Throttle: If too many push occurs simultaneously, should we delay them? – Aggregate: Should we cache push operations and aggregate them to avoid overloading the network? – Filter: Should all messages by pushed back to the client. – Should a thread pool be used to improve the push speed operation? Should a JMS backed be used to deliver the message? •  The DefaultNotificationHandler push all messages. 20
  • 21. NotificationHandler – Main API /** * Set to <tt>true</tt> if the invoker of notify() should block when * notifying Comet Handlers. */ public void setBlockingNotification(boolean blockingNotification); /** * Notify all {@link CometHandler}. * @param cometEvent the CometEvent used to notify CometHandler * @param iteratorHandlers An iterator over a list of CometHandler */ public void notify(CometEvent cometEvent,Iterator<CometHandler> iteratorHandlers) throws IOException; 21
  • 22. NotificationHandler - Filtering public void notify(CometEvent<String> ce,List<CometHandler> l){ escape(ce); discard(ce); } 22
  • 23. NotificationHandler - Clustering @Override public void notify(CometEvent cometEvent, Iterator<CometHandler> iteratorHandlers) throws IOException { try { // Push to the cluster ObjectMessage message = jmsSession.createObjectMessage(cometEvent); messageproducer.send(message); // Push locally super.notify(cometEvent,iteratorHandlers); } catch (JMSException ex) { throw new IOException(quot;comet JMS send failed quot;, ex); } } 23
  • 24. Demo 24
  • 25. How the client looks like? • The client open a single connection to the server > Use http-streaming • The Flickr Letters are powered by the a jMaki library which use http-streaming. • The Follower/Following updates are made using a long poll connection, powered by the behavior.js framework. 25
  • 26. How the client looks like? • The client open a single connection to the server > Use http-streaming • The Flickr Letters are powered by the a jMaki library which use http-streaming. • The Follower/Following updates are made using a long poll connection, powered by the behavior.js and prototype.js framework. 26
  • 27. What is Project Atmosphere The state of Comet (Ajax Push) right now •  Since July 2006 the Grizzly Comet Framework and its extensions’ popularity keep increasing. >  Among the most popular framework right now. •  Comet techniques aren't standardized among Web Container >  Grizzly Comet applications aren't portable (cannot run on Tomcat nor Jetty)‫‏‬ •  Servlet 3.0 will supports only a subset of Comet >  No async I/O, No pushing functionalities >  Way too complicated (this is my personal opinion ) >  Support will takes time (Spec to be finalized)‫‏‬ 27
  • 28. What is Project Atmosphere (con't)‫‏‬ So... • Atmosphere is a POJO based framework using Inversion of Control (IoC) to bring Comet to the masses. • A framework which can run on any Java based Web Server.....without having to wait for Servlet 3.0 or without the needs to learn how Comet support has been differently implemented by current Web Server supporting Comet • Run on top of Servlet 2.5 compliant Web Server 28
  • 29. What is Project Atmosphere (con't)‫‏‬ Extends and improve the Grizzlet concept.... • Grizzlet is a POJO based approach for writing Comet application. > Grizzlet only runs on top of the Grizzly Comet Framework right now > Grizzly community asked many times to have the concept ported to other Web Server • Evolve the Grizzlet...and make it the core of Project Atmosphere. • Currently at version 0.1, with support for GlassFish, Tomcat and Jetty. 29
  • 30. Architecture Reuse experience and code...from Grizzly Comet to Jersey! Grizzlet Atmosphere re-usable (Atmosphere POJO)‫‏‬ Components library Jersey's Injection Provider, IoC Support, and more.... Atmosphere Servlet Runtime Engine Tomcat Comet Jetty Comet Blocking WS Grizzly Comet User defined Atmosphere Component 30
  • 31. Example Easy of use of Jersey, power of Grizzly Comet @Grizzlet(Grizzlet.Scope.APPLICATION)‫‏‬ @Path(quot;myGrizzletquot;)‫‏‬ public class MyGrizzlet{ @Suspend(6000)‫‏‬ @GET @Push public String onGet(){ return quot;Suspending the connectionquot;; } @POST @Push public String onPost(@Context HttpServletRequest req, @Context HttpServletResponse res) throws IOException{ res.setStatus(200); res.getWriter().println(quot;OK, info pushedquot;); return req.getParameter(quot;chatMessagequot;); } 31
  • 32. Demo 32
  • 33. Summary The Asynchronous Web Revolution is Now •  The Asynchronous Web will revolutionize human interaction •  Writing Comet application with GlassFish is easy! 33
  • 34. For More Information http://twitter.com/project_grizzly •  Getting Started with Grizzly Comet Framework on GlassFish >  http://weblogs.java.net/blog/jfarcand/archive/2008/11/writing_a_twitt.html >  http://weblogs.java.net/blog/jfarcand/archive/2008/04/the_hitchhikers.html >  http://weblogs.java.net/blog/jfarcand/archive/2006/10/writting_a_come.html •  GlassFish’s Comet Official Documentation: >  http://docs.sun.com/app/docs/doc/820-4496/ggrgy •  GlassFish: http://glassfish.dev.java.net •  Grizzly: http://grizzly.dev.java.net 34
  • 35. What is Project Grizzly •  Suite of embeddable components, which include:   >  Framework: A Framework for building network I/O applications   >  Http: A Framework for building HTTP based applications   >  Comet: A Framework for building AjaxPush/Comet applications   >  Cometd/Bayeux: The JSON based Bayeux protocol.   >  Servlet: A tiny Servlet Container with a programmatic API (not compliant)   >  HttpService OSGi implementation: OSGi enabled WebServer •  Components only available for via GlassFish Enterprise (not OSS)   >  Cluster Comet: Grizzly Comet cluster enabled. •  Who is using Grizzly: GlassFish v2, GlassFish v3 (JRuby, Grails, Admin, Servlet Container, V3 kernel build on top of it), Jetty, Jersey, JXTA, Netbeans, RESTlet, JXTA, Phobos, OpenESB, Sailfin, Futjisu, Sun Shared Shell, 4Home, Convergence, Ericsson, Nortel, Eventgnosis…and many many more! 35