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

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