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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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.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.JsonConstants;
  41. import com.vaadin.shared.communication.PushMode;
  42. import com.vaadin.ui.UI;
  43. import elemental.json.JsonException;
  44. /**
  45. * Handles incoming push connections and messages and dispatches them to the
  46. * correct {@link UI}/ {@link AtmospherePushConnection}.
  47. *
  48. * @author Vaadin Ltd
  49. * @since 7.1
  50. */
  51. public class PushHandler {
  52. private int longPollingSuspendTimeout = -1;
  53. private final ServerRpcHandler rpcHandler = createRpcHandler();
  54. /**
  55. * Callback interface used internally to process an event with the
  56. * corresponding UI properly locked.
  57. */
  58. private interface PushEventCallback {
  59. public void run(AtmosphereResource resource, UI ui) throws IOException;
  60. }
  61. /**
  62. * Callback used when we receive a request to establish a push channel for a
  63. * UI. Associate the AtmosphereResource with the UI and leave the connection
  64. * open by calling resource.suspend(). If there is a pending push, send it
  65. * now.
  66. */
  67. private final PushEventCallback establishCallback = (
  68. AtmosphereResource resource, UI ui) -> {
  69. getLogger().log(Level.FINER,
  70. "New push connection for resource {0} with transport {1}",
  71. new Object[] { resource.uuid(), resource.transport() });
  72. resource.getResponse().setContentType("text/plain; charset=UTF-8");
  73. VaadinSession session = ui.getSession();
  74. if (resource.transport() == TRANSPORT.STREAMING) {
  75. // Must ensure that the streaming 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. resource.getResponse().addHeader("Connection", "close");
  81. }
  82. String requestToken = resource.getRequest()
  83. .getParameter(ApplicationConstants.PUSH_ID_PARAMETER);
  84. if (!isPushIdValid(session, requestToken)) {
  85. getLogger().log(Level.WARNING,
  86. "Invalid identifier in new connection received from {0}",
  87. resource.getRequest().getRemoteHost());
  88. // Refresh on client side, create connection just for
  89. // sending a message
  90. sendRefreshAndDisconnect(resource);
  91. return;
  92. }
  93. suspend(resource);
  94. AtmospherePushConnection connection = getConnectionForUI(ui);
  95. assert (connection != null);
  96. connection.connect(resource);
  97. };
  98. /**
  99. * Callback used when we receive a UIDL request through Atmosphere. If the
  100. * push channel is bidirectional (websockets), the request was sent via the
  101. * same channel. Otherwise, the client used a separate AJAX request. Handle
  102. * the request and send changed UI state via the push channel (we do not
  103. * respond to the request directly.)
  104. */
  105. private final PushEventCallback receiveCallback = (
  106. AtmosphereResource resource, UI ui) -> {
  107. getLogger().log(Level.FINER, "Received message from resource {0}",
  108. resource.uuid());
  109. AtmosphereRequest req = resource.getRequest();
  110. AtmospherePushConnection connection = getConnectionForUI(ui);
  111. assert connection != null : "Got push from the client "
  112. + "even though the connection does not seem to be "
  113. + "valid. This might happen if a HttpSession is "
  114. + "serialized and deserialized while the push "
  115. + "connection is kept open or if the UI has a "
  116. + "connection of unexpected type.";
  117. Reader reader = connection.receiveMessage(req.getReader());
  118. if (reader == null) {
  119. // The whole message was not yet received
  120. return;
  121. }
  122. // Should be set up by caller
  123. VaadinRequest vaadinRequest = VaadinService.getCurrentRequest();
  124. assert vaadinRequest != null;
  125. try {
  126. rpcHandler.handleRpc(ui, reader, vaadinRequest);
  127. connection.push(false);
  128. } catch (JsonException e) {
  129. getLogger().log(Level.SEVERE, "Error writing JSON to response", e);
  130. // Refresh on client side
  131. sendRefreshAndDisconnect(resource);
  132. } catch (InvalidUIDLSecurityKeyException e) {
  133. getLogger().log(Level.WARNING,
  134. "Invalid security key received from {0}",
  135. resource.getRequest().getRemoteHost());
  136. // Refresh on client side
  137. sendRefreshAndDisconnect(resource);
  138. }
  139. };
  140. private final VaadinServletService service;
  141. public PushHandler(VaadinServletService service) {
  142. this.service = service;
  143. }
  144. /**
  145. * Creates the ServerRpcHandler to use.
  146. *
  147. * @return the ServerRpcHandler to use
  148. * @since 8.5
  149. */
  150. protected ServerRpcHandler createRpcHandler() {
  151. return new ServerRpcHandler();
  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. */
  175. private void callWithUi(final AtmosphereResource resource,
  176. final PushEventCallback callback) {
  177. AtmosphereRequest req = resource.getRequest();
  178. VaadinServletRequest vaadinRequest = new VaadinServletRequest(req,
  179. service);
  180. VaadinSession session = null;
  181. boolean isWebsocket = resource.transport() == TRANSPORT.WEBSOCKET;
  182. if (isWebsocket) {
  183. // For any HTTP request we have already started the request in the
  184. // servlet
  185. service.requestStart(vaadinRequest, null);
  186. }
  187. try {
  188. try {
  189. session = service.findVaadinSession(vaadinRequest);
  190. assert VaadinSession.getCurrent() == session;
  191. } catch (ServiceException e) {
  192. getLogger().log(Level.SEVERE,
  193. "Could not get session. This should never happen", e);
  194. return;
  195. } catch (SessionExpiredException e) {
  196. SystemMessages msg = service
  197. .getSystemMessages(ServletPortletHelper.findLocale(null,
  198. null, vaadinRequest), vaadinRequest);
  199. sendNotificationAndDisconnect(resource,
  200. VaadinService.createCriticalNotificationJSON(
  201. msg.getSessionExpiredCaption(),
  202. msg.getSessionExpiredMessage(), null,
  203. msg.getSessionExpiredURL()));
  204. return;
  205. }
  206. UI ui = null;
  207. session.lock();
  208. try {
  209. ui = service.findUI(vaadinRequest);
  210. assert UI.getCurrent() == ui;
  211. if (ui == null) {
  212. sendNotificationAndDisconnect(resource, UidlRequestHandler
  213. .getUINotFoundErrorJSON(service, vaadinRequest));
  214. } else {
  215. callback.run(resource, ui);
  216. }
  217. } catch (final IOException e) {
  218. callErrorHandler(session, e);
  219. } catch (final Exception e) {
  220. SystemMessages msg = service
  221. .getSystemMessages(ServletPortletHelper.findLocale(null,
  222. null, vaadinRequest), vaadinRequest);
  223. AtmosphereResource errorResource = resource;
  224. if (ui != null && ui.getPushConnection() != null) {
  225. // We MUST use the opened push connection if there is one.
  226. // Otherwise we will write the response to the wrong request
  227. // when using streaming (the client -> server request
  228. // instead of the opened push channel)
  229. errorResource = ((AtmospherePushConnection) ui
  230. .getPushConnection()).getResource();
  231. }
  232. sendNotificationAndDisconnect(errorResource,
  233. VaadinService.createCriticalNotificationJSON(
  234. msg.getInternalErrorCaption(),
  235. msg.getInternalErrorMessage(), null,
  236. msg.getInternalErrorURL()));
  237. callErrorHandler(session, e);
  238. } finally {
  239. try {
  240. session.unlock();
  241. } catch (Exception e) {
  242. getLogger().log(Level.WARNING,
  243. "Error while unlocking session", e);
  244. // can't call ErrorHandler, we (hopefully) don't have a lock
  245. }
  246. }
  247. } finally {
  248. try {
  249. if (isWebsocket) {
  250. service.requestEnd(vaadinRequest, null, session);
  251. }
  252. } catch (Exception e) {
  253. getLogger().log(Level.WARNING, "Error while ending request", e);
  254. // can't call ErrorHandler, we don't have a lock
  255. }
  256. }
  257. }
  258. /**
  259. * Call the session's {@link ErrorHandler}, if it has one, with the given
  260. * exception wrapped in an {@link ErrorEvent}.
  261. */
  262. private void callErrorHandler(VaadinSession session, Exception e) {
  263. try {
  264. ErrorHandler errorHandler = ErrorEvent.findErrorHandler(session);
  265. if (errorHandler != null) {
  266. errorHandler.error(new ErrorEvent(e));
  267. }
  268. } catch (Exception ex) {
  269. // Let's not allow error handling to cause trouble; log fails
  270. getLogger().log(Level.WARNING, "ErrorHandler call failed", ex);
  271. }
  272. }
  273. private static AtmospherePushConnection getConnectionForUI(UI ui) {
  274. PushConnection pushConnection = ui.getPushConnection();
  275. if (pushConnection instanceof AtmospherePushConnection) {
  276. return (AtmospherePushConnection) pushConnection;
  277. } else {
  278. return null;
  279. }
  280. }
  281. void connectionLost(AtmosphereResourceEvent event) {
  282. // We don't want to use callWithUi here, as it assumes there's a client
  283. // request active and does requestStart and requestEnd among other
  284. // things.
  285. if (event == null) {
  286. getLogger().log(Level.SEVERE,
  287. "Could not get event. This should never happen.");
  288. return;
  289. }
  290. AtmosphereResource resource = event.getResource();
  291. if (resource == null) {
  292. getLogger().log(Level.SEVERE,
  293. "Could not get resource. This should never happen.");
  294. return;
  295. }
  296. VaadinServletRequest vaadinRequest = new VaadinServletRequest(
  297. resource.getRequest(), service);
  298. VaadinSession session = null;
  299. try {
  300. session = service.findVaadinSession(vaadinRequest);
  301. } catch (ServiceException e) {
  302. getLogger().log(Level.SEVERE,
  303. "Could not get session. This should never happen", e);
  304. return;
  305. } catch (SessionExpiredException e) {
  306. // This happens at least if the server is restarted without
  307. // preserving the session. After restart the client reconnects, gets
  308. // a session expired notification and then closes the connection and
  309. // ends up here
  310. getLogger().log(Level.FINER,
  311. "Session expired before push disconnect event was received",
  312. e);
  313. return;
  314. }
  315. UI ui = null;
  316. session.lock();
  317. try {
  318. VaadinSession.setCurrent(session);
  319. // Sets UI.currentInstance
  320. ui = service.findUI(vaadinRequest);
  321. if (ui == null) {
  322. /*
  323. * UI not found, could be because FF has asynchronously closed
  324. * the websocket connection and Atmosphere has already done
  325. * cleanup of the request attributes. In that case, we still
  326. * have a chance of finding the right UI by iterating through
  327. * the UIs in the session looking for one using the same
  328. * AtmosphereResource.
  329. */
  330. ui = findUiUsingResource(resource, session.getUIs());
  331. if (ui == null) {
  332. getLogger().log(Level.FINE,
  333. "Could not get UI. This should never happen,"
  334. + " except when reloading in Firefox and Chrome -"
  335. + " see http://dev.vaadin.com/ticket/14251.");
  336. return;
  337. } else {
  338. getLogger().log(Level.INFO,
  339. "No UI was found based on data in the request,"
  340. + " but a slower lookup based on the AtmosphereResource succeeded."
  341. + " See http://dev.vaadin.com/ticket/14251 for more details.");
  342. }
  343. }
  344. PushMode pushMode = ui.getPushConfiguration().getPushMode();
  345. AtmospherePushConnection pushConnection = getConnectionForUI(ui);
  346. String id = resource.uuid();
  347. if (pushConnection == null) {
  348. getLogger().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().log(Level.FINER,
  365. "Connection unexpectedly closed for resource {0} with transport {1}",
  366. new Object[] { id, resource.transport() });
  367. }
  368. pushConnection.connectionLost();
  369. }
  370. } catch (final Exception e) {
  371. callErrorHandler(session, e);
  372. } finally {
  373. try {
  374. session.unlock();
  375. } catch (Exception e) {
  376. getLogger().log(Level.WARNING, "Error while unlocking session",
  377. e);
  378. // can't call ErrorHandler, we (hopefully) don't have a lock
  379. }
  380. }
  381. }
  382. private static UI findUiUsingResource(AtmosphereResource resource,
  383. Collection<UI> uIs) {
  384. for (UI ui : uIs) {
  385. PushConnection pushConnection = ui.getPushConnection();
  386. if (pushConnection instanceof AtmospherePushConnection) {
  387. if (((AtmospherePushConnection) pushConnection)
  388. .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, VaadinService
  411. .createCriticalNotificationJSON(null, null, null, null));
  412. }
  413. /**
  414. * Tries to send a critical notification to the client and close the
  415. * connection. Does nothing if the connection is already closed.
  416. */
  417. private static void sendNotificationAndDisconnect(
  418. AtmosphereResource resource, String notificationJson) {
  419. // TODO Implemented differently from sendRefreshAndDisconnect
  420. try {
  421. if (resource instanceof AtmosphereResourceImpl
  422. && !((AtmosphereResourceImpl) resource).isInScope()) {
  423. // The resource is no longer valid so we should not write
  424. // anything to it
  425. getLogger().fine(
  426. "sendNotificationAndDisconnect called for resource no longer in scope");
  427. return;
  428. }
  429. resource.getResponse()
  430. .setContentType(JsonConstants.JSON_CONTENT_TYPE);
  431. resource.getResponse().getWriter().write(notificationJson);
  432. resource.resume();
  433. } catch (Exception e) {
  434. getLogger().log(Level.FINEST,
  435. "Failed to send critical notification to client", e);
  436. }
  437. }
  438. private static final Logger getLogger() {
  439. return Logger.getLogger(PushHandler.class.getName());
  440. }
  441. /**
  442. * Checks whether a given push id matches the session's push id.
  443. *
  444. * @param session
  445. * the vaadin session for which the check should be done
  446. * @param requestPushId
  447. * the push id provided in the request
  448. * @return {@code true} if the id is valid, {@code false} otherwise
  449. */
  450. private static boolean isPushIdValid(VaadinSession session,
  451. String requestPushId) {
  452. String sessionPushId = session.getPushId();
  453. if (requestPushId == null || !requestPushId.equals(sessionPushId)) {
  454. return false;
  455. }
  456. return true;
  457. }
  458. /**
  459. * Called when a new push connection is requested to be opened by the client
  460. *
  461. * @since 7.5.0
  462. * @param resource
  463. * The related atmosphere resources
  464. */
  465. void onConnect(AtmosphereResource resource) {
  466. callWithUi(resource, establishCallback);
  467. }
  468. /**
  469. * Called when a message is received through the push connection
  470. *
  471. * @since 7.5.0
  472. * @param resource
  473. * The related atmosphere resources
  474. */
  475. void onMessage(AtmosphereResource resource) {
  476. callWithUi(resource, receiveCallback);
  477. }
  478. /**
  479. * Sets the timeout used for suspend calls when using long polling.
  480. *
  481. * If you are using a proxy with a defined idle timeout, set the suspend
  482. * timeout to a value smaller than the proxy timeout so that the server is
  483. * aware of a reconnect taking place.
  484. *
  485. * @since 7.6
  486. * @param longPollingSuspendTimeout
  487. * the timeout to use for suspended AtmosphereResources
  488. */
  489. public void setLongPollingSuspendTimeout(int longPollingSuspendTimeout) {
  490. this.longPollingSuspendTimeout = longPollingSuspendTimeout;
  491. }
  492. /**
  493. * Gets the timeout used for suspend calls when using long polling.
  494. *
  495. * @since 7.6
  496. * @return the timeout to use for suspended AtmosphereResources
  497. */
  498. public int getLongPollingSuspendTimeout() {
  499. return longPollingSuspendTimeout;
  500. }
  501. }