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

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