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

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