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

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