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.

PushHandler.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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.io.Reader;
  19. import java.util.Collection;
  20. import java.util.logging.Level;
  21. import java.util.logging.Logger;
  22. import org.atmosphere.cpr.AtmosphereHandler;
  23. import org.atmosphere.cpr.AtmosphereRequest;
  24. import org.atmosphere.cpr.AtmosphereResource;
  25. import org.atmosphere.cpr.AtmosphereResource.TRANSPORT;
  26. import org.atmosphere.cpr.AtmosphereResourceEvent;
  27. import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter;
  28. import org.atmosphere.handler.AbstractReflectorAtmosphereHandler;
  29. import org.json.JSONException;
  30. import com.vaadin.server.ErrorEvent;
  31. import com.vaadin.server.ErrorHandler;
  32. import com.vaadin.server.LegacyCommunicationManager.InvalidUIDLSecurityKeyException;
  33. import com.vaadin.server.ServiceException;
  34. import com.vaadin.server.ServletPortletHelper;
  35. import com.vaadin.server.SessionExpiredException;
  36. import com.vaadin.server.SystemMessages;
  37. import com.vaadin.server.VaadinRequest;
  38. import com.vaadin.server.VaadinService;
  39. import com.vaadin.server.VaadinServletRequest;
  40. import com.vaadin.server.VaadinServletService;
  41. import com.vaadin.server.VaadinSession;
  42. import com.vaadin.shared.ApplicationConstants;
  43. import com.vaadin.shared.communication.PushMode;
  44. import com.vaadin.ui.UI;
  45. /**
  46. * Establishes bidirectional ("push") communication channels
  47. *
  48. * @author Vaadin Ltd
  49. * @since 7.1
  50. */
  51. public class PushHandler extends AtmosphereResourceEventListenerAdapter {
  52. AtmosphereHandler handler = new AbstractReflectorAtmosphereHandler() {
  53. @Override
  54. public void onStateChange(AtmosphereResourceEvent event)
  55. throws IOException {
  56. super.onStateChange(event);
  57. if (event.isCancelled() || event.isResumedOnTimeout()) {
  58. disconnect(event);
  59. }
  60. }
  61. @Override
  62. public void onRequest(AtmosphereResource resource) {
  63. AtmosphereRequest req = resource.getRequest();
  64. if (req.getMethod().equalsIgnoreCase("GET")) {
  65. callWithUi(resource, establishCallback);
  66. } else if (req.getMethod().equalsIgnoreCase("POST")) {
  67. callWithUi(resource, receiveCallback);
  68. }
  69. }
  70. };
  71. /**
  72. * Callback interface used internally to process an event with the
  73. * corresponding UI properly locked.
  74. */
  75. private interface PushEventCallback {
  76. public void run(AtmosphereResource resource, UI ui) throws IOException;
  77. }
  78. /**
  79. * Callback used when we receive a request to establish a push channel for a
  80. * UI. Associate the AtmosphereResource with the UI and leave the connection
  81. * open by calling resource.suspend(). If there is a pending push, send it
  82. * now.
  83. */
  84. private final PushEventCallback establishCallback = new PushEventCallback() {
  85. @Override
  86. public void run(AtmosphereResource resource, UI ui) throws IOException {
  87. getLogger().log(Level.FINER,
  88. "New push connection for resource {0} with transport {1}",
  89. new Object[] { resource.uuid(), resource.transport() });
  90. resource.addEventListener(PushHandler.this);
  91. resource.getResponse().setContentType("text/plain; charset=UTF-8");
  92. VaadinSession session = ui.getSession();
  93. if (resource.transport() == TRANSPORT.STREAMING) {
  94. // Must ensure that the streaming response contains
  95. // "Connection: close", otherwise iOS 6 will wait for the
  96. // response to this request before sending another request to
  97. // the same server (as it will apparently try to reuse the same
  98. // connection)
  99. resource.getResponse().addHeader("Connection", "close");
  100. }
  101. String requestToken = resource.getRequest().getParameter(
  102. ApplicationConstants.CSRF_TOKEN_PARAMETER);
  103. if (!VaadinService.isCsrfTokenValid(session, requestToken)) {
  104. getLogger()
  105. .log(Level.WARNING,
  106. "Invalid CSRF token in new connection received from {0}",
  107. resource.getRequest().getRemoteHost());
  108. // Refresh on client side, create connection just for
  109. // sending a message
  110. sendRefreshAndDisconnect(resource);
  111. return;
  112. }
  113. resource.suspend();
  114. AtmospherePushConnection connection = getConnectionForUI(ui);
  115. assert (connection != null);
  116. connection.connect(resource);
  117. }
  118. };
  119. /**
  120. * Callback used when we receive a UIDL request through Atmosphere. If the
  121. * push channel is bidirectional (websockets), the request was sent via the
  122. * same channel. Otherwise, the client used a separate AJAX request. Handle
  123. * the request and send changed UI state via the push channel (we do not
  124. * respond to the request directly.)
  125. */
  126. private final PushEventCallback receiveCallback = new PushEventCallback() {
  127. @Override
  128. public void run(AtmosphereResource resource, UI ui) throws IOException {
  129. getLogger().log(Level.FINER, "Received message from resource {0}",
  130. resource.uuid());
  131. AtmosphereRequest req = resource.getRequest();
  132. AtmospherePushConnection connection = getConnectionForUI(ui);
  133. assert connection != null : "Got push from the client "
  134. + "even though the connection does not seem to be "
  135. + "valid. This might happen if a HttpSession is "
  136. + "serialized and deserialized while the push "
  137. + "connection is kept open or if the UI has a "
  138. + "connection of unexpected type.";
  139. Reader reader = connection.receiveMessage(req.getReader());
  140. if (reader == null) {
  141. // The whole message was not yet received
  142. return;
  143. }
  144. // Should be set up by caller
  145. VaadinRequest vaadinRequest = VaadinService.getCurrentRequest();
  146. assert vaadinRequest != null;
  147. try {
  148. new ServerRpcHandler().handleRpc(ui, reader, vaadinRequest);
  149. connection.push(false);
  150. } catch (JSONException e) {
  151. getLogger().log(Level.SEVERE, "Error writing JSON to response",
  152. e);
  153. // Refresh on client side
  154. sendRefreshAndDisconnect(resource);
  155. } catch (InvalidUIDLSecurityKeyException e) {
  156. getLogger().log(Level.WARNING,
  157. "Invalid security key received from {0}",
  158. resource.getRequest().getRemoteHost());
  159. // Refresh on client side
  160. sendRefreshAndDisconnect(resource);
  161. }
  162. }
  163. };
  164. private VaadinServletService service;
  165. public PushHandler(VaadinServletService service) {
  166. this.service = service;
  167. }
  168. /**
  169. * Find the UI for the atmosphere resource, lock it and invoke the callback.
  170. *
  171. * @param resource
  172. * the atmosphere resource for the current request
  173. * @param callback
  174. * the push callback to call when a UI is found and locked
  175. */
  176. private void callWithUi(final AtmosphereResource resource,
  177. final PushEventCallback callback) {
  178. AtmosphereRequest req = resource.getRequest();
  179. VaadinServletRequest vaadinRequest = new VaadinServletRequest(req,
  180. service);
  181. VaadinSession session = null;
  182. service.requestStart(vaadinRequest, null);
  183. try {
  184. try {
  185. session = service.findVaadinSession(vaadinRequest);
  186. assert VaadinSession.getCurrent() == session;
  187. } catch (ServiceException e) {
  188. getLogger().log(Level.SEVERE,
  189. "Could not get session. This should never happen", e);
  190. return;
  191. } catch (SessionExpiredException e) {
  192. SystemMessages msg = service.getSystemMessages(
  193. ServletPortletHelper.findLocale(null, null,
  194. vaadinRequest), vaadinRequest);
  195. sendNotificationAndDisconnect(
  196. resource,
  197. VaadinService.createCriticalNotificationJSON(
  198. msg.getSessionExpiredCaption(),
  199. msg.getSessionExpiredMessage(), null,
  200. msg.getSessionExpiredURL()));
  201. return;
  202. }
  203. UI ui = null;
  204. session.lock();
  205. try {
  206. ui = service.findUI(vaadinRequest);
  207. assert UI.getCurrent() == ui;
  208. if (ui == null) {
  209. sendNotificationAndDisconnect(resource,
  210. UidlRequestHandler.getUINotFoundErrorJSON(service,
  211. vaadinRequest));
  212. } else {
  213. callback.run(resource, ui);
  214. }
  215. } catch (final IOException e) {
  216. callErrorHandler(session, e);
  217. } catch (final Exception e) {
  218. SystemMessages msg = service.getSystemMessages(
  219. ServletPortletHelper.findLocale(null, null,
  220. vaadinRequest), vaadinRequest);
  221. AtmosphereResource errorResource = resource;
  222. if (ui != null && ui.getPushConnection() != null) {
  223. // We MUST use the opened push connection if there is one.
  224. // Otherwise we will write the response to the wrong request
  225. // when using streaming (the client -> server request
  226. // instead of the opened push channel)
  227. errorResource = ((AtmospherePushConnection) ui
  228. .getPushConnection()).getResource();
  229. }
  230. sendNotificationAndDisconnect(
  231. errorResource,
  232. VaadinService.createCriticalNotificationJSON(
  233. msg.getInternalErrorCaption(),
  234. msg.getInternalErrorMessage(), null,
  235. msg.getInternalErrorURL()));
  236. callErrorHandler(session, e);
  237. } finally {
  238. try {
  239. session.unlock();
  240. } catch (Exception e) {
  241. getLogger().log(Level.WARNING,
  242. "Error while unlocking session", e);
  243. // can't call ErrorHandler, we (hopefully) don't have a lock
  244. }
  245. }
  246. } finally {
  247. try {
  248. service.requestEnd(vaadinRequest, null, session);
  249. } catch (Exception e) {
  250. getLogger().log(Level.WARNING, "Error while ending request", e);
  251. // can't call ErrorHandler, we don't have a lock
  252. }
  253. }
  254. }
  255. /**
  256. * Call the session's {@link ErrorHandler}, if it has one, with the given
  257. * exception wrapped in an {@link ErrorEvent}.
  258. */
  259. private void callErrorHandler(VaadinSession session, Exception e) {
  260. try {
  261. ErrorHandler errorHandler = ErrorEvent.findErrorHandler(session);
  262. if (errorHandler != null) {
  263. errorHandler.error(new ErrorEvent(e));
  264. }
  265. } catch (Exception ex) {
  266. // Let's not allow error handling to cause trouble; log fails
  267. getLogger().log(Level.WARNING, "ErrorHandler call failed", ex);
  268. }
  269. }
  270. private static AtmospherePushConnection getConnectionForUI(UI ui) {
  271. PushConnection pushConnection = ui.getPushConnection();
  272. if (pushConnection instanceof AtmospherePushConnection) {
  273. return (AtmospherePushConnection) pushConnection;
  274. } else {
  275. return null;
  276. }
  277. }
  278. @Override
  279. public void onDisconnect(AtmosphereResourceEvent event) {
  280. // Log event on trace level
  281. super.onDisconnect(event);
  282. disconnect(event);
  283. }
  284. @Override
  285. public void onThrowable(AtmosphereResourceEvent event) {
  286. getLogger().log(Level.SEVERE, "Exception in push connection",
  287. event.throwable());
  288. disconnect(event);
  289. }
  290. private void disconnect(AtmosphereResourceEvent event) {
  291. // We don't want to use callWithUi here, as it assumes there's a client
  292. // request active and does requestStart and requestEnd among other
  293. // things.
  294. AtmosphereResource resource = event.getResource();
  295. VaadinServletRequest vaadinRequest = new VaadinServletRequest(
  296. resource.getRequest(), service);
  297. VaadinSession session = null;
  298. try {
  299. session = service.findVaadinSession(vaadinRequest);
  300. } catch (ServiceException e) {
  301. getLogger().log(Level.SEVERE,
  302. "Could not get session. This should never happen", e);
  303. return;
  304. } catch (SessionExpiredException e) {
  305. getLogger()
  306. .log(Level.SEVERE,
  307. "Session expired before push was disconnected. This should never happen",
  308. e);
  309. return;
  310. }
  311. UI ui = null;
  312. session.lock();
  313. try {
  314. VaadinSession.setCurrent(session);
  315. // Sets UI.currentInstance
  316. ui = service.findUI(vaadinRequest);
  317. if (ui == null) {
  318. /*
  319. * UI not found, could be because FF has asynchronously closed
  320. * the websocket connection and Atmosphere has already done
  321. * cleanup of the request attributes.
  322. *
  323. * In that case, we still have a chance of finding the right UI
  324. * by iterating through the UIs in the session looking for one
  325. * using the same AtmosphereResource.
  326. */
  327. ui = findUiUsingResource(resource, session.getUIs());
  328. if (ui == null) {
  329. getLogger()
  330. .log(Level.SEVERE,
  331. "Could not get UI. This should never happen,"
  332. + " except when reloading in Firefox -"
  333. + " see http://dev.vaadin.com/ticket/14251.");
  334. return;
  335. } else {
  336. getLogger()
  337. .log(Level.INFO,
  338. "No UI was found based on data in the request,"
  339. + " but a slower lookup based on the AtmosphereResource succeeded."
  340. + " See http://dev.vaadin.com/ticket/14251 for more details.");
  341. }
  342. }
  343. PushMode pushMode = ui.getPushConfiguration().getPushMode();
  344. AtmospherePushConnection pushConnection = getConnectionForUI(ui);
  345. String id = resource.uuid();
  346. if (pushConnection == null) {
  347. getLogger()
  348. .log(Level.WARNING,
  349. "Could not find push connection to close: {0} with transport {1}",
  350. new Object[] { id, resource.transport() });
  351. } else {
  352. if (!pushMode.isEnabled()) {
  353. /*
  354. * The client is expected to close the connection after push
  355. * mode has been set to disabled.
  356. */
  357. getLogger().log(Level.FINER,
  358. "Connection closed for resource {0}", id);
  359. } else {
  360. /*
  361. * Unexpected cancel, e.g. if the user closes the browser
  362. * tab.
  363. */
  364. getLogger()
  365. .log(Level.FINER,
  366. "Connection unexpectedly closed for resource {0} with transport {1}",
  367. new Object[] { id, resource.transport() });
  368. }
  369. if (pushConnection.isConnected()) {
  370. // disconnect() assumes the push connection is connected but
  371. // this method can currently be called more than once during
  372. // disconnect, depending on the situation
  373. pushConnection.disconnect();
  374. }
  375. }
  376. } catch (final Exception e) {
  377. callErrorHandler(session, e);
  378. } finally {
  379. try {
  380. session.unlock();
  381. } catch (Exception e) {
  382. getLogger().log(Level.WARNING, "Error while unlocking session",
  383. e);
  384. // can't call ErrorHandler, we (hopefully) don't have a lock
  385. }
  386. }
  387. }
  388. private static UI findUiUsingResource(AtmosphereResource resource,
  389. Collection<UI> uIs) {
  390. for (UI ui : uIs) {
  391. PushConnection pushConnection = ui.getPushConnection();
  392. if (pushConnection instanceof AtmospherePushConnection) {
  393. if (((AtmospherePushConnection) pushConnection).getResource() == resource) {
  394. return ui;
  395. }
  396. }
  397. }
  398. return null;
  399. }
  400. /**
  401. * Sends a refresh message to the given atmosphere resource. Uses an
  402. * AtmosphereResource instead of an AtmospherePushConnection even though it
  403. * might be possible to look up the AtmospherePushConnection from the UI to
  404. * ensure border cases work correctly, especially when there temporarily are
  405. * two push connections which try to use the same UI. Using the
  406. * AtmosphereResource directly guarantees the message goes to the correct
  407. * recipient.
  408. *
  409. * @param resource
  410. * The atmosphere resource to send refresh to
  411. *
  412. */
  413. private static void sendRefreshAndDisconnect(AtmosphereResource resource)
  414. throws IOException {
  415. AtmospherePushConnection connection = new AtmospherePushConnection(null);
  416. connection.connect(resource);
  417. try {
  418. connection.sendMessage(VaadinService
  419. .createCriticalNotificationJSON(null, null, null, null));
  420. } finally {
  421. connection.disconnect();
  422. }
  423. }
  424. /**
  425. * Tries to send a critical notification to the client and close the
  426. * connection. Does nothing if the connection is already closed.
  427. */
  428. private static void sendNotificationAndDisconnect(
  429. AtmosphereResource resource, String notificationJson) {
  430. // TODO Implemented differently from sendRefreshAndDisconnect
  431. try {
  432. resource.getResponse().getWriter().write(notificationJson);
  433. resource.resume();
  434. } catch (Exception e) {
  435. getLogger().log(Level.FINEST,
  436. "Failed to send critical notification to client", e);
  437. }
  438. }
  439. private static final Logger getLogger() {
  440. return Logger.getLogger(PushHandler.class.getName());
  441. }
  442. }