Grizzly 2.0 and Comet

With the release of Grizzly 2.0, I'd like to highlight one of its newest features: comet support. When implementing support for comet in grizzly 2.0, I tried as best I could to make it API compatible with your 1.9 applications. That said, there are a handful of changes that were made to clean things up a little and simplify some of the implementation details.  I'll outline the changes you'll need to make to existing apps before building a new one from scratch. Most of the changes are largely cosmetic. The first change you'll notice is that the package names have changed. With the advent of 2.0, grizzly now lives under the org.glassfish.grizzly rather than com.sun.grizzly. CometHandler is the core of any comet application code and it, too, has received a minor makeover:

  • attach() has been removed from the interface. This won't actually affect your code unless you happen to have used @Override. This method has been typically used to attach things like the HttpRequest object to your CometHandler instance. In reality, this kind of information can be passed via the constructor or a method on your subclass. Grizzly doesn't actually reference this method or the attachment in any way so it has been removed from the interface. You are, of course, welcome to continue using attach() if you'd like. But since Grizzly never uses it internally, there's no sense in forcing all implementations to implement it.
  • Four new methods have been added added to the interface:
    1. Response getResponse();
    2. void setResponse(Response response);
    3. CometContext<E> getCometContext();
    4. void setCometContext(CometContext<E> context);

    Your CometHandler implementation needs only provide these getters/setters and the fields they imply. Grizzly will handle the setting of those values itself. It didn't make it into 2.0 (because I got sidetracked) but 2.0.1 will have a DefaultCometHandler that takes care of that for you if you choose. The type of <E> should be consistent with the data type you want to pass to your handlers when an event occurs. Typically, this will simply be a String but, of course, could be almost anything.

  • The type of comet events have been modernized. In 1.9 you had a set of int constants to manage. In 2.0, I've changed them to an enum. This probably won't affect your code overly much but you do need to change any thing like CometEvent.READ to CometEvent.Type.READ. Enum comparisons being what they are, everything else should just compile as long as you used the named constants.
  • A great number of items have been deprecated as well. The compiler will highlight these for you. All the deprecated methods should continue to work as you would expect, but I would recommend changing over when you get the chance. (You're already having to tweak code anyway.) We've striven to keep things API compatible as much as possible to ease the transition, but these methods might go away in the future so it's best to be prepared.

    The riskiest change, to my mind, is that the execution type has been removed. The execution model of grizzly 2.0 makes supporting that feature complicated. However, when examining every comet app and unit test I could find, I didn't find that this feature was really ever used that much anyway. Indeed, when asked about it some of the original authors weren't really entirely sure about the feature anyway. If you find that you really need that feature the decision can be readdressed. But I have to warn you, prepare yourself for some disappointment because it seems unlikely to happen. But you never know.

That should cover the changes you'll see. There are a number of other changes behind the scenes, of course, but hopefully we've done a good job of shielding you from those. Now that we've seen what changes you need to make to an existing application, let's see what it takes to write a new one. With 2.0, creating a grizzly instance to run your apps becomes much, much simpler. From here on out, we'll take a look at the comet click counter example you can find in the samples folder of the source repository.

To start grizzly, you just need a few lines of code:

        HttpServer httpServer = HttpServer.createSimpleServer("./", PORT);
        httpServer.getServerConfiguration().addHttpHandler(new ServletHandler(new LongPollingServlet()),
            QUERY_PATH);
        final Collection listeners = httpServer.getListeners();
        for (NetworkListener listener : listeners) {
            listener.registerAddOn(new CometAddOn());
        }
        httpServer.start();

This snippet sets up all the HTTP bits you'll need to serve up your comet application. With that set up, the next piece is the servlet manage your requests and the handler that provides your application logic.

public class LongPollingServlet extends HttpServlet {
    final AtomicInteger counter = new AtomicInteger();
    private static final long serialVersionUID = 1L;
    private String contextPath = null;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext context = config.getServletContext();
        contextPath = context.getContextPath() + "/long_polling";
        CometEngine engine = CometEngine.getEngine();
        CometContext cometContext = engine.register(contextPath);
        cometContext.setExpirationDelay(5 * 30 * 1000);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(contextPath);
        final int hash = context.addCometHandler(new CounterHandler(res, counter));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        counter.incrementAndGet();
        CometContext context = CometEngine.getEngine().getCometContext(contextPath);
        context.notify(null);

        PrintWriter writer = res.getWriter();
        writer.write("success");
        writer.flush();
    }
}
public class CounterHandler extends DefaultCometHandler {
    private HttpServletResponse httpResponse;
    private AtomicInteger counter;

    CounterHandler(HttpServletResponse httpResponse, final AtomicInteger counter) {
        this.httpResponse = httpResponse;
        this.counter = counter;
    }

    public void onEvent(CometEvent event) throws IOException {
        if (CometEvent.Type.NOTIFY == event.getType()) {
            httpResponse.addHeader("X-JSON", "{\"counter\":" + counter.get() + " }");
            PrintWriter writer = httpResponse.getWriter();
            writer.write("success");
            writer.flush();
            event.getCometContext().resumeCometHandler(this);
        }
    }

    public void onInterrupt(CometEvent event) throws IOException {
        httpResponse.addHeader("X-JSON", "{\"counter\":" + counter.get() + " }");
       PrintWriter writer = httpResponse.getWriter();
        writer.write("success");
        writer.flush();
    }
}

The init() in the servlet registers the comet context we'll use to track all the handlers that various requests will park. That's the java code you need. Without overdoing it, a quick look at the javascript side should cover it.

var counter = {
      'poll' : function() {
         new Ajax.Request('long_polling', {
            method : 'GET',
            onSuccess : counter.update
         });
      },
      'increment' : function() {
         new Ajax.Request('long_polling', {
            method : 'POST'
         });
      },
      'update' : function(req, json) {
         $('count').innerHTML = json.counter;
         counter.poll();
      }
}

When the page loads, it makes the initial GET request to the server. That request gets parked in doGet() above. That request will stay open until the user clicks on a link in the html from the sample application. That click triggers a POST post. In doPost(), we call notify() on the context which triggers the parked CometHandler to finally respond to that initial GET request. Once that request finally responds, the javascript code will make another GET which gets parked and the process repeats itself. In this way multiple clients can track and update the counter on the server.

This is just a basic example, of course, ut it covers all the basic building blocks you'll need for more complex applications. For more examples, you can look through the sample applications. There are more examples in 1.9 than 2.0 right but, changes listed above aside, should help you find the answers. We're putting more and more documentation up at the website and, of course, we have mailing lists where you can post your questions. I think you'll find that 2.0 is much more pleasant to work with. So please take a look and give us some feedback on the lists. We'd love to hear about your experiences.