Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

PushHandler.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.AtmosphereRequest;
  23. import org.atmosphere.cpr.AtmosphereResource;
  24. import org.atmosphere.cpr.AtmosphereResource.TRANSPORT;
  25. import org.atmosphere.cpr.AtmosphereResourceEvent;
  26. import org.atmosphere.cpr.AtmosphereResourceImpl;
  27. import com.vaadin.server.ErrorEvent;
  28. import com.vaadin.server.ErrorHandler;
  29. import com.vaadin.server.LegacyCommunicationManager.InvalidUIDLSecurityKeyException;
  30. import com.vaadin.server.ServiceException;
  31. import com.vaadin.server.ServletPortletHelper;
  32. import com.vaadin.server.SessionExpiredException;
  33. import com.vaadin.server.SystemMessages;
  34. import com.vaadin.server.VaadinRequest;
  35. import com.vaadin.server.VaadinService;
  36. import com.vaadin.server.VaadinServletRequest;
  37. import com.vaadin.server.VaadinServletService;
  38. import com.vaadin.server.VaadinSession;
  39. import com.vaadin.shared.ApplicationConstants;
  40. import com.vaadin.shared.communication.PushMode;
  41. import com.vaadin.ui.UI;
  42. import elemental.json.JsonException;
  43. /**
  44. * Handles incoming push connections and messages and dispatches them to the
  45. * correct {@link UI}/ {@link AtmospherePushConnection}
  46. *
  47. * @author Vaadin Ltd
  48. * @since 7.1
  49. */
  50. public class PushHandler {
  51. private int longPollingSuspendTimeout = -1;
  52. /**
  53. * Callback interface used internally to process an event with the
  54. * corresponding UI properly locked.
  55. */
  56. private interface PushEventCallback {
  57. public void run(AtmosphereResource resource, UI ui) throws IOException;
  58. }
  59. /**
  60. * Callback used when we receive a request to establish a push channel for a
  61. * UI. Associate the AtmosphereResource with the UI and leave the connection
  62. * open by calling resource.suspend(). If there is a pending push, send it
  63. * now.
  64. */
  65. private final PushEventCallback establishCallback = new PushEventCallback() {
  66. @Override
  67. public void run(AtmosphereResource resource, UI ui) throws IOException {
  68. getLogger().log(Level.FINER,
  69. "New push connection for resource {0} with transport {1}",
  70. new Object[] { resource.uuid(), resource.transport() });
  71. resource.getResponse().setContentType("text/plain; charset=UTF-8");
  72. VaadinSession session = ui.getSession();
  73. if (resource.transport() == TRANSPORT.STREAMING
  74. || resource.transport() == TRANSPORT.LONG_POLLING) {
  75. // Must ensure that the streaming/long-polling response contains
  76. // "Connection: close", otherwise iOS 6 will wait for the
  77. // response to this request before sending another request to
  78. // the same server (as it will apparently try to reuse the same
  79. // connection).
  80. // Other browsers might also try to re-use the same
  81. // connection for fetching static files after refreshing, which
  82. // will cause a failure in loading vaadinPush.js or
  83. // vaadinBootstrap.js
  84. resource.getResponse().addHeader("Connection", "close");
  85. }
  86. String requestToken = resource.getRequest().getParameter(
  87. ApplicationConstants.CSRF_TOKEN_PARAMETER);
  88. if (!VaadinService.isCsrfTokenValid(session, requestToken)) {
  89. getLogger()
  90. .log(Level.WARNING,
  91. "Invalid CSRF token in new connection received from {0}",
  92. resource.getRequest().getRemoteHost());
  93. // Refresh on client side, create connection just for
  94. // sending a message
  95. sendRefreshAndDisconnect(resource);
  96. return;
  97. }
  98. suspend(resource);
  99. AtmospherePushConnection connection = getConnectionForUI(ui);
  100. assert (connection != null);
  101. connection.connect(resource);
  102. }
  103. };
  104. /**
  105. * Callback used when we receive a UIDL request through Atmosphere. If the
  106. * push channel is bidirectional (websockets), the request was sent via the
  107. * same channel. Otherwise, the client used a separate AJAX request. Handle
  108. * the request and send changed UI state via the push channel (we do not
  109. * respond to the request directly.)
  110. */
  111. private final PushEventCallback receiveCallback = new PushEventCallback() {
  112. @Override
  113. public void run(AtmosphereResource resource, UI ui) throws IOException {
  114. getLogger().log(Level.FINER, "Received message from resource {0}",
  115. resource.uuid());
  116. AtmosphereRequest req = resource.getRequest();
  117. AtmospherePushConnection connection = getConnectionForUI(ui);
  118. assert connection != null : "Got push from the client "
  119. + "even though the connection does not seem to be "
  120. + "valid. This might happen if a HttpSession is "
  121. + "serialized and deserialized while the push "
  122. + "connection is kept open or if the UI has a "
  123. + "connection of unexpected type.";
  124. Reader reader = connection.receiveMessage(req.getReader());
  125. if (reader == null) {
  126. // The whole message was not yet received
  127. return;
  128. }
  129. // Should be set up by caller
  130. VaadinRequest vaadinRequest = VaadinService.getCurrentRequest();
  131. assert vaadinRequest != null;
  132. try {
  133. new ServerRpcHandler().handleRpc(ui, reader, vaadinRequest);
  134. connection.push(false);
  135. } catch (JsonException e) {
  136. getLogger().log(Level.SEVERE, "Error writing JSON to response",
  137. e);
  138. // Refresh on client side
  139. sendRefreshAndDisconnect(resource);
  140. } catch (InvalidUIDLSecurityKeyException e) {
  141. getLogger().log(Level.WARNING,
  142. "Invalid security key received from {0}",
  143. resource.getRequest().getRemoteHost());
  144. // Refresh on client side
  145. sendRefreshAndDisconnect(resource);
  146. }
  147. }
  148. };
  149. private VaadinServletService service;
  150. public PushHandler(VaadinServletService service) {
  151. this.service = service;
  152. }
  153. /**
  154. * Suspends the given resource
  155. *
  156. * @since 7.6
  157. * @param resource
  158. * the resource to suspend
  159. */
  160. protected void suspend(AtmosphereResource resource) {
  161. if (resource.transport() == TRANSPORT.LONG_POLLING) {
  162. resource.suspend(getLongPollingSuspendTimeout());
  163. } else {
  164. resource.suspend(-1);
  165. }
  166. }
  167. /**
  168. * Find the UI for the atmosphere resource, lock it and invoke the callback.
  169. *
  170. * @param resource
  171. * the atmosphere resource for the current request
  172. * @param callback
  173. * the push callback to call when a UI is found and locked
  174. * @param websocket
  175. * true if this is a websocket message (as opposed to a HTTP
  176. * request)
  177. */
  178. private void callWithUi(final AtmosphereResource resource,
  179. final PushEventCallback callback, boolean websocket) {
  180. AtmosphereRequest req = resource.getRequest();
  181. VaadinServletRequest vaadinRequest = new VaadinServletRequest(req,
  182. service);
  183. VaadinSession session = null;
  184. if (websocket) {
  185. // For any HTTP request we have already started the request in the
  186. // servlet
  187. service.requestStart(vaadinRequest, null);
  188. }
  189. try {
  190. try {
  191. session = service.findVaadinSession(vaadinRequest);
  192. assert VaadinSession.getCurrent() == session;
  193. } catch (ServiceException e) {
  194. getLogger().log(Level.SEVERE,
  195. "Could not get session. This should never happen", e);
  196. return;
  197. } catch (SessionExpiredException e) {
  198. SystemMessages msg = service.getSystemMessages(
  199. ServletPortletHelper.findLocale(null, null,
  200. vaadinRequest), vaadinRequest);
  201. sendNotificationAndDisconnect(
  202. resource,
  203. VaadinService.createCriticalNotificationJSON(
  204. msg.getSessionExpiredCaption(),
  205. msg.getSessionExpiredMessage(), null,
  206. msg.getSessionExpiredURL()));
  207. return;
  208. }
  209. UI ui = null;
  210. session.lock();
  211. try {
  212. ui = service.findUI(vaadinRequest);
  213. assert UI.getCurrent() == ui;
  214. if (ui == null) {
  215. sendNotificationAndDisconnect(resource,
  216. UidlRequestHandler.getUINotFoundErrorJSON(service,
  217. vaadinRequest));
  218. } else {
  219. callback.run(resource, ui);
  220. }
  221. } catch (final IOException e) {
  222. callErrorHandler(session, e);
  223. } catch (final Exception e) {
  224. SystemMessages msg = service.getSystemMessages(
  225. ServletPortletHelper.findLocale(null, null,
  226. vaadinRequest), vaadinRequest);
  227. AtmosphereResource errorResource = resource;
  228. if (ui != null && ui.getPushConnection() != null) {
  229. // We MUST use the opened push connection if there is one.
  230. // Otherwise we will write the response to the wrong request
  231. // when using streaming (the client -> server request
  232. // instead of the opened push channel)
  233. errorResource = ((AtmospherePushConnection) ui
  234. .getPushConnection()).getResource();
  235. }
  236. sendNotificationAndDisconnect(
  237. errorResource,
  238. VaadinService.createCriticalNotificationJSON(
  239. msg.getInternalErrorCaption(),
  240. msg.getInternalErrorMessage(), null,
  241. msg.getInternalErrorURL()));
  242. callErrorHandler(session, e);
  243. } finally {
  244. try {
  245. session.unlock();
  246. } catch (Exception e) {
  247. getLogger().log(Level.WARNING,
  248. "Error while unlocking session", e);
  249. // can't call ErrorHandler, we (hopefully) don't have a lock
  250. }
  251. }
  252. } finally {
  253. try {
  254. if (websocket) {
  255. service.requestEnd(vaadinRequest, null, session);
  256. }
  257. } catch (Exception e) {
  258. getLogger().log(Level.WARNING, "Error while ending request", e);
  259. // can't call ErrorHandler, we don't have a lock
  260. }
  261. }
  262. }
  263. /**
  264. * Call the session's {@link ErrorHandler}, if it has one, with the given
  265. * exception wrapped in an {@link ErrorEvent}.
  266. */
  267. private void callErrorHandler(VaadinSession session, Exception e) {
  268. try {
  269. ErrorHandler errorHandler = ErrorEvent.findErrorHandler(session);
  270. if (errorHandler != null) {
  271. errorHandler.error(new ErrorEvent(e));
  272. }
  273. } catch (Exception ex) {
  274. // Let's not allow error handling to cause trouble; log fails
  275. getLogger().log(Level.WARNING, "ErrorHandler call failed", ex);
  276. }
  277. }
  278. private static AtmospherePushConnection getConnectionForUI(UI ui) {
  279. PushConnection pushConnection = ui.getPushConnection();
  280. if (pushConnection instanceof AtmospherePushConnection) {
  281. return (AtmospherePushConnection) pushConnection;
  282. } else {
  283. return null;
  284. }
  285. }
  286. void connectionLost(AtmosphereResourceEvent event) {
  287. // We don't want to use callWithUi here, as it assumes there's a client
  288. // request active and does requestStart and requestEnd among other
  289. // things.
  290. AtmosphereResource resource = event.getResource();
  291. VaadinServletRequest vaadinRequest = new VaadinServletRequest(
  292. resource.getRequest(), service);
  293. VaadinSession session = null;
  294. try {
  295. session = service.findVaadinSession(vaadinRequest);
  296. } catch (ServiceException e) {
  297. getLogger().log(Level.SEVERE,
  298. "Could not get session. This should never happen", e);
  299. return;
  300. } catch (SessionExpiredException e) {
  301. // This happens at least if the server is restarted without
  302. // preserving the session. After restart the client reconnects, gets
  303. // a session expired notification and then closes the connection and
  304. // ends up here
  305. getLogger()
  306. .log(Level.FINER,
  307. "Session expired before push disconnect event was received",
  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.FINE,
  331. "Could not get UI. This should never happen,"
  332. + " except when reloading in Firefox and Chrome -"
  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. pushConnection.connectionLost();
  370. }
  371. } catch (final Exception e) {
  372. callErrorHandler(session, e);
  373. } finally {
  374. try {
  375. session.unlock();
  376. } catch (Exception e) {
  377. getLogger().log(Level.WARNING, "Error while unlocking session",
  378. e);
  379. // can't call ErrorHandler, we (hopefully) don't have a lock
  380. }
  381. }
  382. }
  383. private static UI findUiUsingResource(AtmosphereResource resource,
  384. Collection<UI> uIs) {
  385. for (UI ui : uIs) {
  386. PushConnection pushConnection = ui.getPushConnection();
  387. if (pushConnection instanceof AtmospherePushConnection) {
  388. if (((AtmospherePushConnection) pushConnection).getResource() == resource) {
  389. return ui;
  390. }
  391. }
  392. }
  393. return null;
  394. }
  395. /**
  396. * Sends a refresh message to the given atmosphere resource. Uses an
  397. * AtmosphereResource instead of an AtmospherePushConnection even though it
  398. * might be possible to look up the AtmospherePushConnection from the UI to
  399. * ensure border cases work correctly, especially when there temporarily are
  400. * two push connections which try to use the same UI. Using the
  401. * AtmosphereResource directly guarantees the message goes to the correct
  402. * recipient.
  403. *
  404. * @param resource
  405. * The atmosphere resource to send refresh to
  406. *
  407. */
  408. private static void sendRefreshAndDisconnect(AtmosphereResource resource)
  409. throws IOException {
  410. sendNotificationAndDisconnect(resource,
  411. VaadinService.createCriticalNotificationJSON(null, null, null,
  412. null));
  413. }
  414. /**
  415. * Tries to send a critical notification to the client and close the
  416. * connection. Does nothing if the connection is already closed.
  417. */
  418. private static void sendNotificationAndDisconnect(
  419. AtmosphereResource resource, String notificationJson) {
  420. // TODO Implemented differently from sendRefreshAndDisconnect
  421. try {
  422. if (resource instanceof AtmosphereResourceImpl
  423. && !((AtmosphereResourceImpl) resource).isInScope()) {
  424. // The resource is no longer valid so we should not write
  425. // anything to it
  426. getLogger()
  427. .fine("sendNotificationAndDisconnect called for resource no longer in scope");
  428. return;
  429. }
  430. resource.getResponse().getWriter().write(notificationJson);
  431. resource.resume();
  432. } catch (Exception e) {
  433. getLogger().log(Level.FINEST,
  434. "Failed to send critical notification to client", e);
  435. }
  436. }
  437. private static final Logger getLogger() {
  438. return Logger.getLogger(PushHandler.class.getName());
  439. }
  440. /**
  441. * Called when a new push connection is requested to be opened by the client
  442. *
  443. * @since 7.5.0
  444. * @param resource
  445. * The related atmosphere resources
  446. */
  447. void onConnect(AtmosphereResource resource) {
  448. callWithUi(resource, establishCallback, false);
  449. }
  450. /**
  451. * Called when a message is received through the push connection
  452. *
  453. * @since 7.5.0
  454. * @param resource
  455. * The related atmosphere resources
  456. */
  457. void onMessage(AtmosphereResource resource) {
  458. callWithUi(resource, receiveCallback,
  459. resource.transport() == TRANSPORT.WEBSOCKET);
  460. }
  461. /**
  462. * Sets the timeout used for suspend calls when using long polling.
  463. *
  464. * If you are using a proxy with a defined idle timeout, set the suspend
  465. * timeout to a value smaller than the proxy timeout so that the server is
  466. * aware of a reconnect taking place.
  467. *
  468. * @param suspendTimeout
  469. * the timeout to use for suspended AtmosphereResources
  470. */
  471. public void setLongPollingSuspendTimeout(int longPollingSuspendTimeout) {
  472. this.longPollingSuspendTimeout = longPollingSuspendTimeout;
  473. }
  474. /**
  475. * Gets the timeout used for suspend calls when using long polling.
  476. *
  477. * @return the timeout to use for suspended AtmosphereResources
  478. */
  479. public int getLongPollingSuspendTimeout() {
  480. return longPollingSuspendTimeout;
  481. }
  482. }