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 18KB

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