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.

XhrConnection.java 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.http.client.Request;
  19. import com.google.gwt.http.client.RequestBuilder;
  20. import com.google.gwt.http.client.RequestCallback;
  21. import com.google.gwt.http.client.RequestException;
  22. import com.google.gwt.http.client.Response;
  23. import com.google.gwt.user.client.Timer;
  24. import com.google.gwt.user.client.Window;
  25. import com.vaadin.client.ApplicationConnection;
  26. import com.vaadin.client.ApplicationConnection.CommunicationHandler;
  27. import com.vaadin.client.ApplicationConnection.RequestStartingEvent;
  28. import com.vaadin.client.ApplicationConnection.ResponseHandlingEndedEvent;
  29. import com.vaadin.client.ApplicationConnection.ResponseHandlingStartedEvent;
  30. import com.vaadin.client.BrowserInfo;
  31. import com.vaadin.client.Profiler;
  32. import com.vaadin.client.Util;
  33. import com.vaadin.client.ValueMap;
  34. import com.vaadin.shared.ApplicationConstants;
  35. import com.vaadin.shared.JsonConstants;
  36. import com.vaadin.shared.ui.ui.UIConstants;
  37. import com.vaadin.shared.util.SharedUtil;
  38. import elemental.json.JsonObject;
  39. /**
  40. * Provides a connection to the /UIDL url on the server and knows how to send
  41. * messages to that end point.
  42. *
  43. * @since 7.6
  44. * @author Vaadin Ltd
  45. */
  46. public class XhrConnection {
  47. private ApplicationConnection connection;
  48. /**
  49. * Webkit will ignore outgoing requests while waiting for a response to a
  50. * navigation event (indicated by a beforeunload event). When this happens,
  51. * we should keep trying to send the request every now and then until there
  52. * is a response or until it throws an exception saying that it is already
  53. * being sent.
  54. */
  55. private boolean webkitMaybeIgnoringRequests = false;
  56. public XhrConnection() {
  57. Window.addWindowClosingHandler(
  58. event -> webkitMaybeIgnoringRequests = true);
  59. }
  60. /**
  61. * Sets the application connection this instance is connected to. Called
  62. * internally by the framework.
  63. *
  64. * @param connection
  65. * the application connection this instance is connected to
  66. */
  67. public void setConnection(ApplicationConnection connection) {
  68. this.connection = connection;
  69. connection.addHandler(ResponseHandlingEndedEvent.TYPE,
  70. new CommunicationHandler() {
  71. @Override
  72. public void onRequestStarting(RequestStartingEvent e) {
  73. }
  74. @Override
  75. public void onResponseHandlingStarted(
  76. ResponseHandlingStartedEvent e) {
  77. }
  78. @Override
  79. public void onResponseHandlingEnded(
  80. ResponseHandlingEndedEvent e) {
  81. webkitMaybeIgnoringRequests = false;
  82. }
  83. });
  84. }
  85. private static Logger getLogger() {
  86. return Logger.getLogger(XhrConnection.class.getName());
  87. }
  88. protected XhrResponseHandler createResponseHandler() {
  89. return new XhrResponseHandler();
  90. }
  91. public class XhrResponseHandler implements RequestCallback {
  92. private JsonObject payload;
  93. private double requestStartTime;
  94. public XhrResponseHandler() {
  95. }
  96. /**
  97. * Sets the payload which was sent to the server.
  98. *
  99. * @param payload
  100. * the payload which was sent to the server
  101. */
  102. public void setPayload(JsonObject payload) {
  103. this.payload = payload;
  104. }
  105. @Override
  106. public void onError(Request request, Throwable exception) {
  107. getConnectionStateHandler().xhrException(
  108. new XhrConnectionError(request, payload, exception));
  109. }
  110. @Override
  111. public void onResponseReceived(Request request, Response response) {
  112. int statusCode = response.getStatusCode();
  113. if (statusCode != 200) {
  114. // There was a problem
  115. XhrConnectionError problemEvent = new XhrConnectionError(
  116. request, payload, response);
  117. getConnectionStateHandler().xhrInvalidStatusCode(problemEvent);
  118. return;
  119. }
  120. getLogger().info("Server visit took " + Util.round(
  121. Profiler.getRelativeTimeMillis() - requestStartTime, 3)
  122. + "ms");
  123. // for(;;);["+ realJson +"]"
  124. String responseText = response.getText();
  125. ValueMap json = MessageHandler.parseWrappedJson(responseText);
  126. if (json == null) {
  127. // Invalid string (not wrapped as expected or can't parse)
  128. getConnectionStateHandler().xhrInvalidContent(
  129. new XhrConnectionError(request, payload, response));
  130. return;
  131. }
  132. getConnectionStateHandler().xhrOk();
  133. getLogger().info("Received xhr message: " + responseText);
  134. getMessageHandler().handleMessage(json);
  135. }
  136. /**
  137. * Sets the relative time (see {@link Profiler#getRelativeTimeMillis()})
  138. * when the request was sent.
  139. *
  140. * @param requestStartTime
  141. * the relative time when the request was sent
  142. */
  143. private void setRequestStartTime(double requestStartTime) {
  144. this.requestStartTime = requestStartTime;
  145. }
  146. };
  147. /**
  148. * Sends an asynchronous UIDL request to the server using the given URI.
  149. *
  150. * @param payload
  151. * The URI to use for the request. May includes GET parameters
  152. * @throws RequestException
  153. * if the request could not be sent
  154. */
  155. public void send(JsonObject payload) {
  156. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, getUri());
  157. // TODO enable timeout
  158. // rb.setTimeoutMillis(timeoutMillis);
  159. // TODO this should be configurable
  160. rb.setHeader("Content-Type", JsonConstants.JSON_CONTENT_TYPE);
  161. rb.setRequestData(payload.toJson());
  162. XhrResponseHandler responseHandler = createResponseHandler();
  163. responseHandler.setPayload(payload);
  164. responseHandler.setRequestStartTime(Profiler.getRelativeTimeMillis());
  165. rb.setCallback(responseHandler);
  166. getLogger().info("Sending xhr message to server: " + payload.toJson());
  167. try {
  168. final Request request = rb.send();
  169. if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
  170. final int retryTimeout = 250;
  171. new Timer() {
  172. @Override
  173. public void run() {
  174. // Use native js to access private field in Request
  175. if (resendRequest(request)
  176. && webkitMaybeIgnoringRequests) {
  177. // Schedule retry if still needed
  178. schedule(retryTimeout);
  179. }
  180. }
  181. }.schedule(retryTimeout);
  182. }
  183. } catch (RequestException e) {
  184. getConnectionStateHandler()
  185. .xhrException(new XhrConnectionError(null, payload, e));
  186. }
  187. }
  188. /**
  189. * Retrieves the URI to use when sending RPCs to the server.
  190. *
  191. * @return The URI to use for server messages.
  192. */
  193. protected String getUri() {
  194. String uri = connection
  195. .translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  196. + ApplicationConstants.UIDL_PATH + '/');
  197. uri = SharedUtil.addGetParameters(uri, UIConstants.UI_ID_PARAMETER + "="
  198. + connection.getConfiguration().getUIId());
  199. return uri;
  200. }
  201. private ConnectionStateHandler getConnectionStateHandler() {
  202. return connection.getConnectionStateHandler();
  203. }
  204. private MessageHandler getMessageHandler() {
  205. return connection.getMessageHandler();
  206. }
  207. private static native boolean resendRequest(Request request)
  208. /*-{
  209. var xhr = request.@com.google.gwt.http.client.Request::xmlHttpRequest
  210. if (xhr == null) {
  211. // This might be called even though the request has completed,
  212. // if the webkitMaybeIgnoringRequests has been set to true on beforeunload
  213. // but unload was cancelled after that. It will then stay on until the following
  214. // request and if that request completes before we get here (<250mS), we will
  215. // hit this case.
  216. return false;
  217. }
  218. if (xhr.readyState != 1) {
  219. // Progressed to some other readyState -> no longer blocked
  220. return false;
  221. }
  222. try {
  223. xhr.send();
  224. return true;
  225. } catch (e) {
  226. // send throws exception if it is running for real
  227. return false;
  228. }
  229. }-*/;
  230. }