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

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