* @param atmoResource An {@link AtmosphereResourceEvent}
* @throws java.io.IOException
*/
public void onRequest(AtmosphereResource<HttpServletRequest, HttpServletResponse> atmoResource) throws IOException{
HttpServletRequest request = atmoResource.getRequest();
HttpServletResponse response = atmoResource.getResponse();
String action = request.getParameter("action");
String sessionId = request.getSession().getId();
HttpSession session = request.getSession();
Broadcaster myBroadcasterFollower = (Broadcaster) session.getAttribute(sessionId);
if (action != null) {
if ("login".equals(action)) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
if (name == null) {
logger.error("Name cannot be null");
return;
}
session.setAttribute("name", name);
myBroadcasterFollower.broadcast(BEGIN_SCRIPT_TAG
+ toJsonp("Welcome back", name)
+ END_SCRIPT_TAG);
// Store the Broadcaster associated with this user so
// we can retrieve it for supporting follower.
atmoResource.getAtmosphereConfig().getServletContext().setAttribute(name, myBroadcasterFollower);
} else if ("post".equals(action)) {
String message = request.getParameter("message");
String callback = request.getParameter("callback");
if (message == null) {
logger.error("Message cannot be null");
return;
}
if (callback == null) {
callback = "alert";
}
if (myBroadcasterFollower != null){
myBroadcasterFollower.broadcast("<script id='comet_" + counter++ + "'>"
+ "window.parent." + callback + "(" + message + ");</script>");
} else {
throw new RuntimeException("Broadcaster was null");
}
response.getWriter().println("ok");
} else if ("start".equals(action)) {
String message = "{ message : 'Welcome'}";
response.setContentType("text/html;charset=ISO-8859-1");
String callback = request.getParameter("callback");
if (callback == null) {
callback = "alert";
}
// Use one Broadcaster per AtmosphereResource
try {
atmoResource.setBroadcaster(BroadcasterFactory.getDefault().get());
} catch (Throwable t){
throw new IOException(t);
}
// Create a Broadcaster based on this session id.
myBroadcasterFollower = atmoResource.getBroadcaster();
atmoResource.suspend();
session.setAttribute("atmoResource", atmoResource);
session.setAttribute(sessionId, myBroadcasterFollower);
response.getWriter().println("<script id='comet_" + counter++ + "'>"
+ "window.parent." + callback + "(" + message + ");</script>");
response.getWriter().println(startingMessage);
response.getWriter().flush();
} else if ("following".equals(action)) {
response.setContentType("text/html");
String follow = request.getParameter("message");
String name = (String)session.getAttribute("name");
if (follow == null) {
logger.error("Message cannot be null");