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

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