Implementation of {@link AtmosphereHandler} allows creation ofevent-driven web applications which are hosted in the browser. An {@link AtmosphereHandler} allows a web application to suspend and resumean http response. An http response can be suspended {@link AtmosphereResource#suspend()}and later resume via {@link AtmosphereResource#resume()}. Messages can also be shared between suspended response and their associated {@link AtmosphereHandler}using a {@link Broadcaster}. Any invocation of {@link Broadcaster#broadcast(java.lang.Object)}will allow a suspended response to write the content of the message {@link AtmosphereHandler#onStateChange(org.atmosphere.cpr.AtmosphereResourceEvent)}.
A class implementing {@link AtmosphereHandler} must be thread safe For example, a simple Chat based AtmosphereHandler will take the form of public AtmosphereResource<HttpServletRequest, HttpServletResponse> onRequest(AtmosphereResource<HttpServletRequest, HttpServletResponse> event) throws IOException { HttpServletRequest req = event.getRequest(); HttpServletResponse res = event.getResponse(); res.setContentType("text/html"); res.addHeader("Cache-Control", "private"); res.addHeader("Pragma", "no-cache"); if (req.getMethod().equalsIgnoreCase("GET")) { event.suspend(); } else if (req.getMethod().equalsIgnoreCase("POST")) { res.setCharacterEncoding("UTF-8"); String action = req.getParameterValues("action")[0]; String name = req.getParameterValues("name")[0]; if ("login".equals(action)) { event.getBroadcaster().broadcast( BEGIN_SCRIPT_TAG + toJsonp("System Message from " + event.getWebServerName(), name + " has joined.") + END_SCRIPT_TAG); res.getWriter().write("success"); res.getWriter().flush(); } else if ("post".equals(action)) { String message = req.getParameterValues("message")[0]; event.getBroadcaster().broadcast(BEGIN_SCRIPT_TAG + toJsonp(name, message) + END_SCRIPT_TAG); res.getWriter().write("success"); res.getWriter().flush(); } else { res.setStatus(422); res.getWriter().write("success"); res.getWriter().flush(); } } } public AtmosphereResource<HttpServletRequest, HttpServletResponse> onStateChange(AtmosphereResource<HttpServletRequest, HttpServletResponse> event) throws IOException { HttpServletRequest req = event.getRequest(); HttpServletResponse res = event.getResponse(); if (event.isResuming() || event.isResumedOnTimedout()) { String script = BEGIN_SCRIPT_TAG + "window.parent.app.listen();\n" + END_SCRIPT_TAG; res.getWriter().write(script); res.getWriter().flush(); } else { res.getWriter().write(event.getMessage().toString()); res.getWriter().flush(); } }
@author Jeanfrancois Arcand