Using CometD’s hidden subscribeProps

CometD is an open source implementation of the Bayeux protocol in the Comet pattern. Basically it is used for AJAX push eventing.

To start recieving messages we simply subscribe to a channel with a callback method.

CometD gives us a great API for fined grained authorization of channel operations on the server.  They even have documentation on how to use it http://cometd.org/documentation/2.x/cometd-java/server/authorizers.

The method signature for the authorize method looks like this:

public Result authorize(Operation operation, ChannelId channel, ServerSession session, ServerMessage message);{
  return Result.ignore();
}

Specifically, it is obvious how useful being able to control who can and cannot subscribe to our channel may be important.

We can key off of the type of operation (one of Publish, Create, Subscribe), some ServerSession information, the ChannelId, or part of the message. However, sometimes we may need the client to send us an extra piece of information, and the data we send in the message object is a great place for that. If we are trying to publish a message that works perfectly. We can send the data like this:

cometd.publish('/mychannel', { mydata: { foo: 'bar' } });

and retrieve it like this

public Result authorize(Operation operation, ChannelId channel, ServerSession session, ServerMessage message);{
  String bar = (String)message.getDataAsMap().get("foo");
}

However, on the publish there is no data object. On the client, we subscribe like this:

var subscription = cometd.subscribe('/mychannel', callbackFunction);

This seems like a horrible impasse, but fortunately there is a solution.

You can read the whole cometD documentation on their website, and not find a solution. If we look at the source code, however, we’ll see that the subscribe function actually has a third parameter. Along with channel and callback there is something called subscribeProps.

The documentation in javascript describes the parameter this way:

* @param subscribeProps an object to be merged with the subscribe message

So now our subscribe call looks like this:

var subscription = cometd.subscribe('/mychannel', callbackFunction, { foo: 'bar' });

All that is left is to retrive the information we sent to our Authorizer. The subscribeProps do not get returned in the message.getDataAsMap() or message.getData() calls (like it does in the publish call). Instead, we simply use the message.get() method like this:

public Result authorize(Operation operation, ChannelId channel, ServerSession session, ServerMessage message);{
  String bar = (String)message.get("foo");
}

Now you know how to send and retrieve data as part of a cometD subscription request using the CometD’s “hidden” subscribeProps.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*