Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ServerRpcQueue.java 11KB

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