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

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