XMPP PubSub

I’ve been trying to get pubsub to work on Openfire and Smack for about a week. Finally I’ve managed to get it working this morning so I’ve decided to document seeing that it quite difficult to get all the info in 1 place. The solutions came from various place but in particular from ignite realtime forum and stackoverflow thread. So many thanks to those folks over there.

Here is my setup
1. Openfire server 3.6.4. Setup a few account for testing. Note: you can use any XMPP server but you have to make sure that the pubsub service is running. One way to do this is to use Pidgin, install the XMPP Service Discovery plugin and introspect the server. You should see something like this.

2. Smack from SVN. The release version does not have support for pubsub viz. there are nice classes like PubSubManager, etc. You will have to construct the pubsub stanza yourself.

Here is the code to create a publish an item

//Create a XMPPConnection
SASLAuthentication.supportSASLMechanism(“PLAIN”);
//For debugging
XMPPConnection.DEBUG_ENABLED = true;

ConnectionConfiguration config = new ConnectionConfiguration(HOST, PORT);
XMPPConnection conn = new XMPPConnection(config);
conn.connect();
conn.login(USER, PASSWORD);

//Create the topic
ConfigureForm f = new ConfigureForm(FormType.submit);
//Set some params for the topic – according to your requirement
f.setPersistentItems(false);
f.setDeliverPayloads(true);
f.setAccessModel(AccessModel.open);
f.setPublishModel(PublishModel.open);
f.setSubscribe(true);

//Note that you need to set the second parameter for openfire. This is the
//same as the pubsub service name
PubSubManager mgr = new PubSubManager(conn, “pubsub.” + HOST);
Node n = mgr.createNode(TOPIC, f);

//Now publish something – See Javadocs
SimplePayload payload = new SimplePayload(“book”,”pubsub:test:book”, “”);

PayloadItem payloadItem = new PayloadItem(null, payload);
((LeafNode)n).publish(payloadItem);

If you writing a real app, you would probably not use SimplePlayload but extend from org.jivesoftware.smackx.pubsub.Item.

Finally here is the code to subscribe to a topic

//mgr == PubSubManager
Node n = mgr.getNode(TOPIC);
n.addItemEventListener(new ItemEventListener() {
public void handlePublishedItems(ItemPublishEvent items) {
//Handle items
}
);
n.subscribe(conn.getUser());

Good luck!

Technorati Tags: , , , ,

Advertisements
%d bloggers like this: