您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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.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(new ClosingHandler() {
  58. @Override
  59. public void onWindowClosing(ClosingEvent event) {
  60. webkitMaybeIgnoringRequests = true;
  61. }
  62. });
  63. }
  64. /**
  65. * Sets the application connection this queue is connected to
  66. *
  67. * @param connection
  68. * the application connection this queue is connected to
  69. */
  70. public void setConnection(ApplicationConnection connection) {
  71. this.connection = connection;
  72. connection.addHandler(ResponseHandlingEndedEvent.TYPE,
  73. new CommunicationHandler() {
  74. @Override
  75. public void onRequestStarting(RequestStartingEvent e) {
  76. }
  77. @Override
  78. public void onResponseHandlingStarted(
  79. ResponseHandlingStartedEvent e) {
  80. }
  81. @Override
  82. public void onResponseHandlingEnded(
  83. ResponseHandlingEndedEvent e) {
  84. webkitMaybeIgnoringRequests = false;
  85. }
  86. });
  87. }
  88. public static Logger getLogger() {
  89. return Logger.getLogger(XhrConnection.class.getName());
  90. }
  91. protected XhrResponseHandler createResponseHandler() {
  92. return new XhrResponseHandler();
  93. }
  94. public class XhrResponseHandler implements RequestCallback {
  95. private JsonObject payload;
  96. private Date requestStartTime;
  97. public XhrResponseHandler() {
  98. }
  99. /**
  100. * Sets the payload which was sent to the server
  101. *
  102. * @param payload
  103. * the payload which was sent to the server
  104. */
  105. public void setPayload(JsonObject payload) {
  106. this.payload = payload;
  107. }
  108. @Override
  109. public void onError(Request request, Throwable exception) {
  110. getCommunicationProblemHandler().xhrException(
  111. new CommunicationProblemEvent(request, payload, exception));
  112. }
  113. private ServerCommunicationHandler getServerCommunicationHandler() {
  114. return connection.getServerCommunicationHandler();
  115. }
  116. @Override
  117. public void onResponseReceived(Request request, Response response) {
  118. int statusCode = response.getStatusCode();
  119. if (statusCode != 200) {
  120. // There was a problem
  121. CommunicationProblemEvent problemEvent = new CommunicationProblemEvent(
  122. request, payload, response);
  123. getCommunicationProblemHandler().xhrInvalidStatusCode(
  124. problemEvent);
  125. return;
  126. }
  127. getLogger().info(
  128. "Server visit took "
  129. + String.valueOf((new Date()).getTime()
  130. - requestStartTime.getTime()) + "ms");
  131. String contentType = response.getHeader("Content-Type");
  132. if (contentType == null
  133. || !contentType.startsWith("application/json")) {
  134. getCommunicationProblemHandler().xhrInvalidContent(
  135. new CommunicationProblemEvent(request, payload,
  136. response));
  137. return;
  138. }
  139. // for(;;);["+ realJson +"]"
  140. String responseText = response.getText();
  141. final String jsonText = ServerCommunicationHandler
  142. .stripJSONWrapping(responseText);
  143. if (jsonText == null) {
  144. // Invalid string (not wrapped as expected)
  145. getCommunicationProblemHandler().xhrInvalidContent(
  146. new CommunicationProblemEvent(request, payload,
  147. response));
  148. return;
  149. }
  150. getCommunicationProblemHandler().xhrOk();
  151. getLogger().info("Received xhr message: " + jsonText);
  152. getServerMessageHandler().handleMessage(jsonText);
  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. }