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

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