Quantcast
Channel: Methodology Center – Java Development Philippines – Java Developers – Manila | Ideyatech
Viewing all articles
Browse latest Browse all 33

Push Notifications using Atmosphere and Spring

$
0
0

Most recent applications rely on push notifications to alert users of events that they are interested in. Just like how Facebook alerts users of new friend requests or messages.

notification

This can be implemented in several ways… the simplest is to display the alert when page is loaded or refreshed but this is not very user friendly as user will only be notified when they refresh the page. Alternatively, users can be alerted in a more real-time fashion by polling the server for updates. This works, but when there are thousands of users, this can be a resource hog because each user will have to several poll request every minute.

The ideal solution is to use non-blocking IO technology or websockets to keep the connection open and avoid constant polling. Below is a sample implementation on how to achieve this using Atmosphere and Spring.

STEP 1: Include Atmosphere libraries in your Spring project. In your pom.xml, add Maven to atmosphere library.

		<dependency>
			<groupId>org.atmosphere</groupId>
			<artifactId>atmosphere-runtime</artifactId>
			<version>${org.atmosphere-version}</version>
		</dependency>

STEP 2: Update web.xml to use the Atmosphere servlet. Add the atmosphere servlet that will handle the NIO requests. This servlet will receive the NIO calls and uses retains your Spring configuration. The Atmosphere servlet should have different URL pattern so that only NIO calls are forwarded to Atmosphere.

<servlet>
        <servlet-name>notification</servlet-name>
        <servlet-class>org.atmosphere.cpr.MeteorServlet</servlet-class>
        <init-param>
            <param-name>org.atmosphere.servlet</param-name>
            <param-value>org.springframework.web.servlet.DispatcherServlet</param-value>
        </init-param>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
        <async-supported>true</async-supported>        
    </servlet>
    
  <servlet-mapping>
	<servlet-name>notification</servlet-name>
	<url-pattern>/n/*</url-pattern>
  </servlet-mapping>

STEP 3: Create Spring controller. Below is a sample code snippet to handle atmosphere request. This will be the URL to be invoked to retrieve the NIO request. Notice that the request is suspended by Atmosphere.

@Controller
public class NotifyHandler {

    @Autowired
    private NotificationService notificationService;
	
    @RequestMapping(value = "/notify/{userId}")
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<String> watch(@PathVariable("userId") String userId,
                      HttpServletRequest request) throws Exception {
        //Atmosphere framework puts filter/servlet that adds ATMOSPHERE_RESOURCE to all requests
        AtmosphereResource resource = (AtmosphereResource) request.getAttribute(ApplicationConfig.ATMOSPHERE_RESOURCE);

        //suspending resource to keep connection
        resource.suspend();

        //find broadcaster, second parameter says to create broadcaster if it doesn't exist
        Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(userId,true);

        //saving resource for notifications
        broadcaster.addAtmosphereResource(resource);
        
        long nCount = notificationService.countNewPopup(new Long(userId));
        List<Notification> notifications = notificationService.findMostRecentPopup(new Long(userId));
        List<String> response = new ArrayList<String>();
        response.add(""+nCount);
        for (Notification n:notifications) {
        	response.add(n.getMessage());
        }
        return response;
    }
}

STEP 4: Broadcast message to appropriate users when needed. In your code, whenever a notification is triggered you may broadcast the message to recipient using the sample code below.

    Broadcaster b = BroadcasterFactory.getDefault().lookup(userId);
    if (b!=null) {
        long nCount = notificationDao.countNewPopup(new Long(userId));
        List<Notification> notifications = notificationDao.findMostRecentPopup(new Long(userId));
	StringBuffer response = new StringBuffer("[");
        response.append(nCount);
        for (Notification n:notifications) {
        	response.append(",\"")
        			.append(n.getMessage())
        			.append("\"");
        }
        response.append("]");
        b.broadcast(response.toString());
    }

STEP 5: Finally, include javascript to invoke Atmosphere library. The code below shows the snippet to invoke the URL.

$.atmosphere.subscribe(
                "/n/notify/1", // URL containing the atmosphere servlet
                callback, // javascript callback to handle the response
                $.atmosphere.request = { transport:"websocket", requestCount: 0 });

That’s it. The code snippets above is not complete and cannot not run by itself. The purpose of this post is just to provide directions on the steps needed to get push notification to work. Hope this gives you some direction on how to go about exploring push notification for your application.

The post Push Notifications using Atmosphere and Spring appeared first on Ideyatech - Java Development Outsourcing Philippines.


Viewing all articles
Browse latest Browse all 33

Trending Articles