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.

ServerRpcQueue.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.Collection;
  18. import java.util.Iterator;
  19. import java.util.LinkedHashMap;
  20. import java.util.logging.Logger;
  21. import com.google.gwt.core.client.Scheduler;
  22. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  23. import com.vaadin.client.ApplicationConnection;
  24. import com.vaadin.client.ConnectorMap;
  25. import com.vaadin.client.metadata.Method;
  26. import com.vaadin.client.metadata.NoDataException;
  27. import com.vaadin.client.metadata.Type;
  28. import com.vaadin.client.metadata.TypeDataStore;
  29. import com.vaadin.shared.ApplicationConstants;
  30. import com.vaadin.shared.communication.MethodInvocation;
  31. import elemental.json.Json;
  32. import elemental.json.JsonArray;
  33. import elemental.json.JsonValue;
  34. /**
  35. * Manages the queue of server invocations (RPC) which are waiting to be sent to
  36. * the server.
  37. *
  38. * @since
  39. * @author Vaadin Ltd
  40. */
  41. public class ServerRpcQueue {
  42. /**
  43. * The pending method invocations that will be send to the server by
  44. * {@link #sendPendingCommand}. The key is defined differently based on
  45. * whether the method invocation is enqueued with lastonly. With lastonly
  46. * enabled, the method signature ( {@link MethodInvocation#getLastOnlyTag()}
  47. * ) is used as the key to make enable removing a previously enqueued
  48. * invocation. Without lastonly, an incremental id based on
  49. * {@link #lastInvocationTag} is used to get unique values.
  50. */
  51. private LinkedHashMap<String, MethodInvocation> pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
  52. private int lastInvocationTag = 0;
  53. protected ApplicationConnection connection;
  54. private boolean flushPending = false;
  55. private boolean flushScheduled = false;
  56. public ServerRpcQueue() {
  57. }
  58. /**
  59. * Sets the application connection this queue is connected to
  60. *
  61. * @param connection
  62. * the application connection this queue is connected to
  63. */
  64. public void setConnection(ApplicationConnection connection) {
  65. this.connection = connection;
  66. }
  67. public static Logger getLogger() {
  68. return Logger.getLogger(ServerRpcQueue.class.getName());
  69. }
  70. /**
  71. * Removes any pending invocation of the given method from the queue
  72. *
  73. * @param invocation
  74. * The invocation to remove
  75. */
  76. public void removeMatching(MethodInvocation invocation) {
  77. Iterator<MethodInvocation> iter = pendingInvocations.values()
  78. .iterator();
  79. while (iter.hasNext()) {
  80. MethodInvocation mi = iter.next();
  81. if (mi.equals(invocation)) {
  82. iter.remove();
  83. }
  84. }
  85. }
  86. /**
  87. * Adds an explicit RPC method invocation to the send queue.
  88. *
  89. * @param invocation
  90. * RPC method invocation
  91. * @param delayed
  92. * <code>false</code> to trigger sending within a short time
  93. * window (possibly combining subsequent calls to a single
  94. * request), <code>true</code> to let the framework delay sending
  95. * of RPC calls and variable changes until the next non-delayed
  96. * change
  97. * @param lastOnly
  98. * <code>true</code> to remove all previously delayed invocations
  99. * of the same method that were also enqueued with lastonly set
  100. * to <code>true</code>. <code>false</code> to add invocation to
  101. * the end of the queue without touching previously enqueued
  102. * invocations.
  103. */
  104. public void add(MethodInvocation invocation, boolean lastOnly) {
  105. if (!connection.isApplicationRunning()) {
  106. getLogger()
  107. .warning(
  108. "Trying to invoke method on not yet started or stopped application");
  109. return;
  110. }
  111. String tag;
  112. if (lastOnly) {
  113. tag = invocation.getLastOnlyTag();
  114. assert !tag.matches("\\d+") : "getLastOnlyTag value must have at least one non-digit character";
  115. pendingInvocations.remove(tag);
  116. } else {
  117. tag = Integer.toString(lastInvocationTag++);
  118. }
  119. pendingInvocations.put(tag, invocation);
  120. }
  121. /**
  122. * Returns a collection of all queued method invocations
  123. *
  124. * @return a collection of all queued method invocations
  125. */
  126. public Collection<MethodInvocation> getAll() {
  127. return pendingInvocations.values();
  128. }
  129. /**
  130. * Clears the queue
  131. */
  132. public void clear() {
  133. pendingInvocations.clear();
  134. // Keep tag string short
  135. lastInvocationTag = 0;
  136. flushPending = false;
  137. }
  138. /**
  139. * Returns the current size of the queue
  140. *
  141. * @return the number of invocations in the queue
  142. */
  143. public int size() {
  144. return pendingInvocations.size();
  145. }
  146. /**
  147. * Returns the server RPC queue for the given application
  148. *
  149. * @param connection
  150. * the application connection which owns the queue
  151. * @return the server rpc queue for the given application
  152. */
  153. public static ServerRpcQueue get(ApplicationConnection connection) {
  154. return connection.getServerRpcQueue();
  155. }
  156. /**
  157. * Checks if the queue is empty
  158. *
  159. * @return true if the queue is empty, false otherwise
  160. */
  161. public boolean isEmpty() {
  162. return size() == 0;
  163. }
  164. /**
  165. * Triggers a send of server RPC and legacy variable changes to the server.
  166. */
  167. public void flush() {
  168. if (flushScheduled) {
  169. return;
  170. }
  171. flushPending = true;
  172. flushScheduled = true;
  173. Scheduler.get().scheduleFinally(scheduledFlushCommand);
  174. }
  175. private final ScheduledCommand scheduledFlushCommand = new ScheduledCommand() {
  176. @Override
  177. public void execute() {
  178. flushScheduled = false;
  179. if (!isFlushPending()) {
  180. // Somebody else cleared the queue before we had the chance
  181. return;
  182. }
  183. connection.getServerCommunicationHandler()
  184. .doSendPendingVariableChanges();
  185. }
  186. };
  187. /**
  188. * Checks if a flush operation is pending
  189. *
  190. * @return true if a flush is pending, false otherwise
  191. */
  192. public boolean isFlushPending() {
  193. return flushPending;
  194. }
  195. /**
  196. * Checks if a loading indicator should be shown when the RPCs have been
  197. * sent to the server and we are waiting for a response
  198. *
  199. * @return true if a loading indicator should be shown, false otherwise
  200. */
  201. public boolean showLoadingIndicator() {
  202. for (MethodInvocation invocation : getAll()) {
  203. if (isLegacyVariableChange(invocation)) {
  204. // Always show loading indicator for legacy requests
  205. return true;
  206. } else if (!isJavascriptRpc(invocation)) {
  207. Type type = new Type(invocation.getInterfaceName(), null);
  208. Method method = type.getMethod(invocation.getMethodName());
  209. if (!TypeDataStore.isNoLoadingIndicator(method)) {
  210. return true;
  211. }
  212. }
  213. }
  214. return false;
  215. }
  216. /**
  217. * Returns the current invocations as JSON
  218. *
  219. * @return the current invocations in a JSON format ready to be sent to the
  220. * server
  221. */
  222. public JsonArray toJson() {
  223. JsonArray json = Json.createArray();
  224. if (isEmpty()) {
  225. return json;
  226. }
  227. for (MethodInvocation invocation : getAll()) {
  228. String connectorId = invocation.getConnectorId();
  229. if (!connectorExists(connectorId)) {
  230. getLogger().info(
  231. "Ignoring RPC for removed connector: " + connectorId
  232. + ": " + invocation.toString());
  233. continue;
  234. }
  235. JsonArray invocationJson = Json.createArray();
  236. invocationJson.set(0, connectorId);
  237. invocationJson.set(1, invocation.getInterfaceName());
  238. invocationJson.set(2, invocation.getMethodName());
  239. JsonArray paramJson = Json.createArray();
  240. Type[] parameterTypes = null;
  241. if (!isLegacyVariableChange(invocation)
  242. && !isJavascriptRpc(invocation)) {
  243. try {
  244. Type type = new Type(invocation.getInterfaceName(), null);
  245. Method method = type.getMethod(invocation.getMethodName());
  246. parameterTypes = method.getParameterTypes();
  247. } catch (NoDataException e) {
  248. throw new RuntimeException("No type data for "
  249. + invocation.toString(), e);
  250. }
  251. }
  252. for (int i = 0; i < invocation.getParameters().length; ++i) {
  253. // TODO non-static encoder?
  254. Type type = null;
  255. if (parameterTypes != null) {
  256. type = parameterTypes[i];
  257. }
  258. Object value = invocation.getParameters()[i];
  259. JsonValue jsonValue = JsonEncoder.encode(value, type,
  260. connection);
  261. paramJson.set(i, jsonValue);
  262. }
  263. invocationJson.set(3, paramJson);
  264. json.set(json.length(), invocationJson);
  265. }
  266. return json;
  267. }
  268. /**
  269. * Checks if the connector with the given id is still ok to use (has not
  270. * been removed)
  271. *
  272. * @param connectorId
  273. * the connector id to check
  274. * @return true if the connector exists, false otherwise
  275. */
  276. private boolean connectorExists(String connectorId) {
  277. ConnectorMap connectorMap = ConnectorMap.get(connection);
  278. return connectorMap.hasConnector(connectorId)
  279. || connectorMap.isDragAndDropPaintable(connectorId);
  280. }
  281. /**
  282. * Checks if the given method invocation originates from Javascript
  283. *
  284. * @param invocation
  285. * the invocation to check
  286. * @return true if the method invocation originates from javascript, false
  287. * otherwise
  288. */
  289. public static boolean isJavascriptRpc(MethodInvocation invocation) {
  290. return invocation instanceof JavaScriptMethodInvocation;
  291. }
  292. /**
  293. * Checks if the given method invocation represents a Vaadin 6 variable
  294. * change
  295. *
  296. * @param invocation
  297. * the invocation to check
  298. * @return true if the method invocation is a legacy variable change, false
  299. * otherwise
  300. */
  301. public static boolean isLegacyVariableChange(MethodInvocation invocation) {
  302. return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
  303. .getInterfaceName())
  304. && ApplicationConstants.UPDATE_VARIABLE_METHOD
  305. .equals(invocation.getMethodName());
  306. }
  307. }