選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

DefaultConnectionStateHandler.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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.client.communication;
  17. import java.util.logging.Logger;
  18. import com.google.gwt.core.client.JavaScriptObject;
  19. import com.google.gwt.core.shared.GWT;
  20. import com.google.gwt.http.client.Request;
  21. import com.google.gwt.http.client.Response;
  22. import com.google.gwt.regexp.shared.MatchResult;
  23. import com.google.gwt.regexp.shared.RegExp;
  24. import com.google.gwt.user.client.Timer;
  25. import com.vaadin.client.ApplicationConnection;
  26. import com.vaadin.client.ApplicationConnection.ApplicationStoppedEvent;
  27. import com.vaadin.client.ApplicationConnection.ApplicationStoppedHandler;
  28. import com.vaadin.client.WidgetUtil;
  29. import com.vaadin.client.communication.AtmospherePushConnection.AtmosphereResponse;
  30. import com.vaadin.shared.ui.ui.UIState.ReconnectDialogConfigurationState;
  31. import elemental.json.JsonObject;
  32. /**
  33. * Default implementation of the connection state handler.
  34. * <p>
  35. * Handles temporary errors by showing a reconnect dialog to the user while
  36. * trying to re-establish the connection to the server and re-send the pending
  37. * message.
  38. * <p>
  39. * Handles permanent errors by showing a critical system notification to the
  40. * user
  41. *
  42. * @since 7.6
  43. * @author Vaadin Ltd
  44. */
  45. public class DefaultConnectionStateHandler implements ConnectionStateHandler {
  46. private ApplicationConnection connection;
  47. private ReconnectDialog reconnectDialog = GWT.create(ReconnectDialog.class);
  48. private int reconnectAttempt = 0;
  49. private Type reconnectionCause = null;
  50. private Timer scheduledReconnect;
  51. private Timer dialogShowTimer = new Timer() {
  52. @Override
  53. public void run() {
  54. showDialog();
  55. }
  56. };
  57. protected enum Type {
  58. HEARTBEAT(0), PUSH(1), XHR(2);
  59. private int priority;
  60. private Type(int priority) {
  61. this.priority = priority;
  62. }
  63. public boolean isMessage() {
  64. return this == PUSH || this == XHR;
  65. }
  66. /**
  67. * Checks if this type is of higher priority than the given type
  68. *
  69. * @param type
  70. * the type to compare to
  71. * @return true if this type has higher priority than the given type,
  72. * false otherwise
  73. */
  74. public boolean isHigherPriorityThan(Type type) {
  75. return priority > type.priority;
  76. }
  77. }
  78. @Override
  79. public void setConnection(ApplicationConnection connection) {
  80. this.connection = connection;
  81. connection.addHandler(ApplicationStoppedEvent.TYPE,
  82. new ApplicationStoppedHandler() {
  83. @Override
  84. public void onApplicationStopped(
  85. ApplicationStoppedEvent event) {
  86. if (isReconnecting()) {
  87. giveUp();
  88. }
  89. if (scheduledReconnect != null
  90. && scheduledReconnect.isRunning()) {
  91. scheduledReconnect.cancel();
  92. }
  93. }
  94. });
  95. // Allow dialog to cache needed resources to make them available when we
  96. // are offline
  97. reconnectDialog.preload(connection);
  98. };
  99. /**
  100. * Checks if we are currently trying to reconnect
  101. *
  102. * @return true if we have noted a problem and are trying to re-establish
  103. * server connection, false otherwise
  104. */
  105. private boolean isReconnecting() {
  106. return reconnectionCause != null;
  107. }
  108. private static Logger getLogger() {
  109. return Logger.getLogger(DefaultConnectionStateHandler.class.getName());
  110. }
  111. /**
  112. * Returns the connection this handler is connected to
  113. *
  114. * @return the connection for this handler
  115. */
  116. protected ApplicationConnection getConnection() {
  117. return connection;
  118. }
  119. @Override
  120. public void xhrException(XhrConnectionError xhrConnectionError) {
  121. debug("xhrException");
  122. handleRecoverableError(Type.XHR, xhrConnectionError.getPayload());
  123. }
  124. @Override
  125. public void heartbeatException(Request request, Throwable exception) {
  126. getLogger().severe("Heartbeat exception: " + exception.getMessage());
  127. handleRecoverableError(Type.HEARTBEAT, null);
  128. }
  129. @Override
  130. public void heartbeatInvalidStatusCode(Request request, Response response) {
  131. int statusCode = response.getStatusCode();
  132. getLogger().warning("Heartbeat request returned " + statusCode);
  133. if (response.getStatusCode() == Response.SC_GONE) {
  134. // Session expired
  135. getConnection().showSessionExpiredError(null);
  136. stopApplication();
  137. } else if (response.getStatusCode() == Response.SC_NOT_FOUND) {
  138. // UI closed, do nothing as the UI will react to this
  139. // Should not trigger reconnect dialog as this will prevent user
  140. // input
  141. } else {
  142. handleRecoverableError(Type.HEARTBEAT, null);
  143. }
  144. }
  145. @Override
  146. public void heartbeatOk() {
  147. debug("heartbeatOk");
  148. if (isReconnecting()) {
  149. resolveTemporaryError(Type.HEARTBEAT);
  150. }
  151. }
  152. private void debug(String msg) {
  153. if (false) {
  154. getLogger().warning(msg);
  155. }
  156. }
  157. /**
  158. * Called whenever an error occurs in communication which should be handled
  159. * by showing the reconnect dialog and retrying communication until
  160. * successful again
  161. *
  162. * @param type
  163. * The type of failure detected
  164. * @param payload
  165. * The message which did not reach the server, or null if no
  166. * message was involved (heartbeat or push connection failed)
  167. */
  168. protected void handleRecoverableError(Type type, final JsonObject payload) {
  169. debug("handleTemporaryError(" + type + ")");
  170. if (!connection.isApplicationRunning()) {
  171. return;
  172. }
  173. if (!isReconnecting()) {
  174. // First problem encounter
  175. reconnectionCause = type;
  176. getLogger().warning("Reconnecting because of " + type + " failure");
  177. // Precaution only as there should never be a dialog at this point
  178. // and no timer running
  179. stopDialogTimer();
  180. if (isDialogVisible()) {
  181. hideDialog();
  182. }
  183. // Show dialog after grace period, still continue to try to
  184. // reconnect even before it is shown
  185. dialogShowTimer.schedule(getConfiguration().dialogGracePeriod);
  186. } else {
  187. // We are currently trying to reconnect
  188. // Priority is HEARTBEAT -> PUSH -> XHR
  189. // If a higher priority issues is resolved, we can assume the lower
  190. // one will be also
  191. if (type.isHigherPriorityThan(reconnectionCause)) {
  192. getLogger().warning(
  193. "Now reconnecting because of " + type + " failure");
  194. reconnectionCause = type;
  195. }
  196. }
  197. if (reconnectionCause != type) {
  198. return;
  199. }
  200. reconnectAttempt++;
  201. getLogger().info(
  202. "Reconnect attempt " + reconnectAttempt + " for " + type);
  203. if (reconnectAttempt >= getConfiguration().reconnectAttempts) {
  204. // Max attempts reached, stop trying
  205. giveUp();
  206. } else {
  207. updateDialog();
  208. scheduleReconnect(payload);
  209. }
  210. }
  211. /**
  212. * Called after a problem occurred.
  213. *
  214. * This method is responsible for re-sending the payload to the server (if
  215. * not null) or re-send a heartbeat request at some point
  216. *
  217. * @param payload
  218. * the payload that did not reach the server, null if the problem
  219. * was detected by a heartbeat
  220. */
  221. protected void scheduleReconnect(final JsonObject payload) {
  222. // Here and not in timer to avoid TB for getting in between
  223. // The request is still open at this point to avoid interference, so we
  224. // do not need to start a new one
  225. if (reconnectAttempt == 1) {
  226. // Try once immediately
  227. doReconnect(payload);
  228. } else {
  229. scheduledReconnect = new Timer() {
  230. @Override
  231. public void run() {
  232. scheduledReconnect = null;
  233. doReconnect(payload);
  234. }
  235. };
  236. scheduledReconnect.schedule(getConfiguration().reconnectInterval);
  237. }
  238. }
  239. /**
  240. * Re-sends the payload to the server (if not null) or re-sends a heartbeat
  241. * request immediately
  242. *
  243. * @param payload
  244. * the payload that did not reach the server, null if the problem
  245. * was detected by a heartbeat
  246. */
  247. protected void doReconnect(JsonObject payload) {
  248. if (!connection.isApplicationRunning()) {
  249. // This should not happen as nobody should call this if the
  250. // application has been stopped
  251. getLogger()
  252. .warning(
  253. "Trying to reconnect after application has been stopped. Giving up");
  254. return;
  255. }
  256. if (payload != null) {
  257. getLogger().info("Re-sending last message to the server...");
  258. getConnection().getMessageSender().send(payload);
  259. } else {
  260. // Use heartbeat
  261. getLogger().info("Trying to re-establish server connection...");
  262. getConnection().getHeartbeat().send();
  263. }
  264. }
  265. /**
  266. * Called whenever a reconnect attempt fails to allow updating of dialog
  267. * contents
  268. */
  269. protected void updateDialog() {
  270. reconnectDialog.setText(getDialogText(reconnectAttempt));
  271. }
  272. /**
  273. * Called when we should give up trying to reconnect and let the user decide
  274. * how to continue
  275. *
  276. */
  277. protected void giveUp() {
  278. reconnectionCause = null;
  279. endRequest();
  280. stopDialogTimer();
  281. if (!isDialogVisible()) {
  282. // It SHOULD always be visible at this point, unless you have a
  283. // really strange configuration (grace time longer than total
  284. // reconnect time)
  285. showDialog();
  286. }
  287. reconnectDialog.setText(getDialogTextGaveUp(reconnectAttempt));
  288. reconnectDialog.setReconnecting(false);
  289. // Stopping the application stops heartbeats and push
  290. connection.setApplicationRunning(false);
  291. }
  292. /**
  293. * Ensures the reconnect dialog does not popup some time from now
  294. */
  295. private void stopDialogTimer() {
  296. if (dialogShowTimer.isRunning()) {
  297. dialogShowTimer.cancel();
  298. }
  299. }
  300. /**
  301. * Checks if the reconnect dialog is visible to the user
  302. *
  303. * @return true if the user can see the dialog, false otherwise
  304. */
  305. protected boolean isDialogVisible() {
  306. return reconnectDialog.isVisible();
  307. }
  308. /**
  309. * Called when the reconnect dialog should be shown. This is typically when
  310. * N seconds has passed since a problem with the connection has been
  311. * detected
  312. */
  313. protected void showDialog() {
  314. reconnectDialog.setReconnecting(true);
  315. reconnectDialog.show(connection);
  316. // We never want to show loading indicator and reconnect dialog at the
  317. // same time
  318. connection.getLoadingIndicator().hide();
  319. }
  320. /**
  321. * Called when the reconnect dialog should be hidden.
  322. */
  323. protected void hideDialog() {
  324. reconnectDialog.hide();
  325. }
  326. /**
  327. * Gets the text to show in the reconnect dialog after giving up (reconnect
  328. * limit reached)
  329. *
  330. * @param reconnectAttempt
  331. * The number of the current reconnection attempt
  332. * @return The text to show in the reconnect dialog after giving up
  333. */
  334. protected String getDialogTextGaveUp(int reconnectAttempt) {
  335. return getConfiguration().dialogTextGaveUp.replace("{0}",
  336. reconnectAttempt + "");
  337. }
  338. /**
  339. * Gets the text to show in the reconnect dialog
  340. *
  341. * @param reconnectAttempt
  342. * The number of the current reconnection attempt
  343. * @return The text to show in the reconnect dialog
  344. */
  345. protected String getDialogText(int reconnectAttempt) {
  346. return getConfiguration().dialogText.replace("{0}", reconnectAttempt
  347. + "");
  348. }
  349. @Override
  350. public void configurationUpdated() {
  351. // All other properties are fetched directly from the state when needed
  352. reconnectDialog.setModal(getConfiguration().dialogModal);
  353. }
  354. private ReconnectDialogConfigurationState getConfiguration() {
  355. return connection.getUIConnector().getState().reconnectDialogConfiguration;
  356. }
  357. @Override
  358. public void xhrInvalidContent(XhrConnectionError xhrConnectionError) {
  359. debug("xhrInvalidContent");
  360. endRequest();
  361. String responseText = xhrConnectionError.getResponse().getText();
  362. /*
  363. * A servlet filter or equivalent may have intercepted the request and
  364. * served non-UIDL content (for instance, a login page if the session
  365. * has expired.) If the response contains a magic substring, do a
  366. * synchronous refresh. See #8241.
  367. */
  368. MatchResult refreshToken = RegExp.compile(
  369. ApplicationConnection.UIDL_REFRESH_TOKEN
  370. + "(:\\s*(.*?))?(\\s|$)").exec(responseText);
  371. if (refreshToken != null) {
  372. WidgetUtil.redirect(refreshToken.getGroup(2));
  373. } else {
  374. handleUnrecoverableCommunicationError(
  375. "Invalid JSON response from server: " + responseText,
  376. xhrConnectionError);
  377. }
  378. }
  379. @Override
  380. public void pushInvalidContent(PushConnection pushConnection, String message) {
  381. debug("pushInvalidContent");
  382. if (pushConnection.isBidirectional()) {
  383. // We can't be sure that what was pushed was actually a response but
  384. // at this point it should not really matter, as something is
  385. // seriously broken.
  386. endRequest();
  387. }
  388. // Do nothing special for now. Should likely do the same as
  389. // xhrInvalidContent
  390. handleUnrecoverableCommunicationError("Invalid JSON from server: "
  391. + message, null);
  392. }
  393. @Override
  394. public void xhrInvalidStatusCode(XhrConnectionError xhrConnectionError) {
  395. debug("xhrInvalidStatusCode");
  396. Response response = xhrConnectionError.getResponse();
  397. int statusCode = response.getStatusCode();
  398. getLogger().warning("Server returned " + statusCode + " for xhr");
  399. if (statusCode == 401) {
  400. // Authentication/authorization failed, no need to re-try
  401. endRequest();
  402. handleUnauthorized(xhrConnectionError);
  403. return;
  404. } else {
  405. // 404, 408 and other 4xx codes CAN be temporary when you have a
  406. // proxy between the client and the server and e.g. restart the
  407. // server
  408. // 5xx codes may or may not be temporary
  409. handleRecoverableError(Type.XHR, xhrConnectionError.getPayload());
  410. }
  411. }
  412. private void endRequest() {
  413. getConnection().getMessageSender().endRequest();
  414. }
  415. protected void handleUnauthorized(XhrConnectionError xhrConnectionError) {
  416. /*
  417. * Authorization has failed (401). Could be that the session has timed
  418. * out.
  419. */
  420. connection.showAuthenticationError("");
  421. stopApplication();
  422. }
  423. private void stopApplication() {
  424. // Consider application not running any more and prevent all
  425. // future requests
  426. connection.setApplicationRunning(false);
  427. }
  428. private void handleUnrecoverableCommunicationError(String details,
  429. XhrConnectionError xhrConnectionError) {
  430. int statusCode = -1;
  431. if (xhrConnectionError != null) {
  432. Response response = xhrConnectionError.getResponse();
  433. if (response != null) {
  434. statusCode = response.getStatusCode();
  435. }
  436. }
  437. connection.handleCommunicationError(details, statusCode);
  438. stopApplication();
  439. }
  440. @Override
  441. public void xhrOk() {
  442. debug("xhrOk");
  443. if (isReconnecting()) {
  444. resolveTemporaryError(Type.XHR);
  445. }
  446. }
  447. private void resolveTemporaryError(Type type) {
  448. debug("resolveTemporaryError(" + type + ")");
  449. if (reconnectionCause != type) {
  450. // Waiting for some other problem to be resolved
  451. return;
  452. }
  453. reconnectionCause = null;
  454. reconnectAttempt = 0;
  455. // IF reconnect happens during grace period, make sure the dialog is not
  456. // shown and does not popup later
  457. stopDialogTimer();
  458. hideDialog();
  459. getLogger().info("Re-established connection to server");
  460. }
  461. @Override
  462. public void pushOk(PushConnection pushConnection) {
  463. debug("pushOk()");
  464. if (isReconnecting()) {
  465. resolveTemporaryError(Type.PUSH);
  466. }
  467. }
  468. @Override
  469. public void pushScriptLoadError(String resourceUrl) {
  470. connection.handleCommunicationError(resourceUrl
  471. + " could not be loaded. Push will not work.", 0);
  472. }
  473. @Override
  474. public void pushNotConnected(JsonObject payload) {
  475. debug("pushNotConnected()");
  476. handleRecoverableError(Type.PUSH, payload);
  477. }
  478. @Override
  479. public void pushReconnectPending(PushConnection pushConnection) {
  480. debug("pushReconnectPending(" + pushConnection.getTransportType() + ")");
  481. getLogger().info("Reopening push connection");
  482. if (pushConnection.isBidirectional()) {
  483. // Lost connection for a connection which will tell us when the
  484. // connection is available again
  485. handleRecoverableError(Type.PUSH, null);
  486. } else {
  487. // Lost connection for a connection we do not necessarily know when
  488. // it is available again (long polling behind proxy). Do nothing and
  489. // show reconnect dialog if the user does something and the XHR
  490. // fails
  491. }
  492. }
  493. @Override
  494. public void pushError(PushConnection pushConnection,
  495. JavaScriptObject response) {
  496. debug("pushError()");
  497. connection.handleCommunicationError("Push connection using "
  498. + ((AtmosphereResponse) response).getTransport() + " failed!",
  499. -1);
  500. }
  501. @Override
  502. public void pushClientTimeout(PushConnection pushConnection,
  503. JavaScriptObject response) {
  504. debug("pushClientTimeout()");
  505. // TODO Reconnect, allowing client timeout to be set
  506. // https://dev.vaadin.com/ticket/18429
  507. connection
  508. .handleCommunicationError(
  509. "Client unexpectedly disconnected. Ensure client timeout is disabled.",
  510. -1);
  511. }
  512. @Override
  513. public void pushClosed(PushConnection pushConnection,
  514. JavaScriptObject response) {
  515. debug("pushClosed()");
  516. getLogger().info("Push connection closed");
  517. }
  518. }