The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Writing a RESTful and Comet based PubSub application using Atmosphere in less than 10 lines

Posted by jfarcand on November 3, 2009 at 12:58 PM PST

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

Boo

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:

    @Suspend
@GET
@Path("/{topic}")
@Produces("text/plain;charset=ISO-8859-1")
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:

    @GET
@Path("/{topic}/{message}")
@Produces("text/plain;charset=ISO-8859-1")
@Broadcast
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!

technorati:

Related Topics >> Blogs      General      Web Applications      
Comments
Comments are listed in date ascending order (oldest first)