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.

MessageSender.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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.GWT;
  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.RequestStartingEvent;
  24. import com.vaadin.client.ApplicationConnection.ResponseHandlingEndedEvent;
  25. import com.vaadin.client.Util;
  26. import com.vaadin.client.VLoadingIndicator;
  27. import com.vaadin.shared.ApplicationConstants;
  28. import com.vaadin.shared.Version;
  29. import com.vaadin.shared.ui.ui.UIState.PushConfigurationState;
  30. import elemental.json.Json;
  31. import elemental.json.JsonArray;
  32. import elemental.json.JsonObject;
  33. import elemental.json.JsonValue;
  34. /**
  35. * MessageSender is responsible for sending messages to the server.
  36. * <p>
  37. * Internally uses {@link XhrConnection} and/or {@link PushConnection} for
  38. * delivering messages, depending on the application configuration.
  39. *
  40. * @since 7.6
  41. * @author Vaadin Ltd
  42. */
  43. public class MessageSender {
  44. private ApplicationConnection connection;
  45. private boolean hasActiveRequest = false;
  46. /**
  47. * Counter for the messages send to the server. First sent message has id 0.
  48. */
  49. private int clientToServerMessageId = 0;
  50. private XhrConnection xhrConnection;
  51. private PushConnection push;
  52. public MessageSender() {
  53. xhrConnection = GWT.create(XhrConnection.class);
  54. }
  55. /**
  56. * Sets the application connection this instance is connected to. Called
  57. * internally by the framework.
  58. *
  59. * @param connection
  60. * the application connection this instance is connected to
  61. */
  62. public void setConnection(ApplicationConnection connection) {
  63. this.connection = connection;
  64. xhrConnection.setConnection(connection);
  65. }
  66. private static Logger getLogger() {
  67. return Logger.getLogger(MessageSender.class.getName());
  68. }
  69. public void sendInvocationsToServer() {
  70. if (!connection.isApplicationRunning()) {
  71. getLogger().warning(
  72. "Trying to send RPC from not yet started or stopped application");
  73. return;
  74. }
  75. if (hasActiveRequest() || (push != null && !push.isActive())) {
  76. // There is an active request or push is enabled but not active
  77. // -> send when current request completes or push becomes active
  78. } else {
  79. doSendInvocationsToServer();
  80. }
  81. }
  82. /**
  83. * Sends all pending method invocations (server RPC and legacy variable
  84. * changes) to the server.
  85. *
  86. */
  87. private void doSendInvocationsToServer() {
  88. ServerRpcQueue serverRpcQueue = getServerRpcQueue();
  89. if (serverRpcQueue.isEmpty()) {
  90. return;
  91. }
  92. if (ApplicationConfiguration.isDebugMode()) {
  93. Util.logMethodInvocations(connection, serverRpcQueue.getAll());
  94. }
  95. boolean showLoadingIndicator = serverRpcQueue.showLoadingIndicator();
  96. JsonArray reqJson = serverRpcQueue.toJson();
  97. serverRpcQueue.clear();
  98. if (reqJson.length() == 0) {
  99. // Nothing to send, all invocations were filtered out (for
  100. // non-existing connectors)
  101. getLogger().warning(
  102. "All RPCs filtered out, not sending anything to the server");
  103. return;
  104. }
  105. JsonObject extraJson = Json.createObject();
  106. if (!connection.getConfiguration().isWidgetsetVersionSent()) {
  107. extraJson.put(ApplicationConstants.WIDGETSET_VERSION_ID,
  108. Version.getFullVersion());
  109. connection.getConfiguration().setWidgetsetVersionSent();
  110. }
  111. if (showLoadingIndicator) {
  112. connection.getLoadingIndicator().trigger();
  113. }
  114. send(reqJson, extraJson);
  115. }
  116. private ServerRpcQueue getServerRpcQueue() {
  117. return connection.getServerRpcQueue();
  118. }
  119. /**
  120. * Makes an UIDL request to the server.
  121. *
  122. * @param reqInvocations
  123. * Data containing RPC invocations and all related information.
  124. * @param extraParams
  125. * Parameters that are added to the payload
  126. */
  127. protected void send(final JsonArray reqInvocations,
  128. final JsonObject extraJson) {
  129. startRequest();
  130. JsonObject payload = Json.createObject();
  131. String csrfToken = getMessageHandler().getCsrfToken();
  132. if (!csrfToken.equals(ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE)) {
  133. payload.put(ApplicationConstants.CSRF_TOKEN, csrfToken);
  134. }
  135. payload.put(ApplicationConstants.RPC_INVOCATIONS, reqInvocations);
  136. payload.put(ApplicationConstants.SERVER_SYNC_ID,
  137. getMessageHandler().getLastSeenServerSyncId());
  138. payload.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
  139. clientToServerMessageId++);
  140. if (extraJson != null) {
  141. for (String key : extraJson.keys()) {
  142. JsonValue value = extraJson.get(key);
  143. payload.put(key, value);
  144. }
  145. }
  146. send(payload);
  147. }
  148. /**
  149. * Sends an asynchronous or synchronous UIDL request to the server using the
  150. * given URI.
  151. *
  152. * @param uri
  153. * The URI to use for the request. May includes GET parameters
  154. * @param payload
  155. * The contents of the request to send
  156. */
  157. public void send(final JsonObject payload) {
  158. if (push != null && push.isBidirectional()) {
  159. push.push(payload);
  160. } else {
  161. xhrConnection.send(payload);
  162. }
  163. }
  164. /**
  165. * Sets the status for the push connection.
  166. *
  167. * @param enabled
  168. * <code>true</code> to enable the push connection;
  169. * <code>false</code> to disable the push connection.
  170. */
  171. public void setPushEnabled(boolean enabled) {
  172. final PushConfigurationState pushState = connection.getUIConnector()
  173. .getState().pushConfiguration;
  174. if (enabled && push == null) {
  175. push = GWT.create(PushConnection.class);
  176. push.init(connection, pushState);
  177. } else if (!enabled && push != null && push.isActive()) {
  178. push.disconnect(new Command() {
  179. @Override
  180. public void execute() {
  181. push = null;
  182. /*
  183. * If push has been enabled again while we were waiting for
  184. * the old connection to disconnect, now is the right time
  185. * to open a new connection
  186. */
  187. if (pushState.mode.isEnabled()) {
  188. setPushEnabled(true);
  189. }
  190. /*
  191. * Send anything that was enqueued while we waited for the
  192. * connection to close
  193. */
  194. if (getServerRpcQueue().isFlushPending()) {
  195. getServerRpcQueue().flush();
  196. }
  197. }
  198. });
  199. }
  200. }
  201. public void startRequest() {
  202. if (hasActiveRequest) {
  203. getLogger().severe(
  204. "Trying to start a new request while another is active");
  205. }
  206. hasActiveRequest = true;
  207. connection.fireEvent(new RequestStartingEvent(connection));
  208. }
  209. public void endRequest() {
  210. if (!hasActiveRequest) {
  211. getLogger().severe("No active request");
  212. }
  213. // After sendInvocationsToServer() there may be a new active
  214. // request, so we must set hasActiveRequest to false before, not after,
  215. // the call.
  216. hasActiveRequest = false;
  217. if (connection.isApplicationRunning()) {
  218. if (getServerRpcQueue().isFlushPending()) {
  219. sendInvocationsToServer();
  220. }
  221. runPostRequestHooks(connection.getConfiguration().getRootPanelId());
  222. }
  223. // deferring to avoid flickering
  224. Scheduler.get().scheduleDeferred(new Command() {
  225. @Override
  226. public void execute() {
  227. if (!connection.isApplicationRunning() || !(hasActiveRequest()
  228. || getServerRpcQueue().isFlushPending())) {
  229. getLoadingIndicator().hide();
  230. // If on Liferay and session expiration management is in
  231. // use, extend session duration on each request.
  232. // Doing it here rather than before the request to improve
  233. // responsiveness.
  234. // Postponed until the end of the next request if other
  235. // requests still pending.
  236. extendLiferaySession();
  237. }
  238. }
  239. });
  240. connection.fireEvent(new ResponseHandlingEndedEvent(connection));
  241. }
  242. /**
  243. * Runs possibly registered client side post request hooks. This is expected
  244. * to be run after each uidl request made by Vaadin application.
  245. *
  246. * @param appId
  247. */
  248. public static native void runPostRequestHooks(String appId)
  249. /*-{
  250. if ($wnd.vaadin.postRequestHooks) {
  251. for ( var hook in $wnd.vaadin.postRequestHooks) {
  252. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  253. try {
  254. $wnd.vaadin.postRequestHooks[hook](appId);
  255. } catch (e) {
  256. }
  257. }
  258. }
  259. }
  260. }-*/;
  261. /**
  262. * If on Liferay and logged in, ask the client side session management
  263. * JavaScript to extend the session duration.
  264. *
  265. * Otherwise, Liferay client side JavaScript will explicitly expire the
  266. * session even though the server side considers the session to be active.
  267. * See ticket #8305 for more information.
  268. */
  269. public static native void extendLiferaySession()
  270. /*-{
  271. if ($wnd.Liferay && $wnd.Liferay.Session) {
  272. $wnd.Liferay.Session.extend();
  273. // if the extend banner is visible, hide it
  274. if ($wnd.Liferay.Session.banner) {
  275. $wnd.Liferay.Session.banner.remove();
  276. }
  277. }
  278. }-*/;
  279. /**
  280. * Indicates whether or not there are currently active UIDL requests. Used
  281. * internally to sequence requests properly, seldom needed in Widgets.
  282. *
  283. * @return true if there are active requests
  284. */
  285. public boolean hasActiveRequest() {
  286. return hasActiveRequest;
  287. }
  288. /**
  289. * Returns a human readable string representation of the method used to
  290. * communicate with the server.
  291. *
  292. * @return A string representation of the current transport type
  293. */
  294. public String getCommunicationMethodName() {
  295. String clientToServer = "XHR";
  296. String serverToClient = "-";
  297. if (push != null) {
  298. serverToClient = push.getTransportType();
  299. if (push.isBidirectional()) {
  300. clientToServer = serverToClient;
  301. }
  302. }
  303. return "Client to server: " + clientToServer + ", "
  304. + "server to client: " + serverToClient;
  305. }
  306. private ConnectionStateHandler getConnectionStateHandler() {
  307. return connection.getConnectionStateHandler();
  308. }
  309. private MessageHandler getMessageHandler() {
  310. return connection.getMessageHandler();
  311. }
  312. private VLoadingIndicator getLoadingIndicator() {
  313. return connection.getLoadingIndicator();
  314. }
  315. /**
  316. * Resynchronize the client side, i.e. reload all component hierarchy and
  317. * state from the server
  318. */
  319. public void resynchronize() {
  320. getLogger().info("Resynchronizing from server");
  321. JsonObject resyncParam = Json.createObject();
  322. resyncParam.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
  323. send(Json.createArray(), resyncParam);
  324. }
  325. /**
  326. * Used internally to update what the server expects
  327. *
  328. * @param clientToServerMessageId
  329. * the new client id to set
  330. * @param force
  331. * true if the id must be updated, false otherwise
  332. */
  333. public void setClientToServerMessageId(int nextExpectedId, boolean force) {
  334. if (nextExpectedId == clientToServerMessageId) {
  335. // No op as everything matches they way it should
  336. return;
  337. }
  338. if (force) {
  339. getLogger().info(
  340. "Forced update of clientId to " + clientToServerMessageId);
  341. clientToServerMessageId = nextExpectedId;
  342. return;
  343. }
  344. if (nextExpectedId > clientToServerMessageId) {
  345. if (clientToServerMessageId == 0) {
  346. // We have never sent a message to the server, so likely the
  347. // server knows better (typical case is that we refreshed a
  348. // @PreserveOnRefresh UI)
  349. getLogger().info("Updating client-to-server id to "
  350. + nextExpectedId + " based on server");
  351. } else {
  352. getLogger().warning(
  353. "Server expects next client-to-server id to be "
  354. + nextExpectedId + " but we were going to use "
  355. + clientToServerMessageId + ". Will use "
  356. + nextExpectedId + ".");
  357. }
  358. clientToServerMessageId = nextExpectedId;
  359. } else {
  360. // Server has not yet seen all our messages
  361. // Do nothing as they will arrive eventually
  362. }
  363. }
  364. }