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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright 2000-2018 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.ServiceException;
  34. import com.vaadin.server.ServletPortletHelper;
  35. import com.vaadin.server.SessionExpiredHandler;
  36. import com.vaadin.server.VaadinRequest;
  37. import com.vaadin.server.VaadinResponse;
  38. import com.vaadin.server.VaadinServletRequest;
  39. import com.vaadin.server.VaadinServletResponse;
  40. import com.vaadin.server.VaadinServletService;
  41. import com.vaadin.server.VaadinSession;
  42. import com.vaadin.shared.communication.PushConstants;
  43. /**
  44. * Handles requests to open a push (bidirectional) communication channel between
  45. * the client and the server. After the initial request, communication through
  46. * the push channel is managed by {@link PushAtmosphereHandler} and
  47. * {@link PushHandler}
  48. *
  49. * @author Vaadin Ltd
  50. * @since 7.1
  51. */
  52. public class PushRequestHandler implements SessionExpiredHandler {
  53. private AtmosphereFramework atmosphere;
  54. private PushHandler pushHandler;
  55. public PushRequestHandler(VaadinServletService service)
  56. throws ServiceException {
  57. service.addServiceDestroyListener(event -> destroy());
  58. final ServletConfig vaadinServletConfig = service.getServlet()
  59. .getServletConfig();
  60. pushHandler = createPushHandler(service);
  61. atmosphere = getPreInitializedAtmosphere(vaadinServletConfig);
  62. if (atmosphere == null) {
  63. // Not initialized by JSR356WebsocketInitializer
  64. getLogger().fine("Initializing Atmosphere for servlet "
  65. + vaadinServletConfig.getServletName());
  66. try {
  67. atmosphere = initAtmosphere(vaadinServletConfig);
  68. } catch (Exception e) {
  69. getLogger().log(Level.WARNING,
  70. "Failed to initialize Atmosphere for "
  71. + service.getServlet().getServletName()
  72. + ". Push will not work.",
  73. e);
  74. return;
  75. }
  76. } else {
  77. getLogger().fine("Using pre-initialized Atmosphere for servlet "
  78. + vaadinServletConfig.getServletName());
  79. }
  80. pushHandler.setLongPollingSuspendTimeout(
  81. atmosphere.getAtmosphereConfig().getInitParameter(
  82. com.vaadin.server.Constants.SERVLET_PARAMETER_PUSH_SUSPEND_TIMEOUT_LONGPOLLING,
  83. -1));
  84. for (AtmosphereHandlerWrapper handlerWrapper : atmosphere
  85. .getAtmosphereHandlers().values()) {
  86. AtmosphereHandler handler = handlerWrapper.atmosphereHandler;
  87. if (handler instanceof PushAtmosphereHandler) {
  88. // Map the (possibly pre-initialized) handler to the actual push
  89. // handler
  90. ((PushAtmosphereHandler) handler).setPushHandler(pushHandler);
  91. }
  92. }
  93. }
  94. /**
  95. * Creates a push handler for this request handler.
  96. * <p>
  97. * Create your own request handler and override this method if you want to
  98. * customize the {@link PushHandler}, e.g. to dynamically decide the suspend
  99. * timeout.
  100. *
  101. * @since 7.6
  102. * @param service
  103. * the vaadin service
  104. * @return the push handler to use for this service
  105. */
  106. protected PushHandler createPushHandler(VaadinServletService service) {
  107. return new PushHandler(service);
  108. }
  109. private static final Logger getLogger() {
  110. return Logger.getLogger(PushRequestHandler.class.getName());
  111. }
  112. /**
  113. * Returns an AtmosphereFramework instance which was initialized in the
  114. * servlet context init phase by {@link JSR356WebsocketInitializer}, if such
  115. * exists
  116. */
  117. private AtmosphereFramework getPreInitializedAtmosphere(
  118. ServletConfig vaadinServletConfig) {
  119. String attributeName = JSR356WebsocketInitializer
  120. .getAttributeName(vaadinServletConfig.getServletName());
  121. Object framework = vaadinServletConfig.getServletContext()
  122. .getAttribute(attributeName);
  123. if (framework instanceof AtmosphereFramework) {
  124. return (AtmosphereFramework) framework;
  125. }
  126. return null;
  127. }
  128. /**
  129. * Initializes Atmosphere for the given ServletConfiguration
  130. *
  131. * @since 7.5.0
  132. * @param vaadinServletConfig
  133. * The servlet configuration for the servlet which should have
  134. * Atmosphere support
  135. */
  136. static AtmosphereFramework initAtmosphere(
  137. final ServletConfig vaadinServletConfig) {
  138. AtmosphereFramework atmosphere = new AtmosphereFramework(false, false) {
  139. @Override
  140. protected void analytics() {
  141. // Overridden to disable version number check
  142. }
  143. @Override
  144. public AtmosphereFramework addInitParameter(String name,
  145. String value) {
  146. if (vaadinServletConfig.getInitParameter(name) == null) {
  147. super.addInitParameter(name, value);
  148. }
  149. return this;
  150. }
  151. };
  152. atmosphere.addAtmosphereHandler("/*", new PushAtmosphereHandler());
  153. atmosphere.addInitParameter(ApplicationConfig.BROADCASTER_CACHE,
  154. UUIDBroadcasterCache.class.getName());
  155. atmosphere.addInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR,
  156. VoidAnnotationProcessor.class.getName());
  157. atmosphere.addInitParameter(ApplicationConfig.PROPERTY_SESSION_SUPPORT,
  158. "true");
  159. atmosphere.addInitParameter(ApplicationConfig.MESSAGE_DELIMITER,
  160. String.valueOf(PushConstants.MESSAGE_DELIMITER));
  161. atmosphere.addInitParameter(
  162. ApplicationConfig.DROP_ACCESS_CONTROL_ALLOW_ORIGIN_HEADER,
  163. "false");
  164. final String bufferSize = String
  165. .valueOf(PushConstants.WEBSOCKET_BUFFER_SIZE);
  166. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE,
  167. bufferSize);
  168. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE,
  169. bufferSize);
  170. atmosphere.addInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE,
  171. bufferSize);
  172. atmosphere.addInitParameter(
  173. ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL,
  174. "false");
  175. // This prevents Atmosphere from recreating a broadcaster after it has
  176. // already been destroyed when the servlet is being undeployed
  177. // (see #20026)
  178. atmosphere.addInitParameter(ApplicationConfig.RECOVER_DEAD_BROADCASTER,
  179. "false");
  180. // Disable Atmosphere's message about commercial support
  181. atmosphere.addInitParameter("org.atmosphere.cpr.showSupportMessage",
  182. "false");
  183. try {
  184. atmosphere.init(vaadinServletConfig);
  185. // Ensure the client-side knows how to split the message stream
  186. // into individual messages when using certain transports
  187. AtmosphereInterceptor trackMessageSize = new TrackMessageSizeInterceptor();
  188. trackMessageSize.configure(atmosphere.getAtmosphereConfig());
  189. atmosphere.interceptor(trackMessageSize);
  190. } catch (ServletException e) {
  191. throw new RuntimeException("Atmosphere init failed", e);
  192. }
  193. return atmosphere;
  194. }
  195. @Override
  196. public boolean handleRequest(VaadinSession session, VaadinRequest request,
  197. VaadinResponse response) throws IOException {
  198. if (!ServletPortletHelper.isPushRequest(request)) {
  199. return false;
  200. }
  201. if (request instanceof VaadinServletRequest) {
  202. if (atmosphere == null) {
  203. response.sendError(500,
  204. "Atmosphere initialization failed. No push available.");
  205. return true;
  206. }
  207. try {
  208. atmosphere.doCometSupport(
  209. AtmosphereRequestImpl
  210. .wrap((VaadinServletRequest) request),
  211. AtmosphereResponseImpl
  212. .wrap((VaadinServletResponse) response));
  213. } catch (ServletException e) {
  214. // TODO PUSH decide how to handle
  215. throw new RuntimeException(e);
  216. }
  217. } else {
  218. throw new IllegalArgumentException(
  219. "Portlets not currently supported");
  220. }
  221. return true;
  222. }
  223. public void destroy() {
  224. atmosphere.destroy();
  225. }
  226. /*
  227. * (non-Javadoc)
  228. *
  229. * @see
  230. * com.vaadin.server.SessionExpiredHandler#handleSessionExpired(com.vaadin
  231. * .server.VaadinRequest, com.vaadin.server.VaadinResponse)
  232. */
  233. @Override
  234. public boolean handleSessionExpired(VaadinRequest request,
  235. VaadinResponse response) throws IOException {
  236. // Websockets request must be handled by accepting the websocket
  237. // connection and then sending session expired so we let
  238. // PushRequestHandler handle it
  239. return handleRequest(null, request, response);
  240. }
  241. }