You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PushRequestHandler.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server.communication;
  17. import java.io.IOException;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import javax.servlet.ServletConfig;
  21. import javax.servlet.ServletException;
  22. import org.atmosphere.cache.UUIDBroadcasterCache;
  23. import org.atmosphere.client.TrackMessageSizeInterceptor;
  24. import org.atmosphere.cpr.ApplicationConfig;
  25. import org.atmosphere.cpr.AtmosphereFramework;
  26. import org.atmosphere.cpr.AtmosphereFramework.AtmosphereHandlerWrapper;
  27. import org.atmosphere.cpr.AtmosphereHandler;
  28. import org.atmosphere.cpr.AtmosphereInterceptor;
  29. import org.atmosphere.cpr.AtmosphereRequestImpl;
  30. import org.atmosphere.cpr.AtmosphereResponseImpl;
  31. import org.atmosphere.interceptor.HeartbeatInterceptor;
  32. import org.atmosphere.util.VoidAnnotationProcessor;
  33. import com.vaadin.server.RequestHandler;
  34. import com.vaadin.server.ServiceDestroyEvent;
  35. import com.vaadin.server.ServiceDestroyListener;
  36. import com.vaadin.server.ServiceException;
  37. import com.vaadin.server.ServletPortletHelper;
  38. import com.vaadin.server.SessionExpiredHandler;
  39. import com.vaadin.server.VaadinRequest;
  40. import com.vaadin.server.VaadinResponse;
  41. import com.vaadin.server.VaadinServletRequest;
  42. import com.vaadin.server.VaadinServletResponse;
  43. import com.vaadin.server.VaadinServletService;
  44. import com.vaadin.server.VaadinSession;
  45. import com.vaadin.shared.communication.PushConstants;
  46. /**
  47. * Handles requests to open a push (bidirectional) communication channel between
  48. * the client and the server. After the initial request, communication through
  49. * the push channel is managed by {@link PushAtmosphereHandler} and
  50. * {@link PushHandler}
  51. *
  52. * @author Vaadin Ltd
  53. * @since 7.1
  54. */
  55. public class PushRequestHandler
  56. implements RequestHandler, SessionExpiredHandler {
  57. private AtmosphereFramework atmosphere;
  58. private PushHandler pushHandler;
  59. public PushRequestHandler(VaadinServletService service)
  60. throws ServiceException {
  61. service.addServiceDestroyListener(new ServiceDestroyListener() {
  62. @Override
  63. public void serviceDestroy(ServiceDestroyEvent event) {
  64. destroy();
  65. }
  66. });
  67. final ServletConfig vaadinServletConfig = service.getServlet()
  68. .getServletConfig();
  69. pushHandler = createPushHandler(service);
  70. atmosphere = getPreInitializedAtmosphere(vaadinServletConfig);
  71. if (atmosphere == null) {
  72. // Not initialized by JSR356WebsocketInitializer
  73. getLogger().fine("Initializing Atmosphere for servlet "
  74. + vaadinServletConfig.getServletName());
  75. try {
  76. atmosphere = initAtmosphere(vaadinServletConfig);
  77. } catch (Exception e) {
  78. getLogger().log(Level.WARNING,
  79. "Failed to initialize Atmosphere for "
  80. + service.getServlet().getServletName()
  81. + ". Push will not work.",
  82. e);
  83. return;
  84. }
  85. } else {
  86. getLogger().fine("Using pre-initialized Atmosphere for servlet "
  87. + vaadinServletConfig.getServletName());
  88. }
  89. pushHandler.setLongPollingSuspendTimeout(
  90. atmosphere.getAtmosphereConfig().getInitParameter(
  91. com.vaadin.server.Constants.SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING,
  92. -1));
  93. for (AtmosphereHandlerWrapper handlerWrapper : atmosphere
  94. .getAtmosphereHandlers().values()) {
  95. AtmosphereHandler handler = handlerWrapper.atmosphereHandler;
  96. if (handler instanceof PushAtmosphereHandler) {
  97. // Map the (possibly pre-initialized) handler to the actual push
  98. // handler
  99. ((PushAtmosphereHandler) handler).setPushHandler(pushHandler);
  100. }
  101. }
  102. }
  103. /**
  104. * Creates a push handler for this request handler.
  105. * <p>
  106. * Create your own request handler and override this method if you want to
  107. * customize the {@link PushHandler}, e.g. to dynamically decide the suspend
  108. * timeout.
  109. *
  110. * @since 7.6
  111. * @param service
  112. * the vaadin service
  113. * @return the push handler to use for this service
  114. */
  115. protected PushHandler createPushHandler(VaadinServletService service) {
  116. return new PushHandler(service);
  117. }
  118. private static final Logger getLogger() {
  119. return Logger.getLogger(PushRequestHandler.class.getName());
  120. }
  121. /**
  122. * Returns an AtmosphereFramework instance which was initialized in the
  123. * servlet context init phase by {@link JSR356WebsocketInitializer}, if such
  124. * exists
  125. */
  126. private AtmosphereFramework getPreInitializedAtmosphere(
  127. ServletConfig vaadinServletConfig) {
  128. String attributeName = JSR356WebsocketInitializer
  129. .getAttributeName(vaadinServletConfig.getServletName());
  130. Object framework = vaadinServletConfig.getServletContext()
  131. .getAttribute(attributeName);
  132. if (framework != null && framework instanceof AtmosphereFramework) {
  133. return (AtmosphereFramework) framework;
  134. }
  135. return null;
  136. }
  137. /**
  138. * Initializes Atmosphere for the given ServletConfiguration
  139. *
  140. * @since 7.5.0
  141. * @param vaadinServletConfig
  142. * The servlet configuration for the servlet which should have
  143. * Atmosphere support
  144. */
  145. static AtmosphereFramework initAtmosphere(
  146. final ServletConfig vaadinServletConfig) {
  147. AtmosphereFramework atmosphere = new AtmosphereFramework(false, false) {
  148. @Override
  149. protected void analytics() {
  150. // Overridden to disable version number check
  151. }
  152. @Override
  153. public AtmosphereFramework addInitParameter(String name,
  154. String value) {
  155. if (vaadinServletConfig.getInitParameter(name) == null) {
  156. super.addInitParameter(name, value);
  157. }
  158. return this;
  159. }
  160. };
  161. atmosphere.addAtmosphereHandler("/*", new PushAtmosphereHandler());
  162. atmosphere.addInitParameter(ApplicationConfig.BROADCASTER_CACHE,
  163. UUIDBroadcasterCache.class.getName());
  164. atmosphere.addInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR,
  165. VoidAnnotationProcessor.class.getName());
  166. atmosphere.addInitParameter(ApplicationConfig.PROPERTY_SESSION_SUPPORT,
  167. "true");
  168. atmosphere.addInitParameter(ApplicationConfig.MESSAGE_DELIMITER,
  169. String.valueOf(PushConstants.MESSAGE_DELIMITER));
  170. atmosphere.addInitParameter(
  171. ApplicationConfig.DROP_ACCESS_CONTROL_ALLOW_ORIGIN_HEADER,
  172. "false");
  173. // Disable heartbeat (it does not emit correct events client side)
  174. // https://github.com/Atmosphere/atmosphere-javascript/issues/141
  175. atmosphere.addInitParameter(
  176. ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTORS,
  177. HeartbeatInterceptor.class.getName());
  178. final String bufferSize = String
  179. .valueOf(PushConstants.WEBSOCKET_BUFFER_SIZE);
  180. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE,
  181. bufferSize);
  182. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE,
  183. bufferSize);
  184. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE,
  185. bufferSize);
  186. atmosphere.addInitParameter(
  187. ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL,
  188. "false");
  189. // Disable Atmosphere's message about commercial support
  190. atmosphere.addInitParameter("org.atmosphere.cpr.showSupportMessage",
  191. "false");
  192. try {
  193. atmosphere.init(vaadinServletConfig);
  194. // Ensure the client-side knows how to split the message stream
  195. // into individual messages when using certain transports
  196. AtmosphereInterceptor trackMessageSize = new TrackMessageSizeInterceptor();
  197. trackMessageSize.configure(atmosphere.getAtmosphereConfig());
  198. atmosphere.interceptor(trackMessageSize);
  199. } catch (ServletException e) {
  200. throw new RuntimeException("Atmosphere init failed", e);
  201. }
  202. return atmosphere;
  203. }
  204. @Override
  205. public boolean handleRequest(VaadinSession session, VaadinRequest request,
  206. VaadinResponse response) throws IOException {
  207. if (!ServletPortletHelper.isPushRequest(request)) {
  208. return false;
  209. }
  210. if (request instanceof VaadinServletRequest) {
  211. if (atmosphere == null) {
  212. response.sendError(500,
  213. "Atmosphere initialization failed. No push available.");
  214. return true;
  215. }
  216. try {
  217. atmosphere.doCometSupport(
  218. AtmosphereRequestImpl
  219. .wrap((VaadinServletRequest) request),
  220. AtmosphereResponseImpl
  221. .wrap((VaadinServletResponse) response));
  222. } catch (ServletException e) {
  223. // TODO PUSH decide how to handle
  224. throw new RuntimeException(e);
  225. }
  226. } else {
  227. throw new IllegalArgumentException(
  228. "Portlets not currently supported");
  229. }
  230. return true;
  231. }
  232. public void destroy() {
  233. atmosphere.destroy();
  234. }
  235. /*
  236. * (non-Javadoc)
  237. *
  238. * @see
  239. * com.vaadin.server.SessionExpiredHandler#handleSessionExpired(com.vaadin
  240. * .server.VaadinRequest, com.vaadin.server.VaadinResponse)
  241. */
  242. @Override
  243. public boolean handleSessionExpired(VaadinRequest request,
  244. VaadinResponse response) throws IOException {
  245. // Websockets request must be handled by accepting the websocket
  246. // connection and then sending session expired so we let
  247. // PushRequestHandler handle it
  248. return handleRequest(null, request, response);
  249. }
  250. }