Over a million developers have joined DZone.
Platinum Partner

Writing a RESTful and Comet Based PubSub Application Using Atmosphere in Less Than 10 Lines

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

Writing a publisher/subscriber (PubSub) is quite simple with Atmosphere using the atmosphere-jersey module.

The main idea here is to use Comet for suspending the response when a client subscribe to a topic, and use REST for publishing messages to the those suspended responses. First, let’s bind our application to the root uri using the @path annotation

package org.atmosphere.samples.pubsub;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import org.atmosphere.annotation.Broadcast;
import org.atmosphere.annotation.Schedule;
import org.atmosphere.annotation.Suspend;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.jersey.Broadcastable;

@Path("/") public class PubSub {

Next, let’s implement the subscribe operation by using the @Suspend and inject our Atmosphere’s Broadcaster using the @PathParam annotation:

public Broadcastable subscribe(@PathParam("topic") Broadcaster topic) {
return new Broadcastable("",topic);


The code above will be invoked when we want to create a new topic (@Path("/{topic}"), we will return a Broadcastable instance which will tell Atmosphere to use the passed Broadcaster, who got injected using the @PathParam, when broadcasting {topic}. Finally, the underlying response will be suspended forever via @Suspend annotation. Next, let’s implement the publish operation:

public Broadcastable publish(@PathParam("topic") Broadcaster topic,
@PathParam("message") String message){

return new Broadcastable(message,topic);

To publish, we just need to send a uri that takes the form of "/{topic}/{message}" as defined by @Path("/{topic}/{message}") and again, the Broadcaster we want to use to broadcast messagse will be injected based on the {topic} value. Finally, we just return a Broadcastable object and let Atmosphere broadcast the value to all suspended connections. That’s it! Now we can see it in action by doing:


Create a topic
curl http://localhost:8080/atmosphere-pubsub/myAtmosphereTopic
Publish to that topic
curl http://localhost:8080/atmosphere-pubsub/myAtmosphereTopic/Atmosphere_is_cool


The source for the entire sample can be viewed here. Really simple, is it?

For any questions or to download Atmosphere, go to our main site and use our Nabble forum (no subscription needed) or follow us on Twitter and tweet your questions there!

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}