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

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