<?xml version="1.0"?>
<rss version="2.0">
<channel>
  <title>The Kitchen in the Zoo - java ee tag</title>
  <link>http://blog.maxant.co.uk:80/pebble/tags/java ee/</link>
  <description>&lt;small&gt;A blog where Ant writes about anything he finds interesting! &lt;a href=&#039;http://www.linkedin.com/in/maxant&#039;&gt;&lt;font color=&#039;white&#039;&gt;Who is Ant?&lt;/font&gt;&lt;/a&gt;      &lt;a href=&#039;/pebble/pages/copyright.html&#039;&gt;&lt;font color=&#039;white&#039;&gt;Copyright 2005-2012 Ant Kutschera&lt;/font&gt;&lt;/a&gt;&lt;/small&gt;</description>
  <language>en</language>
  <copyright>Ant Kutschera</copyright>
  <lastBuildDate>Thu, 10 May 2012 20:07:00 GMT</lastBuildDate>
  <generator>Pebble (http://pebble.sourceforge.net)</generator>
  <docs>http://backend.userland.com/rss</docs>
  
  
  <item>
    <title>JSR-299 &amp; @Produces</title>
    <link>http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html</link>
    
      
        <description>
          I&#039;ve been reading &lt;a href=&#039;http://www.jcp.org/en/jsr/detail?id=299&#039; target=&#039;_blank&#039;&gt;JSR-299&lt;/a&gt; and I have a few thoughts.&lt;br&gt;
&lt;br&gt;
First, a quote from chapter 1:&lt;br&gt;
&lt;br&gt;
&lt;i&gt;&#034;The use of these services significantly simplifies the task of creating Java EE applications by integrating the Java EE web
tier with Java EE enterprise services. In particular, EJB components may be used as JSF managed beans, thus integrating
the programming models of EJB and JSF.&#034;&lt;/i&gt;&lt;br&gt;
&lt;br&gt;
The second sentence made my ears prick up.  Do I really want EJBs to be the backing beans of web pages?  To me that sounds like one is mixing up responsibilities in MVC.  Sure, there are people out there who say that an MVC Controller should be skinny and the model should be fat (&lt;a href=&#039;http://www.youtube.com/watch?v=91C7ax0UAAc&#039; target=&#039;_blank&#039;&gt;youtube ad&lt;/a&gt;).  Perhaps I&#039;m old school, but I prefer my JSF page to have a backing bean which is my view model and deals with presentation specific logic, and when it needs transaction and security support, it can call through to an EJB which deals with more businessy things.&lt;br&gt;
&lt;br&gt;
The JSR then goes on to introduce the &lt;code&gt;@Produces&lt;/code&gt; annotation.  I don&#039;t like that annotation and the rest of this blog posting is about why.&lt;br&gt;
&lt;br&gt;
When I need an object, like a service or a resource, I can get the container to inject it for me.  Typically, I use the &lt;code&gt;@Inject&lt;/code&gt;, &lt;code&gt;@EJB&lt;/code&gt;, &lt;code&gt;@Resource&lt;/code&gt; or &lt;code&gt;@PersistenceContext&lt;/code&gt; annotations.  In the object which has such things injected, I can write code which uses those objects.  I let the container compose my object using those pieces and other beans.  There are many advantages, like having code which is easily testable because I can compose the object out of mocks if required, or like being able to configure its composition rather than hard coding it.  And we are all used to composing objects like this, from the earliest days of Spring, if not before.&lt;br&gt;
&lt;br&gt;
Now, with &lt;code&gt;@Produces&lt;/code&gt;, we have a new way to declare where things come from.  Take the example in the JSR, where a &lt;code&gt;Login&lt;/code&gt; bean is shown (chapter 1). 
The Login bean &#034;produces&#034; the current user (page 4).  Well, let&#039;s start with some code:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Produces @LoggedIn User getCurrentUser()&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
If I read that code out loud, I say something with a similar meaning to: &lt;i&gt;&#034;The bean called Login produces the currently logged in user&#034;.&lt;/i&gt;&lt;br&gt;
&lt;br&gt;
Well, that doesn&#039;t make too much sense to me, because coming at the design from a pure OO point of view, starting with use-cases, there is no Login bean mentioned in the use case, and even if there were, it does not &#034;produce&#034; the user!  The user exists before they login to the software.  They are simply authenticated and perhaps authorised after login.  The login component of the software (which could be represented by the Login bean) can provide the details of the currently logged in user.  The syntax used in that code above has a poor semantic meaning, in my view.&lt;br&gt;
&lt;br&gt;
So if this is the modern trendy way of passing information around in a JSF app, I have to ask myself whether we were not able to do such things in the past?  Or was it really hard to program before we had the &lt;code&gt;@Produces&lt;/code&gt; annotation?  Let&#039;s look at one solution; some code in a bean which needs to know the logged in user.&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Inject Login loginBean;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
To use that, the Login bean would need to be declared as being &lt;code&gt;@SessionScoped&lt;/code&gt;, and guess what - it is already marked so in the JSR example.&lt;br&gt;
&lt;br&gt;
To access the current user, I would simply write code like this:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;loginBean.getCurrentUser().getName() blah blah&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
Simple huh?&lt;br&gt;
&lt;br&gt;
If you don&#039;t like the idea of injecting the Login bean, then why not simply create a session scoped bean called &#034;&lt;code&gt;CurrentUser&lt;/code&gt;&#034; and during login, set the authenticated user attributes into that session scoped bean?  Why go to the lengths of adding yet another way of injecting objects, namely the &lt;code&gt;@Produces&lt;/code&gt; annotation?  Because there is a different way of doing injection, the whole mechanism has become more complex.  I believe it is these types of complexity which cause newbies to give up Java EE before fully understanding it, and which cause existing Java advocates to give up and move to Grails, etc.&lt;br&gt;
&lt;br&gt;
To go with the &lt;code&gt;@Produces&lt;/code&gt; annotation, we are given qualifiers.  Qualifiers are effectively type safe names used for filtering, and as such, potentially better than String constants in an interface somewhere used in conjunction with an &lt;code&gt;@Named&lt;/code&gt; annotation.  Here is why I don&#039;t think Qualifiers should be used as the norm, but rather as the exception.  The class of object being injected should have a suitable name to tell the reader what is going on.  Consider this code, which injects the current user which the login bean produces:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Inject @LoggedIn User currentUser;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
There is unnecessary triplication going on in that line.  &#034;LoggedIn&#034;, &#034;User&#034; and &#034;currentUser&#034;.  In the ideal world, I don&#039;t want three names here, I want one.  Java forces me to declare the type, which is actually not really that necessary, because the compiler could, using conventions, infer the type from the name.  But let&#039;s not go there, and instead accept that we have to declare a type.  Why on earth then, do I want to additionally declare a qualifier?  I don&#039;t, it&#039;s a waste of finger energy.  Only when there is ambiguity would I be required to use a qualifier.  But if I have a session scoped model, which contained the user, I could spare myself the energy of using a qualifier.  I would simply inject the model bean and pull the current user out of it.  That is what I have been doing for years without a problem.  My Mum always told me not to fix something which isn&#039;t broken.&lt;br&gt;
&lt;br&gt;
At this &lt;a target=&#039;_blank&#039; href=&#039;https://docs.jboss.org/author/display/AS7/Getting+Started+Developing+Applications+Guide&#039;&gt;JBoss getting started guide&lt;/a&gt;, they give an example of producing a random number, with code like this (in the producer):&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Produces @Random int next() {&lt;/code&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;return getRandom().nextInt(maxNumber - 1) + 1;&lt;/code&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;}&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
and this code in the consumer:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Inject @Random int someRandomNumber;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
Sure, it&#039;s a toy example.  But what is wrong with injecting the &lt;code&gt;Generator&lt;/code&gt; bean (which contains that producer method), and calling the method on it which generates the random number?  I could even work with &lt;code&gt;@Alternative&lt;/code&gt; if I wanted to decide on the actual implementation at deployment time.&lt;br&gt;
&lt;br&gt;
For me, injecting the bean, rather than the value is very important for readability.  It gives the reader (maintainer) contextual information about where that value is coming from.  In my mind, the following code is much better.  It is quicker to write, because I don&#039;t need to create a qualifier annotation.&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Inject Generator generator;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
And then in that class, some code to use the generator:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;generator.nextRandomInt();&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
Section 1.3.3 of the JSR gives an example of setting up the entity managers for injection into beans:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Produces @PersistenceContext(unitName=&#034;UserData&#034;) @Users&lt;/code&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;EntityManager userDatabaseEntityManager;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
And then here, the code which uses that entity manager:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@Inject @Users EntityManager userDatabaseEntityManager;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
Oh, and don&#039;t forget the code for the &lt;code&gt;@Users&lt;/code&gt; annotation...  I end up with two extra files (the annotation and the producer).  Is all that code really better than the following, which is simply put into a bean requiring the entity manager:&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;@PersistenceContext(unitName=Units.UserData)&lt;/code&gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;code&gt;EntityManager userDatabaseEntityManager;&lt;/code&gt;&lt;br&gt;
&lt;br&gt;
I&#039;m just not convinced that the &#034;modern&#034; &amp;amp; trendy, yet complex JSR-299 way of doing it is better.&lt;br&gt;
&lt;br&gt;
Section 3.3 then goes on to tell us a bit more about why producers exist and in which circumstances we might want to use them:&lt;br&gt;
&lt;br&gt;
&lt;i&gt; - the objects to be injected are not required to be instances of beans&lt;/i&gt;&lt;br&gt;
&lt;br&gt;
Since almost every class is now a bean, I am hard pushed to think of a case where I could not create a bean if I wanted something injected.&lt;br&gt;
&lt;br&gt;
&lt;i&gt; - the concrete type of the objects to be injected may vary at runtime&lt;/i&gt;&lt;br&gt;
&lt;br&gt;
This is exactly what &lt;code&gt;@Alternative&lt;/code&gt; and &lt;code&gt;@Specialize&lt;/code&gt; annotations are for, and I do not need to use a producer to vary the concrete runtime implementation.&lt;br&gt;
&lt;br&gt;
&lt;i&gt; - the objects require some custom initialization that is not performed by the bean constructor&lt;/i&gt;&lt;br&gt;
&lt;br&gt;
Adding the &lt;code&gt;@Inject&lt;/code&gt; annotation to a constructor tells the container which constructor to call when special construction is required.  How can a producer produce something which a bean couldn&#039;t?&lt;br&gt;
&lt;br&gt;
Section 3.4.2 then talks about declaring producer fields.  The example they give shows the field having default (package) visibility, yet as far as I can tell, any bean in the deployment bundle, even one outside the producers package, can use the &#034;product&#034;.  This is a little like indecently assaulting Java.&lt;br&gt;
&lt;br&gt;
So to summarise, I guess I just want to put out a plea to future spec authors.  If you can&#039;t work out a way to do things simply, especially if we already have that mechanism, please don&#039;t go and make things more complicated than they need to be.  I don&#039;t want to learn 92 pages of JSR just to be good at using beans, when I already have to learn thousands of other pages of JSR just to get working with Java EE.&lt;br&gt;
&lt;br&gt;
&amp;copy; 2011, Ant Kutschera
&lt;br&gt;
&lt;br&gt;
&lt;div class=&#034;tags&#034;&gt;&lt;span&gt;Social Bookmarks : &lt;/span&gt;&amp;nbsp;&lt;a href=&#034;http://slashdot.org/bookmark.pl?url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Slash Dot&#034;&gt;&lt;img src=&#034;common/images/slashdot.png&#034; alt=&#034;Add this post to Slashdot&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://digg.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Digg this post&#034;&gt;&lt;img src=&#034;common/images/digg.png&#034; alt=&#034;Add this post to Digg&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://reddit.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Reddit&#034;&gt;&lt;img src=&#034;common/images/reddit.png&#034; alt=&#034;Add this post to Reddit&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://del.icio.us/post?url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Save this post to Del.icio.us&#034;&gt;&lt;img src=&#034;common/images/delicious.png&#034; alt=&#034;Add this post to Delicious&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.stumbleupon.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Stumble this post&#034;&gt;&lt;img src=&#034;common/images/stumbleupon.png&#034; alt=&#034;Add this post to Stumble it&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.google.com/bookmarks/mark?op=edit&amp;amp;bkmk=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Google&#034;&gt;&lt;img src=&#034;common/images/google.png&#034; alt=&#034;Add this post to Google&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://technorati.com/faves?add=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Technorati&#034;&gt;&lt;img src=&#034;common/images/technorati.png&#034; alt=&#034;Add this post to Technorati&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.bloglines.com/sub/http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Bloglines&#034;&gt;&lt;img src=&#034;common/images/bloglines.png&#034; alt=&#034;Add this post to Bloglines&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.facebook.com/share.php?u=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Facebook&#034;&gt;&lt;img src=&#034;common/images/facebook.png&#034; alt=&#034;Add this post to Facebook&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.furl.net/storeIt.jsp?u=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;t=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Furl&#034;&gt;&lt;img src=&#034;common/images/furl.png&#034; alt=&#034;Add this post to Furl&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;amp;url=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;title=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Windows Live&#034;&gt;&lt;img src=&#034;common/images/windowslive.png&#034; alt=&#034;Add this post to Windows Live&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;amp;u=http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html&amp;amp;t=JSR-299+%26+%40Produces&#034; target=&#034;_blank&#034; title=&#034;Add this post to Yahoo!&#034;&gt;&lt;img src=&#034;common/images/yahoo.png&#034; alt=&#034;Add this post to Yahoo!&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&lt;/div&gt;
        </description>
      
      
    
    
    
    <comments>http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html#comments</comments>
    <guid isPermaLink="true">http://blog.maxant.co.uk:80/pebble/2011/11/07/1320702240000.html</guid>
    <pubDate>Mon, 07 Nov 2011 21:44:00 GMT</pubDate>
  </item>
  
  <item>
    <title>Tomcat, WebSockets, HTML5, jWebSockets, JSR-340, JSON and more</title>
    <link>http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html</link>
    
      
        <description>
          &lt;p&gt;On my recent excursion into non-blocking servers I came across Comet, server push technologies and then Web Sockets. I was late arriving at the Comet party, but I think I have arrived at the Web Sockets party just in time.   The final standard is still being evovled and at the time of writing, the only browser supporting it by default is Chrome. So to get started, I had a look at what was around.  Initially, I wasn&#039;t going to write a blog article about it, I just wanted to learn about this new thing.&lt;br /&gt;
&lt;br /&gt;
My only requirement was that the server implementation was Java based.  The reason is simple - my entire technology stack is based on Java EE  and I want to be able to integrate all my existing stuff into any new server, without the need for an integration bus.  I like being able to  drop a JAR file from one project into another one and to be up and running immediately.&lt;br /&gt;
&lt;br /&gt;
So I had a quick look at jWebSockets, Grizzly (Glassfish), Jetty and Caucho&#039;s Resin.  All similar, yet all somewhat different.  Most different, was  jWebSockets, because they have gone to the extent of building their own server, instead of basing their solution on an existing server.  I had a  good long rant about that kind of thing when I blogged about node.js, so I won&#039;t start again.  But jWebSockets has a real issue to face in the  coming years.  &lt;a target=&#034;_blank&#034; href=&#034;http://www.jcp.org/en/jsr/detail?id=340&#034;&gt;JSR-340&lt;/a&gt; talks about support for web technologies based around HTML5 and there is talk that this JSR will be part of Servlet 3.1 and be included in Java EE 7 at the end of next year.  If that happens,  jWebScokets will have the problem that their server implementation will become deprecated.  And because their server doesn&#039;t offer anything else from Java EE, it is likely to lose a large part of it&#039;s market share.  Don&#039;t get me wrong, they are still innovating on the client side, with a bridge to allow any browser to use websockets, and creating things like Java SE web socket clients.  But server side isn&#039;t looking so hot -  just take a look at the huge config file which you need to supply to get your plugins to work.&lt;br /&gt;
&lt;br /&gt;
Anyway, I wasn&#039;t really enthusiastic about any of the solutions I saw.  Some are servlet based (which is good), and all rely on you creating a  new instance of a  listener, handler, plugin or whatever they choose to call it.  But what struck me was, by doing that, you lose the benefits of running  inside the container.  What I mean by this is that if you think about a servlet or an EJB (and I&#039;m talking Java EE 6 and beyond here),  the components you write have the benefit that the container can take care of cross cutting concerns like transactions, security and concurrency as  well as provide you with injected resources, so that all you have left to do is write business code.  So the reason I was not enthusiastic about  any of the solutions listed above, was that what I felt to be glaringly obvious, has been missed.  Sure, an inner class within a servlet could  make use of resources from the servlet, but nothing I found on the net suggested that should be the normal way to program a web socket solution. And I&#039;m not convinced that a reference in an inner class to a resource from the servlet couldn&#039;t go stale between messages received.   I would rather the container always injected fresh resources just before my event handling method gets called, just as happens in the lifecycle of a servlet or EJB instance.  Just think about a database connection timeout occurring between messages?  If the container ensured the connection was always fresh, then the app developer wouldn&#039;t need to worry about technicalities.&lt;br /&gt;
&lt;br /&gt;
An &lt;code&gt;HttpServlet&lt;/code&gt; has methods for handling GETs, POSTs, et al.  Why shouldn&#039;t a component handling a Web Socket not be a  &lt;code&gt;WebSocketServlet&lt;/code&gt; and have methods for handling the events for handshaking, opening, messaging, closing and error handling? I would benefit, because the servlet could have resources injected into it before the event handler methods get called, and the container  could start any transactions that are required, or check security, etc.&lt;br /&gt;
&lt;br /&gt;
So without realising that this would actually be quite hard to implement, I set upon taking Tomcat 7 apart, and building web sockets into it, in  a way which fulfilled my requirements.&lt;br /&gt;
&lt;br /&gt;
What resulted was (what I think is) a pretty sexy servlet solution.  Please take a few minutes to study the  code and especially the comments below, because it is the essence of this article. &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 300px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
/**
 * a demo of what a web socket servlet could look like
 */
@WebServlet(urlPatterns={&amp;quot;/TestServlet&amp;quot;})
@ServletSecurity(@HttpConstraint(rolesAllowed = &amp;quot;registered&amp;quot;))
public class TestServlet extends WebSocketsServlet&amp;lt;CommandContainer&amp;gt; {

  @WebServiceRef
  private PricingSystem pricingSystem;
  
  @EJB
  private SalesLog salesLog;
  
  @Override
  protected void doJSONMessage(
      WebSocketsServletRequest&amp;lt;CommandContainer&amp;gt; request,
      WebSocketsServletResponse response) throws IOException {
    
    //see how generics is helping me here, 
    //when i grab the request payload?
    //CommandContainer is a class defined in the app!
    CommandContainer c = request.getDataObject();
    
    if(&amp;quot;CLOSE&amp;quot;.equals(c.getCommand())){
    
      //closing connection to client
      response.close();

      //handle updates to say my model or whatever      
      actualClose(EventSubType.SESSION_END, request.getSession());
      
      return;

    }else if(&amp;quot;PRICE&amp;quot;.equals(c.getCommand())){

      //hey wow - a call to an injected web service!
      BigDecimal price = pricingSystem.getPrice(c.getData());
      c.setResult(price.toString());

    }else if(&amp;quot;BUY&amp;quot;.equals(c.getCommand())){
      
      //data is e.g. GOOG,100@200.25 - equally I could have 
      //put it in the model
      int idx = c.getData().indexOf(&#039;,&#039;);
      String shareCode = c.getData().substring(0, idx);
      idx = c.getData().indexOf(&#039;@&#039;);
      String numShares = c.getData().substring(shareCode.length()+1, idx);
      String price = c.getData().substring(idx+1, c.getData().length()-1);

      //awesome - a call to an injected EJB!
      salesLog.logPurchase(shareCode, 
                           new BigDecimal(price), 
                           Integer.parseInt(numShares));
      
      //and again cool - I can access the logged in user
      //in a familiar way (security)
      c.setResult(&amp;quot;sold &amp;quot; + numShares + &amp;quot; of &amp;quot; + shareCode + 
                  &amp;quot; for &amp;quot; + request.getUserPrincipal().getName());

    }else{
      
      c.setResult(&amp;quot;unknown command &amp;quot; + c.getCommand());
      
    }

    log(&amp;quot;handled command &amp;quot; + c.getCommand() + &amp;quot; on session &amp;quot; + 
                 request.getSession().getId() + &amp;quot;: &amp;quot; + c.getResult());
  
    //the response takes care of the outputstream, framing, 
    //marshalling, etc - my life is really easy now!
    response.sendJSONResponse(c);
  }

  @Override
  protected void doError(EventSubType eventSubType, 
                         WebSocketsSession session, 
                         Exception e) {

    System.out.println(&amp;quot;error: &amp;quot; + eventSubType + 
                       &amp;quot; on session &amp;quot; + session.getId() + 
                       &amp;quot;.  ex was: &amp;quot; + e);
  }

  @Override
  public void doClose(EventSubType eventSubType, 
                      WebSocketsSession session) {

    actualClose(eventSubType, session);
  }

  /** 
   * this is a method where we might do stuff like
   * tidy up our model, free resources, etc.
   */  
  private void actualClose(EventSubType eventSubType,
                           WebSocketsSession session) {
  
    System.out.println(&amp;quot;closed session &amp;quot; + 
                       session.getId() + &amp;quot;: &amp;quot; + eventSubType);
  }

}
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
To me, this is what a serverside web socket component should look like.  It is really similar to a sevlet or an EJB or a web service - things we are now familiar with.  The learning curve is mini.&lt;br /&gt;
&lt;br /&gt;
But getting Tomcat to use this thing was a little harder.  First off, my approach was to simply write a new Connector and configure it in the  &lt;code&gt;server.xml&lt;/code&gt;.  I gave it a port number and Tomcat willingly instantiated my new class:&lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 120px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
  &amp;lt;!-- NIO WebSockets connector --&amp;gt;    
    &amp;lt;Connector port=&amp;quot;8082&amp;quot; protocol=&amp;quot;org.apache.coyote.http11.WebSocketsNioProtocol&amp;quot; 
               connectionTimeout=&amp;quot;20000&amp;quot; 
             /&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
Of course, I cheated here a bit and stuck my class in a Coyote package.  To get this to work, I unzipped the Tomcat 7.0.14 source and told Eclipse where to find it.  I set up the build folder and added that to the classpath in the &lt;code&gt;catalina.bat&lt;/code&gt; batch, before any of the other  JARs on the classpath, and I did this just near the end of the batch where the call to the Java process is made.  I then ran my modified Tomcat by simply starting the catalina batch, using remote debugging to make life easier.&lt;br /&gt;
&lt;br /&gt;
I initially based my non-blocking connector on the non-blocking server which I have written and extended for my past few blog articles.   My idea was intercept any web socket handshake requests that arrived and to quickly return a self built handshake response.  I would then call the requested servlet and run it using Servlet 3.0 async support, so that the container would keep the connection open.  The messages  which the client then sent after the handshake would be handled by that servlet.&lt;br /&gt;
&lt;br /&gt;
The idea didn&#039;t quite work though, because the servlet used the async support and my connector got  callbacks from Tomcat in order for me to do stuff with threads, handle events and state changes.  I was a little lost because I didn&#039;t  understand the implementation details of Tomcat well enough, and after a while I gave up, because it was becoming clear that I would have  to build quite a lot of stuff that already existed in the HTTP connectors which shipped with Tomcat.  I came to realise that instead of  reinventing the wheel, I would do better by creating my own versions (or even sub-classes) of the Coyote &lt;code&gt;Http11NioProcessor&lt;/code&gt; and  &lt;code&gt;Http11NioProtocol&lt;/code&gt; which Tomcat uses to implement the HTTP connectors.  While these are somewhat complicated, the advantages of  specialising them are firstly that I am not reinventing the wheel, and secondly that I would get HTTPS (or WSS as it is with Web Sockets) for free (theoretically, I haven&#039;t yet tested it, but it is simply encapsulated so it should work with almost no problems).&lt;br /&gt;
&lt;br /&gt;
While it was straight forward to copy the two relevant classes, the next headache was to get the browser to accept the handshake response. I wasn&#039;t sending the handshake response as a self built String like I had with my own non-blocking connector.  Instead I was making as much use of servlet technology as I could, and building the response by setting the relevant headers on it and pushing the 16 byte response key onto the output stream of the response.  Unlike a normal HTTP response, the browser expects any handshake  responses to stick to a pretty strict specification.  Things like a simple date header in the response (which Tomcat kindly sends by default)  cause the browser to close the web socket.  So with a bit of fiddling in the &lt;code&gt;WebSocketsNioProcessor#prepareResponse()&lt;/code&gt; method, I soon had the response header looking perfect, and the browser started to play along.&lt;br /&gt;
&lt;br /&gt;
But the next problem wasn&#039;t as simple to fix.  The message handling didn&#039;t work, at all.  Connections kept getting closed quickly and I couldn&#039;t figure out what was going on.&lt;br /&gt;
&lt;br /&gt;
After a few headaches, I thought back to how Comet is implemented in Tomcat.  I slowly realised, that what I needed was to simply piggy back  the Comet infrastructure in Tomcat.  In Tomcat, you create a Comet handler by simply implementing the &lt;code&gt;CometProcessor&lt;/code&gt; interface in your servlet. The container checks during the initial request whether the servlet which will service the request implements the interface,  and if it does, the request is marked as being a comet request.  That means the container keeps the connection open and forwards future events  (e.g. bytes / messages) to the relevant handler method which your servlet implements.  I made my base servlet (&lt;code&gt;WebSocketsServlet&lt;/code&gt;) implement the &lt;code&gt;CometProcessor&lt;/code&gt; interface, and added the &lt;code&gt;event(CometEvent event)&lt;/code&gt; method using the final keyword, so that  application developers wouldn&#039;t ever think of overriding it, meaning they were protected from having the option of knowing about Comet.   This base class servlet then encapsulated the web sockets events by hiding the fact that I had cheated by using Comet.  The event method from  the Comet processor simply passes the event on to the relevant doXXX method in my base servlet, which application programmers would subclass.   This is pretty much what the &lt;code&gt;HttpServlet&lt;/code&gt; base class does in it&#039;s service method.&lt;br /&gt;
&lt;br /&gt;
So, my &lt;code&gt;WebSocketsServlet&lt;/code&gt; is the Web Sockets equivalent of the &lt;code&gt;HttpServlet&lt;/code&gt;, and as such, I put it into the  &lt;code&gt;javax.servlet.websockets&lt;/code&gt; package - i.e. to be supplied as part of the JSR which gets around to specifying the way in  which Java EE containers should handle web sockets.&lt;br /&gt;
&lt;br /&gt;
The &lt;code&gt;WebSocketsServlet&lt;/code&gt; also deals with &lt;code&gt;WebSocketServletRequest&lt;/code&gt;, &lt;code&gt;WebSocketServletResponse&lt;/code&gt; and  &lt;code&gt;WebSocketSession&lt;/code&gt; objects, rather than HTTP equivalents.  Each of these derives from the relevant &lt;code&gt;ServletXXX&lt;/code&gt; rather than &lt;code&gt;HttpServletXXX&lt;/code&gt; object, because when handling a web socket frame, it makes no sense what so ever to  be able to do things like setting the headers on the response.  Headers are only relevant to the handshake, and not anything which an  application developer needs to concern themselves with.  Again, these interfaces also sit in the &lt;code&gt;javax.servlet.websockets&lt;/code&gt; package, because they are the analagous classes belonging to the specification, rather than just Tomcat.  Sadly, the &lt;code&gt;ServletRequest&lt;/code&gt; class has stuff in it which is too specific to HTTP, like &lt;code&gt;getParameter(String)&lt;/code&gt;, as well as other stuff which I would prefer to  hide for web sockets, like &lt;code&gt;getInputStream()&lt;/code&gt;.  In order to make the &lt;code&gt;WebSocketsServletRequest&lt;/code&gt; fit really well into the  &lt;code&gt;javax&lt;/code&gt; package, I think the &lt;code&gt;ServletRequest&lt;/code&gt; might need to be broken into a super and a sub-class.  Whether that would be  possible, considering the billions of lines of Java code already out there, I don&#039;t know... &lt;br /&gt;
&lt;br /&gt;
Things like wrapping the response String (bytes) in a web socket frame (i.e. leading 0x00 and trailing 0xFF byte) are also handled transparently by the &lt;code&gt;WebSocketsServletResponse&lt;/code&gt; implementation.  In fact, I went a step further.  After listening to two interesting videos  (with Jerome Dochez, the Architect of Glassfish -  &lt;a target=&#034;_blank&#034; href=&#034;http://www.infoq.com/presentations/The-Future-of-Java-EE&#034;&gt;The Future of Java EE&lt;/a&gt; and &lt;a target=&#034;_blank&#034; href=&#034;http://www.infoq.com/interviews/jerome-dochez-ee7&#034;&gt;Jerome discusses early plans for Java EE 7&lt;/a&gt;) I was inspired by some of the things he talked about.  He spoke about not wanting to mess around with parsing strings and getting the container to handle XML and JSON.  So... I added that to Tomcat too.  You&#039;ll notice in the code near the top, the handler method which is called for handling message events is called &lt;code&gt;doJSONMessage(WebSocketsServletRequest, WebSocketsServletResponse)&lt;/code&gt; rather than say simply &lt;code&gt;doMessage&lt;/code&gt;.  The reason is, the web sockets client (running in the browser) lets you send a header  containing the protocol which it will use.  This protocol appears to be a free text which the application can choose.  In my implementation I  went with XML, JSON, TEXT and BIN (binary), although XML and BIN aren&#039;t fully implemented.  So when the client creates the web socket like this:&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;new WebSocket(&amp;quot;ws://localhost:8085/nio-websockets/TestServlet&amp;quot;, &amp;quot;JSON&amp;quot;);&lt;/code&gt; &lt;br /&gt;
&lt;br /&gt;
that JSON parameter is used by the container to decide which exact handler method in the servlet it will call.  It gets better too,  because instead of then having to manually handle the JSON string, the container does the magic, and from the &lt;code&gt;WebSocketsServletRequest&lt;/code&gt;  which is passed into the message handler method, I can retrieve the object, using the &lt;code&gt;#getDataObject()&lt;/code&gt; method.  And thanks to generics, it even passes that object back to me without me having to use a cast - the application servlet which implements the  &lt;code&gt;WebSocketsServlet&lt;/code&gt; base servlet specifies what type of data object it expects.&lt;br /&gt;
&lt;br /&gt;
How does that magic work, I hear you asking?  Well, its not that complicated.  The base servlet receives a byte array from the Comet event. It looks at the original request header and realises it should treat that request as a JSON object.  It then uses &lt;a target=&#034;_blank&#034; href=&#034;http://xstream.codehaus.org/&#034;&gt;XStream&lt;/a&gt; which knows XML as well as JSON to unmarshal the incoming request. One last bit of magic that is required is that it needs to know which class say a &amp;quot;container&amp;quot; object in the JSON string maps too - i.e. which class should it use to stick the JSON data into?  Well, XStream lets you define such aliases.  I had a think about where else this happens, and JAX-Binding does this.  So instead of the &lt;code&gt;@XmlType&lt;/code&gt; annotation for JAXB, I create the  &lt;code&gt;javax.json.bind.annotation.JsonType&lt;/code&gt; annotation, which is applied to data objects, like this:&lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 200px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
@JsonType(name=&amp;quot;container&amp;quot;)
public class CommandContainer {

  private String command;
  private String result;
  private String data;
.
.
.
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
Here, the &amp;quot;name&amp;quot; attribute of the annotation says that this class is mapped to JSON objects whose name is &amp;quot;container&amp;quot;.  So JSON like this: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 150px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
var data = {&amp;quot;container&amp;quot;:
               {&amp;quot;command&amp;quot;: &amp;quot;BUY&amp;quot;, 
                &amp;quot;data&amp;quot;: &amp;quot;GOOG,100@200.25&amp;quot;, 
                &amp;quot;result&amp;quot;: &amp;quot;sold&amp;quot;}
           };
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
is simply unmarshalled into an instance of the &lt;code&gt;CommandContainer&lt;/code&gt; class, so that the Java application can use the object immediately, rather than screwing around with strings and unmarshalling itself. The Tomcat container parses annotations during startup and I simply stuck some extra code in there to note down these mappings so that when the base servlet sets the raw data into the request, the request implementation (which is a Coyote object, rather than a javax object) can use something like XStream and these mappings to do the unmarshalling.  I had to watch out for the class loader here to - luckily XStream lets you set the classloader, because if you don&#039;t set it, you are stuck with one that doesn&#039;t know the webapp.  I simply took the classloader from the servlet context (which I got out of the &lt;code&gt;HttpServletRequest&lt;/code&gt; which the container actually passes to the Comet processor in the Comet Event), and it has a classloader which knows the webapp classes.  Regardless of whether such JSON annotated data classes are in the web-inf/classes  folder, or in jars, the container can deal with them.&lt;br /&gt;
&lt;br /&gt;
So what else is left?  Well, security for starters.  Chrome is very descent and because the Web Sockets path resides (in this case) under the same host as the one which serves the HTML containing the Javascript which opens the socket, it sends the JSESSIONID to the server during the  Web Sockets handshake.  That is really great, because so long as you had to log in to get the HTML, all web socket requests occur in the same session - so application developers have full access to the security framework supplied by Java EE!  Hence I can mark my Servlet as  requiring the user to be in a specific role in order to use it, as well as check their roles programmatically in my handler methods, using the  request object.  If the browser had not been so kind, my plan was to send the session ID to the server in the handshake as a request parameter in  the query string of the requested URL, by putting the session ID into the URL using JSP.&lt;br /&gt;
&lt;br /&gt;
On small problem with this security solution is that if the user isn&#039;t logged in, there is no way for the browser to handle the return code in the handshake properly.  At least not in Chrome.  In Chrome, the connection is simply closed, and the Javascript error console shows a  slightly cryptic message indicating that a 403 code was returned.  To avoid each browser implementing their own way to handle such problems,  the IETF web sockets specification needs to clearly state that such problems should be sent as an event to the client&#039;s &lt;code&gt;onerror&lt;/code&gt; callback method.  Let&#039;s cross our fingers hey?&lt;br /&gt;
&lt;br /&gt;
Resources, like EJBs, Entity Managers (JPA) and Web Services are also easily used - because in Java EE 6 I can inject them all using the container. While Tomcat doesn&#039;t support EJBs/WebServices per se, I still stuck some into the above example, to illustrate how such a servlet might look  in a fully fledged Java EE app server.  To make it work, I hacked Tomcat to look for those annotations and if nothing was found in the JNDI tree,  it simply injected a new instance of the class - ok, its cheating, but great for a proof of concept ;-)&lt;br /&gt;
&lt;br /&gt;
Note that while the servlet shown above might not be a typical application needing web sockets (because its a basic request/response app),  it demonstrates the way I would like to see web sockets added to Java EE.  It wouldn&#039;t be hard at all to write a servlet like this which handled a chat app, or for example an app where a user draws on their screen, and all other members see the drawing update on their screens in pretty much realtime.  I might go on to play with something like that, but  &lt;a target=&#034;_blank&#034; href=&#034;http://java.dzone.com/articles/websocket-chat&#034;&gt;this article&lt;/a&gt; already discusses some of the issues facing Web Sockets.&lt;br /&gt;
&lt;br /&gt;
A few weeks ago, I blogged about how node.js would need to provide the things like I have described in this article to become mature.  Java EE  has exactly the same challenges if it is to remain mature in the future, as new technologies are integrated into it.&lt;br /&gt;
&lt;br /&gt;
Well, that&#039;s pretty much it.  What do you think?&lt;br /&gt;
&lt;br /&gt;
Patches for Tomcat 7.0.14 are available &lt;a href=&#034;/pebble/files/tomcat-7.0.14-src-patchesForWebSockets.zip&#034;&gt;here&lt;/a&gt;.&lt;br /&gt;
The webapp containing the servlet shown above can be downloaded &lt;a href=&#034;/pebble/files/nio-websockets_20110621_2219.zip&#034;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Other useful links:&lt;/p&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://blogs.webtide.com/gregw/entry/jetty_websocket_server&#034;&gt;A blog article about Jetty websockets&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://download.java.net/maven/glassfish/org/glassfish/grizzly/grizzly-websockets/2.0/grizzly-websockets-2.0-sources.jar&#034;&gt;Source code for the Grizzly (Glassfish) web sockets solution&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://www.jcp.org/en/jsr/detail?id=340&#034;&gt;JSR-340&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://java.net/projects/servlet-spec/lists/jsr340-experts/archive/2011-05/message/16&#034;&gt;A discussion on whether Tomcat will have websockets soon&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://jwebsocket.org/&#034;&gt;jWebSockets - a standalone websocket server&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://xstream.codehaus.org/&#034;&gt;XStream - marshals/unmarshals XML &amp;amp; JSON&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://www.infoq.com/presentations/The-Future-of-Java-EE&#034;&gt;A video of the conference presentation about the future of Java EE&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://www.infoq.com/interviews/jerome-dochez-ee7&#034;&gt;A video interview with Glassfish&#039;s architect&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://tomcat.apache.org/tomcat-6.0-doc/aio.html&#034;&gt;Tomcat docs for Comet&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://caucho.com/resin-4.0/examples/websocket-java/index.xtp#WebSocketOverview&#034;&gt;Caucho&#039;s Resin Websockets&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://dev.w3.org/html5/websockets/&#034;&gt;HTML5 Web sockets spec&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a target=&#034;_blank&#034; href=&#034;http://localhost:8080/nio-websockets/index.jsp&#034;&gt;The link to start the demo I created, once you install it locally - http://localhost:8080/nio-websockets/index.jsp&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;br /&gt;
&lt;br /&gt;
Copyright &amp;copy; 2011 Ant Kutschera&lt;/p&gt;&lt;div class=&#034;tags&#034;&gt;&lt;span&gt;Social Bookmarks : &lt;/span&gt;&amp;nbsp;&lt;a href=&#034;http://slashdot.org/bookmark.pl?url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Slash Dot&#034;&gt;&lt;img src=&#034;common/images/slashdot.png&#034; alt=&#034;Add this post to Slashdot&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://digg.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Digg this post&#034;&gt;&lt;img src=&#034;common/images/digg.png&#034; alt=&#034;Add this post to Digg&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://reddit.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Reddit&#034;&gt;&lt;img src=&#034;common/images/reddit.png&#034; alt=&#034;Add this post to Reddit&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://del.icio.us/post?url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Save this post to Del.icio.us&#034;&gt;&lt;img src=&#034;common/images/delicious.png&#034; alt=&#034;Add this post to Delicious&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.stumbleupon.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Stumble this post&#034;&gt;&lt;img src=&#034;common/images/stumbleupon.png&#034; alt=&#034;Add this post to Stumble it&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.google.com/bookmarks/mark?op=edit&amp;amp;bkmk=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Google&#034;&gt;&lt;img src=&#034;common/images/google.png&#034; alt=&#034;Add this post to Google&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://technorati.com/faves?add=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Technorati&#034;&gt;&lt;img src=&#034;common/images/technorati.png&#034; alt=&#034;Add this post to Technorati&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.bloglines.com/sub/http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Bloglines&#034;&gt;&lt;img src=&#034;common/images/bloglines.png&#034; alt=&#034;Add this post to Bloglines&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.facebook.com/share.php?u=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Facebook&#034;&gt;&lt;img src=&#034;common/images/facebook.png&#034; alt=&#034;Add this post to Facebook&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.furl.net/storeIt.jsp?u=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;t=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Furl&#034;&gt;&lt;img src=&#034;common/images/furl.png&#034; alt=&#034;Add this post to Furl&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;amp;url=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;title=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Windows Live&#034;&gt;&lt;img src=&#034;common/images/windowslive.png&#034; alt=&#034;Add this post to Windows Live&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;amp;u=http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html&amp;amp;t=Tomcat%2C+WebSockets%2C+HTML5%2C+jWebSockets%2C+JSR-340%2C+JSON+and+more&#034; target=&#034;_blank&#034; title=&#034;Add this post to Yahoo!&#034;&gt;&lt;img src=&#034;common/images/yahoo.png&#034; alt=&#034;Add this post to Yahoo!&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&lt;/div&gt;
        </description>
      
      
    
    
    
    <comments>http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html#comments</comments>
    <guid isPermaLink="true">http://blog.maxant.co.uk:80/pebble/2011/06/21/1308690720000.html</guid>
    <pubDate>Tue, 21 Jun 2011 21:12:00 GMT</pubDate>
  </item>
  
  <item>
    <title>Non-blocking (NIO) Server Push and Servlet 3</title>
    <link>http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html</link>
    
      
        <description>
          &lt;p&gt;In my &lt;a target=&#034;_blank&#034; href=&#034;/pebble/2011/05/22/1306092969466.html&#034;&gt;previous blog posting&lt;/a&gt;, I wrote about what I would expect node.js to do in order to become mature.  I introduced the idea of having a framework which lets you define a protocol and some handlers in order to let the developer concentrate on writing useful business software, rather than technical code, in a very similar manner to which Java EE does.  And through that posting, I came to learn about a thing called Comet.  I had stated that using a non-blocking server wouldn&#039;t really be any more useful than a blocking one in a typical web application (HTTP), and so I created an example based on my own protocol and a VOIP server, for streaming binary data to many concurrently connected clients.&lt;br /&gt;
&lt;br /&gt;
I have now read up on Comet and come to realise there is indeed a good case for having a non-blocking server in the web.  That case is pushing data back to the client, like for continuously publishing latest stock prices.  While this example could be solved using polling, true Comet uses long-polling or even better, full on push.  A &lt;a target=&#034;_blank&#034; href=&#034;http://www.ibm.com/developerworks/web/library/wa-cometjava/&#034;&gt; great introduction I read was here&lt;/a&gt;.  The idea is that the client makes a call to the server and instead of the server returning data immediately, it keeps the connection open and returns data at some time in the future, potentially many times.  This is not a new idea - the term Comet seems to have been invented in about 2006 and the article I refer to above is from 2009.  I think I&#039;ve arrived at this party very late :-)&lt;br /&gt;
&lt;br /&gt;
My new found case of server push for non-blocking HTTP, and a strong curiosity drove me to knuckle down and start coding.  Before long, I had a rough implementation of the HTTP protocol for my little framework, and I was able to write an app for my server using handlers that subclassed the &lt;code&gt;HttpHandler&lt;/code&gt;, which was for all intents and purposes, a Servlet.&lt;br /&gt;
&lt;br /&gt;
To get Comet push to work properly, you get the client to &amp;quot;log in&amp;quot; and register itself with the server.  In my demo, I didn&#039;t check authorisations against a database, like you might do for a real app, but I had the concept of a channel, to which any browser client could subscribe.  During this login, the client says which channel it wants to subscribe to, and the server adds the clients non-blocking connection to its model.  The server responds using &lt;a target=&#034;_blank&#034; href=&#034;http://en.wikipedia.org/wiki/Chunked_transfer_encoding&#034;&gt;chunked transfer encoding&lt;/a&gt;, because that way, the connection stays open, and you don&#039;t need to state up front how much data you will send back.  At some time in the future, when someone publishes something, the server can use the connection which is still open contained in its model, to push that published data back to the subscribed client, by sending another chunk of data.&lt;br /&gt;
&lt;br /&gt;
The server implementation wasn&#039;t too hard, but the client posed a few problems, until I realised that the data was arriving in the ajax client with a ready state of 3, rather than the more usual 4.  The ajax client&#039;s &lt;code&gt;onreadystatechange&lt;/code&gt; callback function was also given every byte of data in it&#039;s &lt;code&gt;responseText&lt;/code&gt;, rather than just the new stuff, so I had some fiddling around until I could get the browser to just append the new stuff to the &lt;code&gt;innerHTML&lt;/code&gt; attribute of a &lt;code&gt;div&lt;/code&gt; on my page.  Anyway, after just a few hours, I had an app that worked quite well. But it wasn&#039;t entirely satisfactory, partly because as I stated in the previous posting, the server is still a little buggy, especially when the client drops a connection, because for example the browser page is closed.  I had also ended up implementing the HTTP protocol for my framework, which seemed to be reinventing the wheel - servlet technology does all this stuff already, and much better than I can hope to do it.  One of the reasons that I don&#039;t like node.js is that everything is being reinvented.&lt;br /&gt;
&lt;br /&gt;
So, like the article which I referenced above indicated, version 3.0 of Servlets should be able to handle Comet.  I downloaded Tomcat 7.0, which has a Servlet 3.0 container, and I ported my app code to proper Servlets.  It took a while to work out exactly how to use the new asynchronous parts of servlets because there aren&#039;t all that many accurate tutorials out there.  The servlet specs (JSR 315) helped a lot.  Once I cracked how to use the async stuff properly, I had a really really satisfying solution to my push requirements.&lt;br /&gt;
&lt;br /&gt;
The first step, was to reconfigure Tomcat so that it uses non-blocking (NIO) for its connector protocol.  The point of this is that I want to keep a connection open to the client in order to push data to it.  I can&#039;t rely on the one-thread-per-request paradigm, because context switching and thread memory requirements are likely to be a performance killer.  In Tomcat&#039;s &lt;code&gt;server.xml&lt;/code&gt; file, I configured the connector&#039;s protocol:&lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 130px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
	&amp;lt;!-- NIO HTTP/1.1 connector --&amp;gt;    
    &amp;lt;Connector port=&amp;quot;8080&amp;quot; protocol=&amp;quot;org.apache.coyote.http11.Http11NioProtocol&amp;quot; 
               connectionTimeout=&amp;quot;20000&amp;quot; 
               redirectPort=&amp;quot;8443&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
rather than the normal: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 100px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
    &amp;lt;Connector port=&amp;quot;8080&amp;quot; protocol=&amp;quot;HTTP/1.1&amp;quot; 
               connectionTimeout=&amp;quot;20000&amp;quot; 
               redirectPort=&amp;quot;8443&amp;quot; /&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
All you need to do to get Tomcat to turn into an NIO server is change the protocol attribute to the slightly longer class name.&lt;br /&gt;
&lt;br /&gt;
The second step, was to create two servlets.  The first &lt;code&gt;LoginServlet&lt;/code&gt; handles the client &amp;quot;logging in&amp;quot; and subscribing to a channel.  That servlet looks like this: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 300px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
/*  
 * Copyright (c) 2011 Ant Kutschera
 * 
 * This file is part of Ant Kutschera&#039;s blog, 
 * http://blog.maxant.co.uk
 * 
 * This is free software: you can redistribute
 * it and/or modify it under the terms of the
 * Lesser GNU General Public License as published by
 * the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the Lesser GNU General Public License for
 * more details. 
 * 
 * You should have received a copy of the
 * Lesser GNU General Public License along with this software.
 * If not, see http://www.gnu.org/licenses/.
 */
package ch.maxant.blog.nio.servlet3;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.maxant.blog.nio.servlet3.model.Subscriber;

@WebServlet(name = &amp;quot;loginServlet&amp;quot;, urlPatterns = { &amp;quot;/login&amp;quot; }, asyncSupported = true)
public class LoginServlet extends HttpServlet {

	public static final String CLIENTS = &amp;quot;ch.maxant.blog.nio.servlet3.clients&amp;quot;;

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// dont set the content length in the response, and we will end up with chunked 
		// encoding so that a) we can keep the connection open to the client, and b) send
		// updates to the client as chunks.
		
		// *********************
		// we use asyncSupported=true on the annotation for two reasons. first of all, 
		// it means the connection to the client isn&#039;t closed by the container.  second 
		// it means that we can pass the asyncContext to another thread (eg the publisher) 
		// which can then send data back to that open connection.
		// so that we dont require a thread per client, we also use NIO, configured in the 
		// connector of our app server (eg tomcat)
		// *********************

		// what channel does the user want to subscribe to?  
		// for production we would need to check authorisations here!
		String channel = request.getParameter(&amp;quot;channel&amp;quot;);

		// ok, get an async context which we can pass to another thread
		final AsyncContext aCtx = request.startAsync(request, response);

		// a little longer than default, to give us time to test.
		// TODO if we use a heartbeat, then time that to pulse at a similar rate
		aCtx.setTimeout(20000L); 

		// create a data object for this new subscription
		Subscriber subscriber = new Subscriber(aCtx, channel);

		// get the application scope so that we can add our data to the model
		ServletContext appScope = request.getServletContext();

		// fetch the model from the app scope
		@SuppressWarnings(&amp;quot;unchecked&amp;quot;)
		Map&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
The inline comments describe most of the choices I made.  I added a listener to the context so that we get an event in the case of a disconnected client, so that we can tidy up our model - the full code is in the ZIP at the end of this article.  Importantly, this servlet does no async processing itself.  It simply prepares the request and response objects for access at some time in the future.  We stick them (via the async context) into a model which is in application scope.  That model can then be used by the servlet which receives a request to publish something to a given channel: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 300px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
/*  
 * Copyright (c) 2011 Ant Kutschera
 * 
 * This file is part of Ant Kutschera&#039;s blog, 
 * http://blog.maxant.co.uk
 * 
 * This is free software: you can redistribute
 * it and/or modify it under the terms of the
 * Lesser GNU General Public License as published by
 * the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the Lesser GNU General Public License for
 * more details. 
 * 
 * You should have received a copy of the
 * Lesser GNU General Public License along with this software.
 * If not, see http://www.gnu.org/licenses/.
 */
package ch.maxant.blog.nio.servlet3;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ch.maxant.blog.nio.servlet3.model.Subscriber;

@WebServlet(name = &amp;quot;publishServlet&amp;quot;, urlPatterns = { &amp;quot;/publish&amp;quot; }, asyncSupported = true)
public class PublishServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// *************************
		// this servlet simply spawns a thread to send its message to all subscribers.
		// this servlet keeps the connection to its client open long enough to tell it 
		// that it has published to all subscribers.
		// *************************
		
		// add a pipe character, so that the client knows from where the newest model has started.
		// if messages are published really quick, its possible that the client gets two at
		// once, and we dont want it to be confused!  these messages also arrive at the 
		// ajax client in readyState 3, where the responseText contains everything since login,
		// rather than just the latest chunk.  so, the client needs a way to work out the 
		// latest part of the message, containing the newest version of the model it should 
		// work with.  might be better to return XML or JSON here!
		final String msg = &amp;quot;|&amp;quot; + request.getParameter(&amp;quot;message&amp;quot;) + &amp;quot; &amp;quot; + new Date();

		// to which channel should it publish?  in prod, we would check authorisations here too!
		final String channel = request.getParameter(&amp;quot;channel&amp;quot;);

		// get the application scoped model, and copy the list of subscribers, so that the 
		// long running task of publishing doesnt interfere with new logins
		ServletContext appScope = request.getServletContext();
		@SuppressWarnings(&amp;quot;unchecked&amp;quot;)
		final Map&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
Again, there are plenty of comments in the code.  In this servlet, we actually do some (potentially) long running task.  In many online examples of Servlet 3.0 Async Support, they show handing off work to an Executor.  The async context provides the ideal way to do this via the container though, using its &lt;code&gt;start(Runnable)&lt;/code&gt; method.  The container implementation then descides how to handle the task, rather than the developer having to worry about spawning threads, which on app servers like WebSphere is illegal and leads to errors.  In true Java EE fashion, the developer can concentrate on business code, rather than technicalities.&lt;br /&gt;
&lt;br /&gt;
Something else which might be important in the above code, is that the publishing is done on a different thread.  Imagine publishing data to ten thousand clients.  In order to finish within a second, each push it going to have to complete in less than a tenth of a millisecond.  That means doing something useful like a database lookup is not going to be feasible.  On a non-blocking server, we can&#039;t afford to take a second to do something, and many would argue a second is eternity in such an environment.  The ability to hand off such work to a different thread is invaluable, and sadly, something node.js cannot currently do, although you can hand off the task to a different process, albeit potentially messier than that shown here.&lt;br /&gt;
&lt;br /&gt;
Now, we just need to create a client to subscribe to the server.  This client is an ajax request object which is created when the HTML is loaded which runs some JavaScript in a library I have written.  The HTML looks like this: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 300px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
	&amp;lt;script language=&amp;quot;Javascript&amp;quot; type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;push_client.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;p&amp;gt;Boo!&amp;lt;/p&amp;gt;
&amp;lt;div id=&amp;quot;myDiv&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;script language=&amp;quot;Javascript&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;

function callback(model){
	//simply append the model to a div, for demo purposes
	var myDiv = document.getElementById(&amp;quot;myDiv&amp;quot;);
	myDiv.innerHTML = myDiv.innerHTML + &amp;quot;&amp;lt;br&amp;gt;&amp;quot; + model;
}

new PushClient(&amp;quot;myChannel&amp;quot;, callback).login();

&amp;lt;/script&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
As you can see, it simply needs to define a callback function which will handle each message published from the server.  The published message could be text, XML or JSON - the publisher chooses.  The JavaScript in that library is a little more complicated, but basically creates an XHR requester which sends a request to the login servlet.  Any data it receives from the server, it parses, and returns the newest part of the data back to the callback. &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 300px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
/*  
 * Copyright (c) 2011 Ant Kutschera
 * 
 * This file is part of Ant Kutschera&#039;s blog, 
 * http://blog.maxant.co.uk
 * 
 * This is free software: you can redistribute
 * it and/or modify it under the terms of the
 * Lesser GNU General Public License as published by
 * the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * 
 * It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the Lesser GNU General Public License for
 * more details. 
 * 
 * You should have received a copy of the
 * Lesser GNU General Public License along with this software.
 * If not, see http://www.gnu.org/licenses/.
 */

function PushClient(ch, m){

	this.channel = ch;
	this.ajax = getAjaxClient();
	this.onMessage = m;

	// stick a reference to &amp;quot;this&amp;quot; into the ajax client, so that the handleMessage 
	// function can access the push client - its &amp;quot;this&amp;quot; is an XMLHttpRequest object
	// rather than the push client, coz thats how javascript works!
	this.ajax.pushClient = this;
	
	function getAjaxClient(){
		/*
		 * Gets the ajax client
		 * http://en.wikipedia.org/wiki/XMLHttpRequest
		 * http://www.w3.org/TR/XMLHttpRequest/#responsetext
		 */
	    var client = null;
	    try{
			// Firefox, Opera 8.0+, Safari
			client = new XMLHttpRequest();
		}catch (e){
			// Internet Explorer
			try{
				client = new ActiveXObject(&amp;quot;Msxml2.XMLHTTP&amp;quot;);
			}catch (e){
				client = new ActiveXObject(&amp;quot;Microsoft.XMLHTTP&amp;quot;);
			}
		}
		return client;
	};
	
	/** 
	 * pass in a callback and a channel.  
	 * the callback should take a string, 
	 * which is the latest version of the model 
	 */
	PushClient.prototype.login = function(){

		try{
			var params = escape(&amp;quot;channel&amp;quot;) + &amp;quot;=&amp;quot; + escape(this.channel);
			var url = &amp;quot;login?&amp;quot; + params;
			this.ajax.onreadystatechange = handleMessage;
			this.ajax.open(&amp;quot;GET&amp;quot;,url,true); //true means async, which is the safest way to do it
			
			// hint to the browser and server, that we are doing something long running
			// initial tests only seemed to work with this - dont know, perhaps now it 
			// works without it?
			this.ajax.setRequestHeader(&amp;quot;Connection&amp;quot;, &amp;quot;Keep-Alive&amp;quot;);
			this.ajax.setRequestHeader(&amp;quot;Keep-Alive&amp;quot;, &amp;quot;timeout=999, max=99&amp;quot;);
			this.ajax.setRequestHeader(&amp;quot;Transfer-Encoding&amp;quot;, &amp;quot;chunked&amp;quot;);
			
			//send the GET request to the server
			this.ajax.send(null);
		}catch(e){
			alert(e);
		}
	};

	function handleMessage() {
		//states are:
		//	0 (Uninitialized)	The object has been created, but not initialized (the open method has not been called).
		//	1 (Open)	The object has been created, but the send method has not been called.
		//	2 (Sent)	The send method has been called. responseText is not available. responseBody is not available.
		//	3 (Receiving)	Some data has been received. responseText is not available. responseBody is not available.
		//	4 (Loaded)
		try{
			if(this.readyState == 0){
				//this.pushClient.onMessage(&amp;quot;0/-/-&amp;quot;);
			}else if (this.readyState == 1){
				//this.pushClient.onMessage(&amp;quot;1/-/-&amp;quot;);
			}else if (this.readyState == 2){
				//this.pushClient.onMessage(&amp;quot;2/-/-&amp;quot;);
			}else if (this.readyState == 3){
				//for chunked encoding, we get the newest version of the entire response here, 
				//rather than in readyState 4, which is more usual.
				if (this.status == 200){
					this.pushClient.onMessage(&amp;quot;3/200/&amp;quot; + this.responseText.substring(this.responseText.lastIndexOf(&amp;quot;|&amp;quot;)));
				}else{
					this.pushClient.onMessage(&amp;quot;3/&amp;quot; + this.status + &amp;quot;/-&amp;quot;);
				}
			}else if (this.readyState == 4){
				if (this.status == 200){
					
					//the connection is now closed.
					
					this.pushClient.onMessage(&amp;quot;4/200/&amp;quot; + this.responseText.substring(this.responseText.lastIndexOf(&amp;quot;|&amp;quot;)));

					//start again - we were just disconnected!
					this.pushClient.login();

				}else{
					this.pushClient.onMessage(&amp;quot;4/&amp;quot; + this.status + &amp;quot;/-&amp;quot;);
				}
			}
		}catch(e){
			alert(e);
		}
	};
}
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
The important parts here are that we need to listen for events on both ready state 3 and 4, rather than the usual 4.  While the connection is kept open, the client only receives data in ready state 3, and everytime it receives a chunk, the &lt;code&gt;ajax.responseText&lt;/code&gt; attribute contains all chunks since login, rather than just the newest chunk.  This could be bad, if the connection receives tons of data - eventually the browser will run out of memory!  You could measure the number of bytes sent to any client on the server, and when its above a given threshold, force the client to disconnect by ending the stream (call the &lt;code&gt;complete()&lt;/code&gt; method on the async context of the relevant client just after publishing a message to it).  The client above automatically logs itself back into the server when the server disconnects.&lt;br /&gt;
&lt;br /&gt;
Instead of the reconnect solution for dropped / timed-out connections (which is very similar to long polling) we could add a heartbeat which the server sends to each subscribed client.  The heartbeat period would need to be slightly less than the timeout.  The exact details could get messy - do you consider sending a heartbeat every second, but only do it to clients who need it?  Or do you send it to every client, say every 25 seconds, if the timeout is say 30 seconds?  You could use performance tuning to determine if that is better than the reconnecting I have shown above.  Then again, a heartbeat is good for culling closed connections, because it tests the connection every so often, and gets an exception if the push fails.  And then again, the container informs the listener that we added to the login async context if a disconnect occurs too, so perhaps we don&#039;t need a heartbeat - you decide :-)&lt;br /&gt;
&lt;br /&gt;
Now, we need a way to publish data - that&#039;s easy - I just type the following URL into the browser, and it sends a GET request to the publish servlet: &lt;/p&gt;
&lt;div style=&#034;border: thin none; overflow: auto; width: 525px; height: 50px; background-color: rgb(255, 255, 255);&#034;&gt;
&lt;pre&gt;
http://localhost:8080/nio-servlet3/publish?channel=myChannel&amp;amp;message=javaIsAwesome
&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
Keep refreshing the browser window with that protocol, and the other window almost instantly gets updates, showing the latest message at the bottom.  I tested it using Firefox as the subscriber, and Chrome as the publisher.&lt;br /&gt;
&lt;br /&gt;
I haven&#039;t checked out scalability, because I have assumed that Tomcat&#039;s NIO connector has been well tested and performs well.  I&#039;ll let someone else play with the scalability of Servlet 3.0 for a push solution.  This article is about showing how easy it is to implement Comet push, using Java EE Servlets.  Note, it used to be easy too, because servers like Jetty and Tomcat and others provided bespoke Comet interfaces, but now, with the advent of Servlet 3.0, there is a standardised way to do it.&lt;br /&gt;
&lt;br /&gt;
There are plenty of profesional and open source solutions which do what I have done in this article.  See &lt;a target=&#034;_blank&#034; href=&#034;http://ajaxpatterns.org/HTTP_Streaming#Real-World_Examples&#034;&gt;this article&lt;/a&gt;, which lists many, whackiest of all, APE - another project which puts JavaScript on the server!?  Well, better than PHP I guess :-)&lt;br /&gt;
&lt;br /&gt;
The complete code &lt;a target=&#034;_blank&#034; href=&#034;/pebble/files/nio-servlet3.zip&#034;&gt;for this demo is downloadable here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Copyright &amp;copy; 2011 Ant Kutschera&lt;/p&gt;&lt;div class=&#034;tags&#034;&gt;&lt;span&gt;Social Bookmarks : &lt;/span&gt;&amp;nbsp;&lt;a href=&#034;http://slashdot.org/bookmark.pl?url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Slash Dot&#034;&gt;&lt;img src=&#034;common/images/slashdot.png&#034; alt=&#034;Add this post to Slashdot&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://digg.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Digg this post&#034;&gt;&lt;img src=&#034;common/images/digg.png&#034; alt=&#034;Add this post to Digg&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://reddit.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Reddit&#034;&gt;&lt;img src=&#034;common/images/reddit.png&#034; alt=&#034;Add this post to Reddit&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://del.icio.us/post?url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Save this post to Del.icio.us&#034;&gt;&lt;img src=&#034;common/images/delicious.png&#034; alt=&#034;Add this post to Delicious&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.stumbleupon.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Stumble this post&#034;&gt;&lt;img src=&#034;common/images/stumbleupon.png&#034; alt=&#034;Add this post to Stumble it&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.google.com/bookmarks/mark?op=edit&amp;amp;bkmk=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Google&#034;&gt;&lt;img src=&#034;common/images/google.png&#034; alt=&#034;Add this post to Google&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://technorati.com/faves?add=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Technorati&#034;&gt;&lt;img src=&#034;common/images/technorati.png&#034; alt=&#034;Add this post to Technorati&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.bloglines.com/sub/http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Bloglines&#034;&gt;&lt;img src=&#034;common/images/bloglines.png&#034; alt=&#034;Add this post to Bloglines&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.facebook.com/share.php?u=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Facebook&#034;&gt;&lt;img src=&#034;common/images/facebook.png&#034; alt=&#034;Add this post to Facebook&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.furl.net/storeIt.jsp?u=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;t=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Furl&#034;&gt;&lt;img src=&#034;common/images/furl.png&#034; alt=&#034;Add this post to Furl&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;amp;url=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;title=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Windows Live&#034;&gt;&lt;img src=&#034;common/images/windowslive.png&#034; alt=&#034;Add this post to Windows Live&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;amp;u=http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html&amp;amp;t=Non-blocking+%28NIO%29+Server+Push+and+Servlet+3&#034; target=&#034;_blank&#034; title=&#034;Add this post to Yahoo!&#034;&gt;&lt;img src=&#034;common/images/yahoo.png&#034; alt=&#034;Add this post to Yahoo!&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&lt;/div&gt;
        </description>
      
      
    
    
    
    <comments>http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html#comments</comments>
    <guid isPermaLink="true">http://blog.maxant.co.uk:80/pebble/2011/06/05/1307299200000.html</guid>
    <pubDate>Sun, 05 Jun 2011 18:40:00 GMT</pubDate>
  </item>
  
  <item>
    <title>Java non-blocking servers, and what I expect node.js to do if it is to become mature</title>
    <link>http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html</link>
    
      
        <description>
          &lt;a href=&#039;http://www.nodejs.org&#039; target=&#039;_blank&#039;&gt;node.js&lt;/a&gt; is getting a lot of attention at the moment.  
It&#039;s goal is to provide an easy way to build scalable network programs, e.g. build web servers.
It&#039;s different, in two ways.  First of all, it brings Javacript to the server.  But more importantly,
it&#039;s event based, rather than thread based, so relies on the OS to send it events when say a connection to the 
server is made, so that it can handle that request.&lt;br&gt;
&lt;br&gt;
The argument goes, that a typical web server &#034;handles each request using a thread, which is relatively inefficient and very 
difficult to use.&#034;  As an example they state that &#034;Node will show much better memory efficiency under high loads than systems which 
allocate 2MB thread stacks for each connection.&#034;&lt;br&gt;
&lt;br&gt;
They go on to state that &#034;users of Node are free from worries of dead-locking the process — there are no locks. 
Almost no function in Node directly performs I/O, so the process never blocks. 
Because nothing blocks, less-than-expert programmers are able to develop fast systems&#034;.&lt;br&gt;
&lt;br&gt;
Well, reading those statements makes me think that I have problems in my world which need addressing!  But then I look at my world, and realise 
that I don&#039;t have problems.  How can that be?  Well first of all, because we don&#039;t have a thread per request, rather we use a thread pool, reducing 
the memory overhead, and queuing incoming requests if we can&#039;t run them in a thread instantly, until a thread becomes free in the pool.&lt;br&gt;
&lt;br&gt;
The second reason I don&#039;t have threading problems is because I work with Java EE.  I write business software which is written as components
which get deployed to an app server.  That app server is what does all the hard work with threads.  All I have to do is follow some simple 
and common sense rules to avoid threading issues, like ensuring that shared resources like a Map(dictionary) are instantiated using the thread safe API
which Java offers.  In more extreme cases, I use the &lt;code&gt;synchronized&lt;/code&gt; keyword to protect methods or objects being shared. &lt;br&gt;
&lt;br&gt;
All this means that we Java programmers have become very efficient at writing software to solve business problems, rather than writing software to solve
technical problems like concurrency, scalability, security, transactions, resources, object and resource pooling, etc., etc.&lt;br&gt;
&lt;br&gt;
So when do I need to solve those problems which lots of threads introduce, namely memory problems?
Any server which needs to maintain an open connection to the client, in order to say stream video or Voice over IP (VOIP), or handle instant 
messaging, is a server where I&#039;m going to have problems with memory if I have a thread per connection.&lt;br&gt;
&lt;br&gt;
Now, the Java EE specifications tend to focus on multithreaded servers.  And to my knowledge, there is no Java EE specification which 
tells vendors how to make a server which lets people deploy software components to it, which are handled in a non-blocking manner.  Sure, you could 
write a Servlet compliant server like Tomcat with a non-blocking engine under the hood, but Java EE doesn&#039;t talk about streaming.  And probably
99% of websites out there don&#039;t do the kind of streaming which is going to cause memory issues.&lt;br&gt;
&lt;br&gt;
So there certainly are times when something like node.js will be useful.  Or at least the idea of a non-blocking server.  But looking into the
details, node.js isn&#039;t something that I would seriously use if I needed such a server.  The main problems are that:&lt;br&gt;
&lt;ol&gt;
&lt;li&gt;you deploy Javascript to the server&lt;/li&gt;
&lt;li&gt;it doesn&#039;t seem to specify a standardised way of writing components so that I can concentrate on writing business software rather than 
    solving technical issues&lt;/li&gt;
&lt;li&gt;while it is rumoured to be fast, studies such as &lt;a href=&#039;http://www.olympum.com/java/java-aio-vs-nodejs/&#039; target=&#039;_blank&#039;&gt;this&lt;/a&gt; suggest it&#039;s half as slow as Java&lt;/li&gt;
&lt;li&gt;compared to Java, the node.js API and Javascript libraries available today are immature - think about things like sending email, ORM, etc.&lt;/li&gt;
&lt;li&gt;node.js has political problems because it relies on Google.  If Google don&#039;t want to support Javascript on the server (their V8 engine is designed
    for Chrome, client side), and node.js needs a patch or development on V8 to handle a serverside issue, they might never get it.  
    OK, like I have a chance to get a Java bug patched by Oracle ;-)&lt;/li&gt;
&lt;/ol&gt;
It started for me, with this code snippet, taken from the node.js site:&lt;br&gt;
&lt;pre&gt;
    var net = require(&#039;net&#039;);

    var server = net.createServer(function (socket) {
      socket.write(&#034;Echo server\r\n&#034;);
      socket.pipe(socket);
    });

    server.listen(1337, &#034;127.0.0.1&#034;);
&lt;/pre&gt;
&lt;br&gt;
Well, if the point of node.js is to make it really easy to create a server, and pass it a function for handling requests, I can do that in 
Java too:&lt;br&gt;
&lt;pre&gt;
TCPProtocol protocol = new TCPProtocol(){

    public void handleRequest(ServerRequest request, 
                              ServerResponse response) {

        //echo what we just received
        try {
            response.write(request.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

Configuration config = new Configuration(1337, protocol);
ServerFactory.createServer(config).listen();
&lt;/pre&gt;
&lt;br&gt;
OK, it&#039;s a tiny bit more complicated.  But the reason is, I decided to write a non-blocking server which can be configured to handle any kind of request.
The configuration takes a port number for the server to run on, and a protocol object.  The protocol object is a subclass of an abstract protocol,
and its job is to look at the data coming in from the wire and decide how to handle it.  A TCPProtocol as shown above is simplest protocol,
in that it does nothing.  You need to tell it what to do, by overriding the &lt;code&gt;handleRequest()&lt;/code&gt; method (analagous to supplying a function
in Javascript), for example as shown above, by returning to the client what it sent to the server.&lt;br&gt;
&lt;br&gt;
But I wanted to do something more useful, so I extended what I wrote to handle voice over IP, or at least a client streaming an MP3 to a different
client, to simulate a phone call between the two of them.&lt;br&gt;
&lt;br&gt;
The first step was to design the protocol.  At the byte level, the first byte in a packet sent to the server contains the command, or action, the 
second byte contains the length of the payload, if any, and the subsequent bytes contain the payload.&lt;br&gt;
&lt;br&gt;
The protocol then lets a caller login (returning a session ID), start a call (returning an OK/NOK), send data for the call, end a call, 
and quit (logout).&lt;br&gt;
&lt;br&gt;
After a few hours I had my laptop playing my favourite MP3s, streamed to my laptop from a different PC.  But it looked clunky.  I had a think,
and took inspiration from the Servlet and EJB specifications in Java EE.  Namely, I wanted to have deployable components whose sole job was to handle
a business requirement.&lt;br&gt;
&lt;br&gt;
In .NET and Java you can define a web service or web page (Servlet) by annotating the class.  In the annotation, you provide a URL path, which the server uses to 
determine when to call your servlet or web service.  This is similar to a &#034;command&#034; or &#034;action&#034; as I had in my VOIP protocol.&lt;br&gt;
&lt;br&gt;
So I wrote a little container, which sits inside the non-blocking server.  The server takes the incoming request and once it has handled the low
level non-blocking stuff, it passes the request over to the configured protocol.  The VOIP protocol then extracts the command (first byte) from
the incoming request.  It then uses a &#034;context&#034; object, which it gets injected into it from the container, to send the incoming request to a 
Handler.  The handler is a class which has an annotation to state which command it can handle.  The handler is then analagous to a web 
service or servlet.  It is a piece of busienss code which handles an incoming request, based on the command (path) which the client is requesting.&lt;br&gt;
&lt;br&gt;
Put together, it looks as follows.  The first bit is the protocol&#039;s handler method which determines the command and sends it to a handler:&lt;br&gt;
&lt;pre&gt;
    public void handleRequest(ServerRequest request,
	                          ServerResponse response) {

        String criterion = String.valueOf(request.getData()[0]);
        try{
            //call through to the context for help - it
            //will call the handler for us.
            getContext().handleRequest(criterion, request, response);
        } catch (UnknownHandlerException e) {
            //send NOK to client because of unknown command
            response.write(new Packet(UNKNOWN_COMMAND).marshal());
        }
    }
&lt;/pre&gt;
&lt;br&gt;
A &lt;code&gt;Packet&lt;/code&gt; object in the above code is simply an encapsulation of the data sent over the wire, but knows that the first byte is the command, 
the second is the length and 
subsequent bytes are the payload.  In an HTTP request, this Packet object would be something which knew about the HTTP header&#039;s attributes and
the HTTP payload, rather than the &lt;code&gt;ServerRequest&lt;/code&gt; and &lt;code&gt;ServerResponse&lt;/code&gt; objects which only know about byte arrays and 
sockets/channels.&lt;br&gt;
&lt;br&gt;
The second part of the solution are then the handlers.  These are contained in the configuration, either created programatically as shown
in the TCP example above, or created using XML which the server reads upon startup.
The container then locates, instantiates and calls these handlers 
on behalf of the protocol, when the protocol object calls &lt;code&gt;getContext().handleRequest(criterion, request, response)&lt;/code&gt; in the above 
snippet.  A typical handler looks like this:&lt;br&gt;
&lt;pre&gt;
@Handler(selector=VoipProtocol.LOGIN)
public class VoipLoginHandler extends VoipHandler {

    public void service(VoipRequest request,
                        VoipResponse response)
                        throws IOException {
		
        String name = request.getPacket().getPayloadAsString();
        Participant p = new Participant(
                        name, response.getSocketChannel());
        getProtocol().getModel().addParticipant(p);
        request.getKey().attach(p);
		
        //ACK
        String sessId = p.getSessId().getBytes(VoipProtocol.CHARSET);
        Packet packet = new Packet(sessId, VoipProtocol.LOGIN)
        response.write(packet);
	}

}
&lt;/pre&gt;
&lt;br&gt;
So, the &lt;code&gt;service&lt;/code&gt; method is the only one in a handler, 
and is in charge of doing business stuff.  There is no techy stuff here.  The code works out who is logging in,
creates an instance of them (the &lt;code&gt;Participant&lt;/code&gt; object) in the 
model.  The model is contained in the protocol object, which exists just once in the server.  Compared to a servlet, the call to get the model
is analagous to putting data into the application scope.  The code then attaches the participant object
to the client connection using the &lt;code&gt;attach(Object)&lt;/code&gt; method (see Java NIO Package) so that we can always get straight to the 
relevant part of the data model from the connection object, when subsequent requests arrive.  Finally, the code responds to the client with 
the session ID as an aknowledgement. Note that here, I haven&#039;t bothered to authenticate the password - the payload only contains the username.  
But if I were writing a complete app, I would have more data in my payload, perhaps even something like XML or JSON, and I would authenticate 
the username and password.&lt;br&gt;
&lt;br&gt;
The &lt;code&gt;@Handler&lt;/code&gt; annotation at the top of the handler class is analagous to the &lt;code&gt;@WebServlet&lt;/code&gt; annotation applied to 
Java EE Servlets.  It has a &#034;selector&#034; attribute which the container uses to compare to the criterion which the protocol extracts from the 
request.  This is analagous to the URL patterns attribute in &lt;code&gt;@WebServlet&lt;/code&gt; which tells a Java EE web container to which path 
the servlet should be mapped.  There is a little bit of hidden magic too - the service method in the 
handler already knows &lt;code&gt;VoipRequest&lt;/code&gt; and &lt;code&gt;VoipResponse&lt;/code&gt;, rather than &lt;code&gt;ServerRequest&lt;/code&gt; and 
&lt;code&gt;ServerResponse&lt;/code&gt;.  The superclass does this magic, by implementing
the standard &lt;code&gt;service&lt;/code&gt; method and calling the specialised abstract &lt;code&gt;service&lt;/code&gt; method, implemented in subclasses.&lt;br&gt;
&lt;br&gt;
So, being creative, I added a further attribute to the &lt;code&gt;@Handler&lt;/code&gt; annotation.  It is called &lt;code&gt;runAsync&lt;/code&gt; and defaults to false.
But, if it is set to true, then the container sends the handler to a thread pool for execution sometime in the future.  I don&#039;t actually use this in the 
VOIP example, but I did this, to show that it is perfectly feasible, that an app server can do such things.  The developer doesn&#039;t need to worry
about threads or anything - they simple configure the annotation and the container handles the hard parts.  This is typical of Java EE!  And it
becomes extremely useful in cases where a request needs a little more time to execute.  In a non-blocking single threaded process, 
while connections are concurrently connected to the server, they are serviced sequentially, meaning that they MUST return fast, if you don&#039;t want
those in the queue to wait too long.  This is something which node.js CANNOT do, because it has no way of starting threads.  Their solution is to
send an async request to a different process.  But to do that, the developer is spending time working on technical issues, rather than getting
on and trusing the container to do it for them, so that they can spend more time writing cost effective business code.  One of the main 
reasons to use Java EE is that the developer can spend more time writing business software and less time handling techie problems.  
There is no reason why a handler couldn&#039;t also have other annotations:&lt;br&gt;
&lt;pre&gt;
@Handler(selector=VoipProtocol.QUIT)
@RolesAllowed({&#034;someRole&#034;, &#034;someOtherRole&#034;})
@TransactionManagement(TransactionManagementType.CONTAINER)
public class VoipQuitHandler extends VoipHandler {

    @PersistenceContext(unitName=&#034;persistenceUnitName&#034;)
    private EntityManager em;
    .
    .
    .
}
&lt;/pre&gt;
&lt;br&gt;
The &lt;code&gt;@RolesAllowed&lt;/code annotation would mean that the handler only gets called if the container can verify that the logged in user 
has one of the appropriate roles.  The &lt;code&gt;@TransactionManagement&lt;/code&gt; annotation means that transactions will be handled by the container
rather than by the programmer.  When the handler is executed, the &lt;code&gt;@PersistenceContext&lt;/code&gt; annotation causes the container to 
inject a JPA entity manager so that the business code has access to a database.  This is exactly the same way that a Servlet or EJB gets resources 
from the container.  Those resources are created based on the app server configuration, in a standardised way and are managed by the 
container too (pooling, reconnecting, etc.), again, relieving the programmer from that burden.&lt;br&gt;
&lt;br&gt;
So what do we have now?  Instead of a low level API like node.js provides, we have a high level container for running software components within 
a non-blocking server.  What we don&#039;t have, is Javascript running on the server, because it seemed like the ideal language for handling
callbacks in a non-blocking environment, because it has an event queue and function pointers.&lt;br&gt;
&lt;br&gt;
Could this little exercise be the basis of a JSR?  Well, is it really useful?  Only really in cases where you have clients which need to keep 
connections open to the server for a long time, and you have thousands of clients.  There won&#039;t be many people needing to do this, and there 
are more important JSRs awaiting acceptance and implementation.  But who knows what the future will bring.&lt;br&gt;
&lt;br&gt;
To summarise, node.js makes me uneasy, because I don&#039;t like the idea of Javascript and its immature stack of libraries being deployed 
on a production server.  Whenever I develop with Javascript I spend a lot more time with the debugger than I would like to, because the 
language is not entirely checkable using static analysis because it is duck typed.  
But the idea of building a non-blocking server using Java - now that&#039;s interesting (to me at least). 
But like I said, I&#039;m just not sure how often will it be useful.&lt;br&gt;
&lt;br&gt;
It seems to me, that the revolution that node.js is starting isn&#039;t really about Javascript on the server.  It is more about 
using a non-blocking server.  But the problem is, probably 99% of our needs are already 
satisfied with standard multithreaded servers.  And we can already write scalable websites, without all those problems which node.js claims we have.
So let&#039;s not rebuild the world based on non-blocking I/O, just because node.js has arrived.  Let&#039;s build/rebuild just those very special 
cases, where non-blocking I/O will really help us.&lt;br&gt;
&lt;br&gt;
Does node.js deserve the hype it is getting?  I don&#039;t think that it deserves hype because you can run Javascript on the server - 
that&#039;s a bad thing.  Douglas Crockford (senior JavaScript architect at Yahoo!) even hints this, when he 
&lt;a href=&#039;http://developer.yahoo.com/yui/theater/video.php?v=crockford-loopage&#039; target=&#039;_blank&#039;&gt;says&lt;/a&gt;:&lt;br&gt;
&lt;br&gt; 
&lt;i&gt;	&#034;The big surprise for me in this is we&#039;re about to take maybe the most important step we&#039;ve ever taken in terms of the technology of the web, 
	 and JavaScript is leading the way.&#034;
&lt;/i&gt;&lt;br&gt;
&lt;br&gt;	 
He seems to be saying that Javascript is &lt;i&gt;leading&lt;/i&gt; the way in the most important step we are ever taking, and not that Javascript IS the most important
step we are taking.  That is, non-blocking servers are the most important step, and having an event loop on the server is the way forward.  
The way I understand it, he is saying that non-blocking is the revolution.  
The problem I have in joining in on this revolution is that non-blocking servers are not ncessarily the best thing ever.
They only really help, when you have thousands of clients needing to keep their connections to the server open.  HTTP (99% of the web) doesn&#039;t need
non-blocking I/O to become the technology leader of the web - it already is.  So instead of joining in this revolution and all the hype that 
node.js is stirring up, I will ignore it and continue building software the way I have been.&lt;br&gt;
&lt;br&gt;
The code for the examples given above are in two Eclipse projects, which you can download 
&lt;a href=&#039;/pebble/files/nio-apps-framework-201105220028.zip&#039;&gt;here&lt;/a&gt;.  The first project is the framework
itself, including the non-blocking server, container and relevant classes and interfaces.  The second project is an example of how to 
use the framework to build (business) apps.  It contains the &lt;code&gt;TCPServerRunner&lt;/code&gt; class for running a TCP echo server.  
It also contains the &lt;code&gt;VoipServerRunner&lt;/code&gt; which starts the VOIP Server.  
To run the streaming example, first run the &lt;code&gt;ListeningClient&lt;/code&gt;, followed by the &lt;code&gt;SendingClient&lt;/code&gt;.
Change line 74 of the &lt;code&gt;SendingClient&lt;/code&gt; to use your favourite MP3, and you should hear it stream the first 20 seconds.
The VOIP server itself isn&#039;t 100% reliable - especially once clients have
disconnected.  But I guess node.js wasn&#039;t that stable after only a small number of hours of development.   Good luck!&lt;br&gt;
&lt;br&gt;
PS. Performance: streaming at 192 kilobits a second, the server told me it was running around half a percent load (i.e. the event loop was 
idle 99.5% of the time).  GSM, rather than high quality MP3 uses around 30 Kbps, so for a real VOIP server,
you could probably get away with 1200 simultaneous calls.  That doesn&#039;t seem that many, but I have no idea really.  
I guess I have 2 CPU cores which I could use
so that I could use a load balancer to spread the load among two processes, which is the node.js way of using all the cores.  But the load balancer
wouldn&#039;t be doing much less work than my server does, so might not be able to handle any extra load itself.  Or I could stick my handlers in a 
thread pool, using the &lt;code&gt;runAsync&lt;/code&gt; attribute of my &lt;code&gt;@Handler&lt;/code&gt; annotation.  
So a low cost commodity server could handle nearly 2500 simultaneous calls.  Still not many?  Again, I really don&#039;t know.  But I should say that I 
didn&#039;t try optimising the server.  My packet sizes are based on sending one packet of sound data every 12 milliseconds.  
Perhaps I could get away with sending them less frequently which might improve throughput and still have good call quality with low latency.  
Who knows - anyone wanting to optimise it, let me know the results!  One thing for sure is that a server using one thread per connection with 
2500 simultaneous connections, will struggle.  While my 
&lt;a href=&#039;/pebble/2011/03/05/1299360960000.html&#039; target=&#039;_blank&#039;&gt;previous blog article&lt;/a&gt; 
showed it is possible to have many thousand threads open,
the context switching is likely to become the bottle neck.  A non-blocking server is certainly the way forward for this use case.
&lt;br&gt;
&lt;br&gt;
Download the code &lt;a href=&#039;/pebble/files/nio-apps-framework-201105220028.zip&#039;&gt;here&lt;/a&gt;.
&lt;br&gt;
&lt;br&gt;
Copyright &amp;copy; 2011 Ant Kutschera
&lt;br&gt;
&lt;br&gt;
&lt;div class=&#034;tags&#034;&gt;&lt;span&gt;Social Bookmarks : &lt;/span&gt;&amp;nbsp;&lt;a href=&#034;http://slashdot.org/bookmark.pl?url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Slash Dot&#034;&gt;&lt;img src=&#034;common/images/slashdot.png&#034; alt=&#034;Add this post to Slashdot&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://digg.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Digg this post&#034;&gt;&lt;img src=&#034;common/images/digg.png&#034; alt=&#034;Add this post to Digg&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://reddit.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Reddit&#034;&gt;&lt;img src=&#034;common/images/reddit.png&#034; alt=&#034;Add this post to Reddit&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://del.icio.us/post?url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Save this post to Del.icio.us&#034;&gt;&lt;img src=&#034;common/images/delicious.png&#034; alt=&#034;Add this post to Delicious&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.stumbleupon.com/submit?url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Stumble this post&#034;&gt;&lt;img src=&#034;common/images/stumbleupon.png&#034; alt=&#034;Add this post to Stumble it&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.google.com/bookmarks/mark?op=edit&amp;amp;bkmk=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Google&#034;&gt;&lt;img src=&#034;common/images/google.png&#034; alt=&#034;Add this post to Google&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://technorati.com/faves?add=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Technorati&#034;&gt;&lt;img src=&#034;common/images/technorati.png&#034; alt=&#034;Add this post to Technorati&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.bloglines.com/sub/http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Bloglines&#034;&gt;&lt;img src=&#034;common/images/bloglines.png&#034; alt=&#034;Add this post to Bloglines&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.facebook.com/share.php?u=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Facebook&#034;&gt;&lt;img src=&#034;common/images/facebook.png&#034; alt=&#034;Add this post to Facebook&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.furl.net/storeIt.jsp?u=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;t=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Furl&#034;&gt;&lt;img src=&#034;common/images/furl.png&#034; alt=&#034;Add this post to Furl&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;amp;url=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;title=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Windows Live&#034;&gt;&lt;img src=&#034;common/images/windowslive.png&#034; alt=&#034;Add this post to Windows Live&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;amp;u=http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html&amp;amp;t=Java+non-blocking+servers%2C+and+what+I+expect+node.js+to+do+if+it+is+to+become+mature&#034; target=&#034;_blank&#034; title=&#034;Add this post to Yahoo!&#034;&gt;&lt;img src=&#034;common/images/yahoo.png&#034; alt=&#034;Add this post to Yahoo!&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&lt;/div&gt;
        </description>
      
      
    
    
    
    <comments>http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html#comments</comments>
    <guid isPermaLink="true">http://blog.maxant.co.uk:80/pebble/2011/05/22/1306092969466.html</guid>
    <pubDate>Sun, 22 May 2011 19:36:09 GMT</pubDate>
  </item>
  
  <item>
    <title>Persistent State Machine with Apache SCXML</title>
    <link>http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html</link>
    
      
        <description>
          The source code for this blog article can be downloaded &lt;a href=&#039;/pebble/files/SCXMLDemo2.zip&#039;&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;br&gt;
I&#039;m bored of reinventing the wheel.  Everytime I need a state machine to ensure my states traverse only valid transitions, I find myself either not bothering, because I trust my coding (and write all the necessary unit tests of course), or writing very similar code over again.&lt;br&gt;
&lt;br&gt;
So I started wondering if there was a configurable state machine out there somewhere, and in no time at all Google gave me a link to &lt;a target=&#039;blank&#039; href=&#039;http://commons.apache.org/scxml/&#039;&gt;SCXML from Apache&lt;/a&gt;.  Apache SCXML is an implementation of a configurable state machine based on the &lt;a target=&#039;_blank&#039; href=&#039;http://www.w3.org/TR/scxml/&#039;&gt;SCXML working draft&lt;/a&gt; from W3C.&lt;br&gt;
&lt;br&gt;
I started by taking a look at what it does and how it works, always keeping in mind my requirements based on previous projects.  The main question was how I could use a state machine in a persistent entity so that when an attempt is made to change the state, the state machine validated the attempt, ensuring only valid transitions are carried out.  That meant two things:&lt;br&gt;
&lt;ul&gt;
	&lt;li&gt;The state machine had to be able to have its current state set to any state.  If I load an object
		with state out of the database, I need to be able to set that state in the state machine so that 
		it checks any attempts to change state, based on this starting state.&lt;/li&gt;
	&lt;li&gt;The state machine had to fit into a JPA entity class so that I could persist and load the state.&lt;/li&gt;
&lt;/ul&gt;
&lt;br&gt;
Apache SCXML doesn&#039;t come with great documentation but if you look around, it has some &#034;use cases&#034; which are examples of how you can use it.  It comes with the class org.apache.commons.scxml.env.AbstractStateMachine which uses reflection to trigger transitions.  I went for a slightly different approach and created the uk.co.maxant.demo.scxml.util.AbstractStateMachine, which wraps an instance of the SCXMLExecutor (the &#034;engine&#034;, or state machine itself).  By wrapping the state machine, I am able to provide two extra benefits:&lt;br&gt;
&lt;ul&gt;
	&lt;li&gt;I can construct the state machine using the starting state out of a persisted entity, rather than 
		being forced to use the state charts initial state.  The implementation details of this construction 
		are a little complicated so my abstract wrapper can hide the details from the caller who is more
		interested in writing some business code, rather than boiler plate code.&lt;/li&gt;
	&lt;li&gt;I can enforce only valid state transitions, in that before performing a transition, I can use the
		state machine to check if its a valid transition from the current state.  Apache SCXMLs default 
		handling means that if you try to set the state to an illegal state, the state machine simply does
		nothing.  I prefer to be a little harsher and throw an IllegalStateException!&lt;/li&gt;
&lt;/ul&gt;
&lt;br&gt;
The implementation of the AbstractStateMachine contains trigger methods for changing state via transition events.  Each event makes a simple call to the &lt;code&gt;AbstractStateMachine.trigger(String)&lt;/code&gt; method which first of all checks that the current state allows the transition, and second of all delegates the transition to the wrapped state machine instance.  If the requested state transition is illegal, then an &lt;code&gt;IllegalStateException&lt;/code&gt; with details of the problem is thrown.  I too, could have also used reflection like the Apache example, but prefer to write more readable code for this Blog.&lt;br&gt;
&lt;br&gt;
Apache SCXML is built up by creating an &lt;code&gt;SCXML&lt;/code&gt; instance which is based upon the configuration which is an XML representation of the state chart and can be generated from UML.  As such, this configuration has an initial state, as defined in your state chart.  You then create an instance of the engine (state machine, &lt;code&gt;SCXMLExecutor&lt;/code&gt;) which is responsible for running with the configuration.  For performance reasons, the configuration should only be created once, as it parses the XML document.  In my demo, I instantiated it at class load time in the subclass of &lt;code&gt;AbstractStateMachine&lt;/code&gt;.&lt;br&gt;
&lt;br&gt;
So what do you do, if you are loading an object from a persistent store like a database and you want to instantiate your state machine (&lt;code&gt;SCXMLExecutor&lt;/code&gt;) with a state other than the initial state?  Well, it&#039;s quite easy, you simply use the API to modify the current state of the state machine (&lt;code&gt;SCXMLExecutor&lt;/code&gt;) instance and set the initial state to be that, which your persisted entity currently has.  The method isn&#039;t &lt;code&gt;setCurrentState()&lt;/code&gt;, rather you use the current state object, and remove its states and set the relevant state which you retrieved from the configuration (&lt;code&gt;SCXML&lt;/code&gt;).  Have a look at &lt;code&gt;AbstractStateMachine.setInitialState(SCXMLExecutor, String)&lt;/code&gt; to see how.  Thanks to the SCXML team for showing me how to do this!&lt;br&gt;
&lt;br&gt;
So having done all that, I was now in a position to use the state machine to manage the state in a persistent entity.  I created a database table with a &lt;code&gt;varchar&lt;/code&gt; column for holding my state, and primary key.  In the real world, the state would be part of a much larger entity with other fields.  I then setup my Eclipse project to contain the JPA facet and by right clicking on the project was able to generate my JPA entity classes from the table, such as shown in the &lt;code&gt;SomethingPersistentWithState&lt;/code&gt; class.  The only special thing I did, was to select &#034;property based access&#034; as the way in which JPA accesses the attributes.  Normally, and by default, JPA uses field based access, i.e. it uses reflection at runtime to get and set the class attributes.  By selecting &#034;property based access&#034;, Eclipse generates an additional Annotation on my entity class: &lt;code&gt;@Access(AccessType.PROPERTY)&lt;/code&gt;.  I then had only three things to do:&lt;br&gt;
&lt;ul&gt;
	&lt;li&gt;Change the &#034;state&#034; class attribute from a &lt;code&gt;String&lt;/code&gt; into an instance of
		&lt;code&gt;StateMachineDemo&lt;/code&gt;, which is the implementation of &lt;code&gt;AbstractStateMachine&lt;/code&gt;.
		I can do this, because the above Annotation means that JPA doesn&#039;t care how I implement the 
		attribute, is will always use bean conform accessors to set/get the state of my entity, namely the
		&lt;code&gt;String getState()&lt;/code&gt; and &lt;code&gt;void setState(String)&lt;/code&gt; methods.&lt;/li&gt;
	&lt;li&gt;Change the generated &lt;code&gt;void setState(String)&lt;/code&gt; method visibility to become private, so
		that no one could explicitly set the state of my entity.  The method needs to exist, so that JPA can 
		access the attribute to persist it, but JPA can happily live with the method being private.&lt;/li&gt;
	&lt;li&gt;Add methods for each transition, which simply delegate the call to the state machine.  Users of the 
		persistent entity use these trigger methods to change the state, rather than calling
		&lt;code&gt;void setState(String)&lt;/code&gt; on the entity.&lt;/li&gt;
&lt;/ul&gt;
&lt;br&gt;
These changes are all shown/documented in the &lt;code&gt;StateMachineDemo&lt;/code&gt; class.&lt;br&gt;
&lt;br&gt;
To demonstrate the state machine working, as well as it being used in a persistent environment, have a look at the JUnit test case &lt;code&gt;StateMachineDemoTest&lt;/code&gt;.  This class contains tests for setting any state during construction, tests for state transitions proving that only valid ones are allowed, as well as reading/writing an entity containing state to the database and updating the state along the way.
&lt;br&gt;
&lt;br&gt;
Download the source &lt;a href=&#039;/pebble/files/SCXMLDemo2.zip&#039;&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;br&gt;
&amp;copy; 2010, Ant Kutschera&lt;div class=&#034;tags&#034;&gt;&lt;span&gt;Social Bookmarks : &lt;/span&gt;&amp;nbsp;&lt;a href=&#034;http://slashdot.org/bookmark.pl?url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Slash Dot&#034;&gt;&lt;img src=&#034;common/images/slashdot.png&#034; alt=&#034;Add this post to Slashdot&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://digg.com/submit?url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Digg this post&#034;&gt;&lt;img src=&#034;common/images/digg.png&#034; alt=&#034;Add this post to Digg&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://reddit.com/submit?url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Reddit&#034;&gt;&lt;img src=&#034;common/images/reddit.png&#034; alt=&#034;Add this post to Reddit&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://del.icio.us/post?url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Save this post to Del.icio.us&#034;&gt;&lt;img src=&#034;common/images/delicious.png&#034; alt=&#034;Add this post to Delicious&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.stumbleupon.com/submit?url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Stumble this post&#034;&gt;&lt;img src=&#034;common/images/stumbleupon.png&#034; alt=&#034;Add this post to Stumble it&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.google.com/bookmarks/mark?op=edit&amp;amp;bkmk=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Google&#034;&gt;&lt;img src=&#034;common/images/google.png&#034; alt=&#034;Add this post to Google&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://technorati.com/faves?add=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Technorati&#034;&gt;&lt;img src=&#034;common/images/technorati.png&#034; alt=&#034;Add this post to Technorati&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.bloglines.com/sub/http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Bloglines&#034;&gt;&lt;img src=&#034;common/images/bloglines.png&#034; alt=&#034;Add this post to Bloglines&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.facebook.com/share.php?u=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&#034; target=&#034;_blank&#034; title=&#034;Add this post to Facebook&#034;&gt;&lt;img src=&#034;common/images/facebook.png&#034; alt=&#034;Add this post to Facebook&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://www.furl.net/storeIt.jsp?u=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;t=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Furl&#034;&gt;&lt;img src=&#034;common/images/furl.png&#034; alt=&#034;Add this post to Furl&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;amp;url=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;title=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Windows Live&#034;&gt;&lt;img src=&#034;common/images/windowslive.png&#034; alt=&#034;Add this post to Windows Live&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;a href=&#034;http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&amp;amp;u=http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html&amp;amp;t=Persistent+State+Machine+with+Apache+SCXML&#034; target=&#034;_blank&#034; title=&#034;Add this post to Yahoo!&#034;&gt;&lt;img src=&#034;common/images/yahoo.png&#034; alt=&#034;Add this post to Yahoo!&#034; border=&#034;0&#034; /&gt;&lt;/a&gt;&lt;/div&gt;
        </description>
      
      
    
    
    
    <comments>http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html#comments</comments>
    <guid isPermaLink="true">http://blog.maxant.co.uk:80/pebble/2010/08/26/1282857660000.html</guid>
    <pubDate>Thu, 26 Aug 2010 21:21:00 GMT</pubDate>
  </item>
  
  </channel>
</rss>

