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.

ServerCommunicationHandler.java 13KB

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