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.

AtmospherePushConnection.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /*
  2. * Copyright 2000-2021 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.client.Scheduler;
  20. import com.google.gwt.user.client.Command;
  21. import com.google.gwt.user.client.Window.Location;
  22. import com.vaadin.client.ApplicationConfiguration;
  23. import com.vaadin.client.ApplicationConnection;
  24. import com.vaadin.client.ApplicationConnection.ApplicationStoppedEvent;
  25. import com.vaadin.client.ResourceLoader;
  26. import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
  27. import com.vaadin.client.ResourceLoader.ResourceLoadListener;
  28. import com.vaadin.client.ValueMap;
  29. import com.vaadin.shared.ApplicationConstants;
  30. import com.vaadin.shared.Version;
  31. import com.vaadin.shared.communication.PushConstants;
  32. import com.vaadin.shared.ui.ui.UIConstants;
  33. import com.vaadin.shared.ui.ui.UIState.PushConfigurationState;
  34. import com.vaadin.shared.util.SharedUtil;
  35. import elemental.json.JsonObject;
  36. /**
  37. * The default {@link PushConnection} implementation that uses Atmosphere for
  38. * handling the communication channel.
  39. *
  40. * @author Vaadin Ltd
  41. * @since 7.1
  42. */
  43. public class AtmospherePushConnection implements PushConnection {
  44. protected enum State {
  45. /**
  46. * Opening request has been sent, but still waiting for confirmation.
  47. */
  48. CONNECT_PENDING,
  49. /**
  50. * Connection is open and ready to use.
  51. */
  52. CONNECTED,
  53. /**
  54. * Connection was disconnected while the connection was pending. Wait
  55. * for the connection to get established before closing it. No new
  56. * messages are accepted, but pending messages will still be delivered.
  57. */
  58. DISCONNECT_PENDING,
  59. /**
  60. * Connection has been disconnected and should not be used any more.
  61. */
  62. DISCONNECTED;
  63. }
  64. /**
  65. * Represents a message that should be sent as multiple fragments.
  66. */
  67. protected static class FragmentedMessage {
  68. private static final int FRAGMENT_LENGTH = PushConstants.WEBSOCKET_FRAGMENT_SIZE;
  69. private String message;
  70. private int index = 0;
  71. public FragmentedMessage(String message) {
  72. this.message = message;
  73. }
  74. public boolean hasNextFragment() {
  75. return index < message.length();
  76. }
  77. public String getNextFragment() {
  78. assert hasNextFragment();
  79. String result;
  80. if (index == 0) {
  81. String header = "" + message.length()
  82. + PushConstants.MESSAGE_DELIMITER;
  83. int fragmentLen = FRAGMENT_LENGTH - header.length();
  84. result = header + getFragment(0, fragmentLen);
  85. index += fragmentLen;
  86. } else {
  87. result = getFragment(index, index + FRAGMENT_LENGTH);
  88. index += FRAGMENT_LENGTH;
  89. }
  90. return result;
  91. }
  92. private String getFragment(int begin, int end) {
  93. return message.substring(begin, Math.min(message.length(), end));
  94. }
  95. }
  96. private ApplicationConnection connection;
  97. private JavaScriptObject socket;
  98. private State state = State.CONNECT_PENDING;
  99. private AtmosphereConfiguration config;
  100. private String uri;
  101. private String transport;
  102. /**
  103. * Keeps track of the disconnect confirmation command for cases where
  104. * pending messages should be pushed before actually disconnecting.
  105. */
  106. private Command pendingDisconnectCommand;
  107. /**
  108. * The url to use for push requests
  109. */
  110. private String url;
  111. public AtmospherePushConnection() {
  112. }
  113. /*
  114. * (non-Javadoc)
  115. *
  116. * @see
  117. * com.vaadin.client.communication.PushConnection#init(ApplicationConnection
  118. * , Map<String, String>, CommunicationErrorHandler)
  119. */
  120. @Override
  121. public void init(final ApplicationConnection connection,
  122. final PushConfigurationState pushConfiguration) {
  123. this.connection = connection;
  124. connection.addHandler(ApplicationStoppedEvent.TYPE, event -> {
  125. if (state == State.DISCONNECT_PENDING
  126. || state == State.DISCONNECTED) {
  127. return;
  128. }
  129. disconnect(() -> {
  130. });
  131. });
  132. config = createConfig();
  133. String debugParameter = Location.getParameter("debug");
  134. if ("push".equals(debugParameter)) {
  135. config.setStringValue("logLevel", "debug");
  136. }
  137. for (String param : pushConfiguration.parameters.keySet()) {
  138. String value = pushConfiguration.parameters.get(param);
  139. if (value.equalsIgnoreCase("true")
  140. || value.equalsIgnoreCase("false")) {
  141. config.setBooleanValue(param, value.equalsIgnoreCase("true"));
  142. } else {
  143. config.setStringValue(param, value);
  144. }
  145. }
  146. if (pushConfiguration.pushUrl != null) {
  147. url = pushConfiguration.pushUrl;
  148. } else {
  149. url = ApplicationConstants.APP_PROTOCOL_PREFIX
  150. + ApplicationConstants.PUSH_PATH;
  151. }
  152. runWhenAtmosphereLoaded(
  153. () -> Scheduler.get().scheduleDeferred(() -> connect()));
  154. }
  155. private void connect() {
  156. String baseUrl = connection.translateVaadinUri(url);
  157. String extraParams = UIConstants.UI_ID_PARAMETER + "="
  158. + connection.getConfiguration().getUIId();
  159. String pushId = connection.getMessageHandler().getPushId();
  160. if (pushId != null) {
  161. extraParams += "&" + ApplicationConstants.PUSH_ID_PARAMETER + "="
  162. + pushId;
  163. }
  164. // uri is needed to identify the right connection when closing
  165. uri = SharedUtil.addGetParameters(baseUrl, extraParams);
  166. getLogger().info("Establishing push connection");
  167. socket = doConnect(uri, getConfig());
  168. }
  169. @Override
  170. public boolean isActive() {
  171. switch (state) {
  172. case CONNECT_PENDING:
  173. case CONNECTED:
  174. return true;
  175. default:
  176. return false;
  177. }
  178. }
  179. @Override
  180. public boolean isBidirectional() {
  181. if (transport == null) {
  182. return false;
  183. }
  184. if (!transport.equals("websocket")) {
  185. // If we are not using websockets, we want to send XHRs
  186. return false;
  187. }
  188. if (getPushConfigurationState().alwaysUseXhrForServerRequests) {
  189. // If user has forced us to use XHR, let's abide
  190. return false;
  191. }
  192. if (state == State.CONNECT_PENDING) {
  193. // Not sure yet, let's go for using websockets still as still will
  194. // delay the message until a connection is established. When the
  195. // connection is established, bi-directionality will be checked
  196. // again to be sure
  197. }
  198. return true;
  199. };
  200. private PushConfigurationState getPushConfigurationState() {
  201. return connection.getUIConnector().getState().pushConfiguration;
  202. }
  203. @Override
  204. public void push(JsonObject message) {
  205. if (!isBidirectional()) {
  206. throw new IllegalStateException(
  207. "This server to client push connection should not be used to send client to server messages");
  208. }
  209. if (state == State.CONNECTED) {
  210. getLogger().info("Sending push (" + transport
  211. + ") message to server: " + message.toJson());
  212. if (transport.equals("websocket")) {
  213. FragmentedMessage fragmented = new FragmentedMessage(
  214. message.toJson());
  215. while (fragmented.hasNextFragment()) {
  216. doPush(socket, fragmented.getNextFragment());
  217. }
  218. } else {
  219. doPush(socket, message.toJson());
  220. }
  221. return;
  222. }
  223. if (state == State.CONNECT_PENDING) {
  224. getConnectionStateHandler().pushNotConnected(message);
  225. return;
  226. }
  227. throw new IllegalStateException("Can not push after disconnecting");
  228. }
  229. protected AtmosphereConfiguration getConfig() {
  230. return config;
  231. }
  232. protected void onReopen(AtmosphereResponse response) {
  233. getLogger().info("Push connection re-established using "
  234. + response.getTransport());
  235. onConnect(response);
  236. }
  237. protected void onOpen(AtmosphereResponse response) {
  238. getLogger().info(
  239. "Push connection established using " + response.getTransport());
  240. onConnect(response);
  241. }
  242. /**
  243. * Called whenever a server push connection is established (or
  244. * re-established).
  245. *
  246. * @param response
  247. *
  248. * @since 7.2
  249. */
  250. protected void onConnect(AtmosphereResponse response) {
  251. transport = response.getTransport();
  252. switch (state) {
  253. case CONNECT_PENDING:
  254. state = State.CONNECTED;
  255. getConnectionStateHandler().pushOk(this);
  256. break;
  257. case DISCONNECT_PENDING:
  258. // Set state to connected to make disconnect close the connection
  259. state = State.CONNECTED;
  260. assert pendingDisconnectCommand != null;
  261. disconnect(pendingDisconnectCommand);
  262. break;
  263. case CONNECTED:
  264. // IE likes to open the same connection multiple times, just ignore
  265. break;
  266. default:
  267. throw new IllegalStateException(
  268. "Got onOpen event when conncetion state is " + state
  269. + ". This should never happen.");
  270. }
  271. }
  272. /*
  273. * (non-Javadoc)
  274. *
  275. * @see com.vaadin.client.communication.PushConenction#disconnect()
  276. */
  277. @Override
  278. public void disconnect(Command command) {
  279. assert command != null;
  280. switch (state) {
  281. case CONNECT_PENDING:
  282. // Make the connection callback initiate the disconnection again
  283. state = State.DISCONNECT_PENDING;
  284. pendingDisconnectCommand = command;
  285. break;
  286. case CONNECTED:
  287. // Normal disconnect
  288. getLogger().info("Closing push connection");
  289. doDisconnect(uri);
  290. state = State.DISCONNECTED;
  291. command.execute();
  292. break;
  293. case DISCONNECT_PENDING:
  294. case DISCONNECTED:
  295. throw new IllegalStateException(
  296. "Can not disconnect more than once");
  297. }
  298. }
  299. protected void onMessage(AtmosphereResponse response) {
  300. String message = response.getResponseBody();
  301. ValueMap json = MessageHandler.parseWrappedJson(message);
  302. if (json == null) {
  303. // Invalid string (not wrapped as expected)
  304. getConnectionStateHandler().pushInvalidContent(this, message);
  305. return;
  306. } else {
  307. getLogger().info("Received push (" + getTransportType()
  308. + ") message: " + message);
  309. connection.getMessageHandler().handleMessage(json);
  310. }
  311. }
  312. /**
  313. * Called if the transport mechanism cannot be used and the fallback will be
  314. * tried.
  315. */
  316. protected void onTransportFailure() {
  317. getLogger().warning("Push connection using primary method ("
  318. + getConfig().getTransport() + ") failed. Trying with "
  319. + getConfig().getFallbackTransport());
  320. }
  321. /**
  322. * Called if the push connection fails. Atmosphere will automatically retry
  323. * the connection until successful.
  324. *
  325. */
  326. protected void onError(AtmosphereResponse response) {
  327. state = State.DISCONNECTED;
  328. getConnectionStateHandler().pushError(this, response);
  329. }
  330. protected void onClose(AtmosphereResponse response) {
  331. state = State.CONNECT_PENDING;
  332. getConnectionStateHandler().pushClosed(this, response);
  333. }
  334. protected void onClientTimeout(AtmosphereResponse response) {
  335. state = State.DISCONNECTED;
  336. getConnectionStateHandler().pushClientTimeout(this, response);
  337. }
  338. protected void onReconnect(JavaScriptObject request,
  339. final AtmosphereResponse response) {
  340. if (state == State.CONNECTED) {
  341. state = State.CONNECT_PENDING;
  342. }
  343. getConnectionStateHandler().pushReconnectPending(this);
  344. }
  345. public abstract static class AbstractJSO extends JavaScriptObject {
  346. protected AbstractJSO() {
  347. }
  348. protected final native String getStringValue(String key)
  349. /*-{
  350. return this[key];
  351. }-*/;
  352. protected final native void setStringValue(String key, String value)
  353. /*-{
  354. this[key] = value;
  355. }-*/;
  356. protected final native int getIntValue(String key)
  357. /*-{
  358. return this[key];
  359. }-*/;
  360. protected final native void setIntValue(String key, int value)
  361. /*-{
  362. this[key] = value;
  363. }-*/;
  364. protected final native boolean getBooleanValue(String key)
  365. /*-{
  366. return this[key];
  367. }-*/;
  368. protected final native void setBooleanValue(String key, boolean value)
  369. /*-{
  370. this[key] = value;
  371. }-*/;
  372. }
  373. public static class AtmosphereConfiguration extends AbstractJSO {
  374. protected AtmosphereConfiguration() {
  375. super();
  376. }
  377. public final String getTransport() {
  378. return getStringValue("transport");
  379. }
  380. public final String getFallbackTransport() {
  381. return getStringValue("fallbackTransport");
  382. }
  383. public final void setTransport(String transport) {
  384. setStringValue("transport", transport);
  385. }
  386. public final void setFallbackTransport(String fallbackTransport) {
  387. setStringValue("fallbackTransport", fallbackTransport);
  388. }
  389. }
  390. public static class AtmosphereResponse extends AbstractJSO {
  391. protected AtmosphereResponse() {
  392. }
  393. public final int getStatusCode() {
  394. return getIntValue("status");
  395. }
  396. public final String getResponseBody() {
  397. return getStringValue("responseBody");
  398. }
  399. public final String getState() {
  400. return getStringValue("state");
  401. }
  402. public final String getError() {
  403. return getStringValue("error");
  404. }
  405. public final String getTransport() {
  406. return getStringValue("transport");
  407. }
  408. }
  409. protected native AtmosphereConfiguration createConfig()
  410. /*-{
  411. return {
  412. transport: 'websocket',
  413. maxStreamingLength: 1000000,
  414. fallbackTransport: 'long-polling',
  415. contentType: 'application/json; charset=UTF-8',
  416. reconnectInterval: 5000,
  417. timeout: -1,
  418. maxReconnectOnClose: 10000000,
  419. trackMessageLength: true,
  420. enableProtocol: true,
  421. handleOnlineOffline: false,
  422. messageDelimiter: String.fromCharCode(@com.vaadin.shared.communication.PushConstants::MESSAGE_DELIMITER)
  423. };
  424. }-*/;
  425. private native JavaScriptObject doConnect(String uri,
  426. JavaScriptObject config)
  427. /*-{
  428. var self = this;
  429. config.url = uri;
  430. config.onOpen = $entry(function(response) {
  431. self.@com.vaadin.client.communication.AtmospherePushConnection::onOpen(*)(response);
  432. });
  433. config.onReopen = $entry(function(response) {
  434. self.@com.vaadin.client.communication.AtmospherePushConnection::onReopen(*)(response);
  435. });
  436. config.onMessage = $entry(function(response) {
  437. self.@com.vaadin.client.communication.AtmospherePushConnection::onMessage(*)(response);
  438. });
  439. config.onError = $entry(function(response) {
  440. self.@com.vaadin.client.communication.AtmospherePushConnection::onError(*)(response);
  441. });
  442. config.onTransportFailure = $entry(function(reason,request) {
  443. self.@com.vaadin.client.communication.AtmospherePushConnection::onTransportFailure(*)(reason);
  444. });
  445. config.onClose = $entry(function(response) {
  446. self.@com.vaadin.client.communication.AtmospherePushConnection::onClose(*)(response);
  447. });
  448. config.onReconnect = $entry(function(request, response) {
  449. self.@com.vaadin.client.communication.AtmospherePushConnection::onReconnect(*)(request, response);
  450. });
  451. config.onClientTimeout = $entry(function(request) {
  452. self.@com.vaadin.client.communication.AtmospherePushConnection::onClientTimeout(*)(request);
  453. });
  454. return $wnd.vaadinPush.atmosphere.subscribe(config);
  455. }-*/;
  456. private native void doPush(JavaScriptObject socket, String message)
  457. /*-{
  458. socket.push(message);
  459. }-*/;
  460. private static native void doDisconnect(String url)
  461. /*-{
  462. $wnd.vaadinPush.atmosphere.unsubscribeUrl(url);
  463. }-*/;
  464. private static native boolean isAtmosphereLoaded()
  465. /*-{
  466. return $wnd.vaadinPush && $wnd.vaadinPush.atmosphere;
  467. }-*/;
  468. private void runWhenAtmosphereLoaded(final Command command) {
  469. if (isAtmosphereLoaded()) {
  470. command.execute();
  471. } else {
  472. final String pushJs = getVersionedPushJs();
  473. getLogger().info("Loading " + pushJs);
  474. ResourceLoader.get().loadScript(
  475. connection.getConfiguration().getVaadinDirUrl() + pushJs,
  476. new ResourceLoadListener() {
  477. @Override
  478. public void onLoad(ResourceLoadEvent event) {
  479. if (isAtmosphereLoaded()) {
  480. getLogger().info(pushJs + " loaded");
  481. command.execute();
  482. } else {
  483. // If bootstrap tried to load vaadinPush.js,
  484. // ResourceLoader assumes it succeeded even if
  485. // it failed (#11673)
  486. onError(event);
  487. }
  488. }
  489. @Override
  490. public void onError(ResourceLoadEvent event) {
  491. getConnectionStateHandler().pushScriptLoadError(
  492. event.getResourceUrl());
  493. }
  494. });
  495. }
  496. }
  497. private String getVersionedPushJs() {
  498. String pushJs;
  499. if (ApplicationConfiguration.isProductionMode()) {
  500. pushJs = ApplicationConstants.VAADIN_PUSH_JS;
  501. } else {
  502. pushJs = ApplicationConstants.VAADIN_PUSH_DEBUG_JS;
  503. }
  504. // Parameter appended to bypass caches after version upgrade.
  505. pushJs += "?v=" + Version.getFullVersion();
  506. return pushJs;
  507. }
  508. @Override
  509. public String getTransportType() {
  510. return transport;
  511. }
  512. private static Logger getLogger() {
  513. return Logger.getLogger(AtmospherePushConnection.class.getName());
  514. }
  515. private ConnectionStateHandler getConnectionStateHandler() {
  516. return connection.getConnectionStateHandler();
  517. }
  518. }