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.7KB

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