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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. /**
  34. * MessageSender is responsible for sending messages to the server.
  35. * <p>
  36. * Internally uses {@link XhrConnection} and/or {@link PushConnection} for
  37. * delivering messages, depending on the application configuration.
  38. *
  39. * @since 7.6
  40. * @author Vaadin Ltd
  41. */
  42. public class MessageSender {
  43. private ApplicationConnection connection;
  44. private boolean hasActiveRequest = false;
  45. /**
  46. * Counter for the messages send to the server. First sent message has id 0.
  47. */
  48. private int clientToServerMessageId = 0;
  49. private XhrConnection xhrConnection;
  50. private PushConnection push;
  51. public MessageSender() {
  52. xhrConnection = GWT.create(XhrConnection.class);
  53. }
  54. /**
  55. * Sets the application connection this instance is connected to. Called
  56. * internally by the framework.
  57. *
  58. * @param connection
  59. * the application connection this instance is connected to
  60. */
  61. public void setConnection(ApplicationConnection connection) {
  62. this.connection = connection;
  63. xhrConnection.setConnection(connection);
  64. }
  65. private static Logger getLogger() {
  66. return Logger.getLogger(MessageSender.class.getName());
  67. }
  68. public void sendInvocationsToServer() {
  69. if (!connection.isApplicationRunning()) {
  70. getLogger()
  71. .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()
  102. .warning(
  103. "All RPCs filtered out, not sending anything to the server");
  104. return;
  105. }
  106. JsonObject extraJson = Json.createObject();
  107. if (!connection.getConfiguration().isWidgetsetVersionSent()) {
  108. extraJson.put(ApplicationConstants.WIDGETSET_VERSION_ID,
  109. Version.getFullVersion());
  110. connection.getConfiguration().setWidgetsetVersionSent();
  111. }
  112. if (showLoadingIndicator) {
  113. connection.getLoadingIndicator().trigger();
  114. }
  115. send(reqJson, extraJson);
  116. }
  117. private ServerRpcQueue getServerRpcQueue() {
  118. return connection.getServerRpcQueue();
  119. }
  120. /**
  121. * Makes an UIDL request to the server.
  122. *
  123. * @param reqInvocations
  124. * Data containing RPC invocations and all related information.
  125. * @param extraParams
  126. * Parameters that are added to the payload
  127. */
  128. protected void send(final JsonArray reqInvocations,
  129. final JsonObject extraJson) {
  130. startRequest();
  131. JsonObject payload = Json.createObject();
  132. String csrfToken = getMessageHandler().getCsrfToken();
  133. if (!csrfToken.equals(ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE)) {
  134. payload.put(ApplicationConstants.CSRF_TOKEN, csrfToken);
  135. }
  136. payload.put(ApplicationConstants.RPC_INVOCATIONS, reqInvocations);
  137. payload.put(ApplicationConstants.SERVER_SYNC_ID, getMessageHandler()
  138. .getLastSeenServerSyncId());
  139. payload.put(ApplicationConstants.CLIENT_TO_SERVER_ID,
  140. clientToServerMessageId++);
  141. if (extraJson != null) {
  142. for (String key : extraJson.keys()) {
  143. payload.put(key, extraJson.get(key));
  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()
  228. || !(hasActiveRequest() || getServerRpcQueue()
  229. .isFlushPending())) {
  230. getLoadingIndicator().hide();
  231. // If on Liferay and session expiration management is in
  232. // use, extend session duration on each request.
  233. // Doing it here rather than before the request to improve
  234. // responsiveness.
  235. // Postponed until the end of the next request if other
  236. // requests still pending.
  237. extendLiferaySession();
  238. }
  239. }
  240. });
  241. connection.fireEvent(new ResponseHandlingEndedEvent(connection));
  242. }
  243. /**
  244. * Runs possibly registered client side post request hooks. This is expected
  245. * to be run after each uidl request made by Vaadin application.
  246. *
  247. * @param appId
  248. */
  249. public static native void runPostRequestHooks(String appId)
  250. /*-{
  251. if ($wnd.vaadin.postRequestHooks) {
  252. for ( var hook in $wnd.vaadin.postRequestHooks) {
  253. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  254. try {
  255. $wnd.vaadin.postRequestHooks[hook](appId);
  256. } catch (e) {
  257. }
  258. }
  259. }
  260. }
  261. }-*/;
  262. /**
  263. * If on Liferay and logged in, ask the client side session management
  264. * JavaScript to extend the session duration.
  265. *
  266. * Otherwise, Liferay client side JavaScript will explicitly expire the
  267. * session even though the server side considers the session to be active.
  268. * See ticket #8305 for more information.
  269. */
  270. public static native void extendLiferaySession()
  271. /*-{
  272. if ($wnd.Liferay && $wnd.Liferay.Session) {
  273. $wnd.Liferay.Session.extend();
  274. // if the extend banner is visible, hide it
  275. if ($wnd.Liferay.Session.banner) {
  276. $wnd.Liferay.Session.banner.remove();
  277. }
  278. }
  279. }-*/;
  280. /**
  281. * Indicates whether or not there are currently active UIDL requests. Used
  282. * internally to sequence requests properly, seldom needed in Widgets.
  283. *
  284. * @return true if there are active requests
  285. */
  286. public boolean hasActiveRequest() {
  287. return hasActiveRequest;
  288. }
  289. /**
  290. * Returns a human readable string representation of the method used to
  291. * communicate with the server.
  292. *
  293. * @return A string representation of the current transport type
  294. */
  295. public String getCommunicationMethodName() {
  296. String clientToServer = "XHR";
  297. String serverToClient = "-";
  298. if (push != null) {
  299. serverToClient = push.getTransportType();
  300. if (push.isBidirectional()) {
  301. clientToServer = serverToClient;
  302. }
  303. }
  304. return "Client to server: " + clientToServer + ", "
  305. + "server to client: " + serverToClient;
  306. }
  307. private ConnectionStateHandler getConnectionStateHandler() {
  308. return connection.getConnectionStateHandler();
  309. }
  310. private MessageHandler getMessageHandler() {
  311. return connection.getMessageHandler();
  312. }
  313. private VLoadingIndicator getLoadingIndicator() {
  314. return connection.getLoadingIndicator();
  315. }
  316. /**
  317. * Resynchronize the client side, i.e. reload all component hierarchy and
  318. * state from the server
  319. */
  320. public void resynchronize() {
  321. getLogger().info("Resynchronizing from server");
  322. JsonObject resyncParam = Json.createObject();
  323. resyncParam.put(ApplicationConstants.RESYNCHRONIZE_ID, true);
  324. send(Json.createArray(), resyncParam);
  325. }
  326. /**
  327. * Used internally to update what the server expects
  328. *
  329. * @param clientToServerMessageId
  330. * the new client id to set
  331. * @param force
  332. * true if the id must be updated, false otherwise
  333. */
  334. public void setClientToServerMessageId(int nextExpectedId, boolean force) {
  335. if (nextExpectedId == clientToServerMessageId) {
  336. // No op as everything matches they way it should
  337. return;
  338. }
  339. if (force) {
  340. getLogger().info(
  341. "Forced update of clientId to " + clientToServerMessageId);
  342. clientToServerMessageId = nextExpectedId;
  343. return;
  344. }
  345. if (nextExpectedId > clientToServerMessageId) {
  346. if (clientToServerMessageId == 0) {
  347. // We have never sent a message to the server, so likely the
  348. // server knows better (typical case is that we refreshed a
  349. // @PreserveOnRefresh UI)
  350. getLogger().info(
  351. "Updating client-to-server id to " + nextExpectedId
  352. + " based on server");
  353. } else {
  354. getLogger().warning(
  355. "Server expects next client-to-server id to be "
  356. + nextExpectedId + " but we were going to use "
  357. + clientToServerMessageId + ". Will use "
  358. + nextExpectedId + ".");
  359. }
  360. clientToServerMessageId = nextExpectedId;
  361. } else {
  362. // Server has not yet seen all our messages
  363. // Do nothing as they will arrive eventually
  364. }
  365. }
  366. }