Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

XhrConnection.java 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 instance is connected to. Called
  67. * internally by the framework.
  68. *
  69. * @param connection
  70. * the application connection this instance is connected to
  71. */
  72. public void setConnection(ApplicationConnection connection) {
  73. this.connection = connection;
  74. connection.addHandler(ResponseHandlingEndedEvent.TYPE,
  75. new CommunicationHandler() {
  76. @Override
  77. public void onRequestStarting(RequestStartingEvent e) {
  78. }
  79. @Override
  80. public void onResponseHandlingStarted(
  81. ResponseHandlingStartedEvent e) {
  82. }
  83. @Override
  84. public void onResponseHandlingEnded(
  85. ResponseHandlingEndedEvent e) {
  86. webkitMaybeIgnoringRequests = false;
  87. }
  88. });
  89. }
  90. private static Logger getLogger() {
  91. return Logger.getLogger(XhrConnection.class.getName());
  92. }
  93. protected XhrResponseHandler createResponseHandler() {
  94. return new XhrResponseHandler();
  95. }
  96. public class XhrResponseHandler implements RequestCallback {
  97. private JsonObject payload;
  98. private Date requestStartTime;
  99. public XhrResponseHandler() {
  100. }
  101. /**
  102. * Sets the payload which was sent to the server
  103. *
  104. * @param payload
  105. * the payload which was sent to the server
  106. */
  107. public void setPayload(JsonObject payload) {
  108. this.payload = payload;
  109. }
  110. @Override
  111. public void onError(Request request, Throwable exception) {
  112. getConnectionStateHandler().xhrException(
  113. new XhrConnectionError(request, payload, exception));
  114. }
  115. @Override
  116. public void onResponseReceived(Request request, Response response) {
  117. int statusCode = response.getStatusCode();
  118. if (statusCode != 200) {
  119. // There was a problem
  120. XhrConnectionError problemEvent = new XhrConnectionError(
  121. request, payload, response);
  122. getConnectionStateHandler().xhrInvalidStatusCode(problemEvent);
  123. return;
  124. }
  125. getLogger().info(
  126. "Server visit took "
  127. + String.valueOf((new Date()).getTime()
  128. - requestStartTime.getTime()) + "ms");
  129. String contentType = response.getHeader("Content-Type");
  130. if (contentType == null
  131. || !contentType.startsWith("application/json")) {
  132. getConnectionStateHandler().xhrInvalidContent(
  133. new XhrConnectionError(request, payload, response));
  134. return;
  135. }
  136. // for(;;);["+ realJson +"]"
  137. String responseText = response.getText();
  138. ValueMap json = MessageHandler.parseWrappedJson(responseText);
  139. if (json == null) {
  140. // Invalid string (not wrapped as expected or can't parse)
  141. getConnectionStateHandler().xhrInvalidContent(
  142. new XhrConnectionError(request, payload, response));
  143. return;
  144. }
  145. getConnectionStateHandler().xhrOk();
  146. getLogger().info("Received xhr message: " + responseText);
  147. getMessageHandler().handleMessage(json);
  148. }
  149. /**
  150. * Sets the time when the request was sent
  151. *
  152. * @param requestStartTime
  153. * the time when the request was sent
  154. */
  155. public void setRequestStartTime(Date requestStartTime) {
  156. this.requestStartTime = requestStartTime;
  157. }
  158. };
  159. /**
  160. * Sends an asynchronous UIDL request to the server using the given URI.
  161. *
  162. * @param payload
  163. * The URI to use for the request. May includes GET parameters
  164. * @throws RequestException
  165. * if the request could not be sent
  166. */
  167. public void send(JsonObject payload) {
  168. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, getUri());
  169. // TODO enable timeout
  170. // rb.setTimeoutMillis(timeoutMillis);
  171. // TODO this should be configurable
  172. rb.setHeader("Content-Type", JsonConstants.JSON_CONTENT_TYPE);
  173. rb.setRequestData(payload.toJson());
  174. XhrResponseHandler responseHandler = createResponseHandler();
  175. responseHandler.setPayload(payload);
  176. responseHandler.setRequestStartTime(new Date());
  177. rb.setCallback(responseHandler);
  178. getLogger().info("Sending xhr message to server: " + payload.toJson());
  179. try {
  180. final Request request = rb.send();
  181. if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
  182. final int retryTimeout = 250;
  183. new Timer() {
  184. @Override
  185. public void run() {
  186. // Use native js to access private field in Request
  187. if (resendRequest(request)
  188. && webkitMaybeIgnoringRequests) {
  189. // Schedule retry if still needed
  190. schedule(retryTimeout);
  191. }
  192. }
  193. }.schedule(retryTimeout);
  194. }
  195. } catch (RequestException e) {
  196. getConnectionStateHandler().xhrException(
  197. new XhrConnectionError(null, payload, e));
  198. }
  199. }
  200. /**
  201. * Retrieves the URI to use when sending RPCs to the server
  202. *
  203. * @return The URI to use for server messages.
  204. */
  205. protected String getUri() {
  206. String uri = connection
  207. .translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  208. + ApplicationConstants.UIDL_PATH + '/');
  209. uri = SharedUtil.addGetParameters(uri, UIConstants.UI_ID_PARAMETER
  210. + "=" + connection.getConfiguration().getUIId());
  211. return uri;
  212. }
  213. private ConnectionStateHandler getConnectionStateHandler() {
  214. return connection.getConnectionStateHandler();
  215. }
  216. private MessageHandler getMessageHandler() {
  217. return connection.getMessageHandler();
  218. }
  219. private static native boolean resendRequest(Request request)
  220. /*-{
  221. var xhr = request.@com.google.gwt.http.client.Request::xmlHttpRequest
  222. if (xhr.readyState != 1) {
  223. // Progressed to some other readyState -> no longer blocked
  224. return false;
  225. }
  226. try {
  227. xhr.send();
  228. return true;
  229. } catch (e) {
  230. // send throws exception if it is running for real
  231. return false;
  232. }
  233. }-*/;
  234. }