Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  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.ArrayList;
  18. import java.util.Collections;
  19. import java.util.Date;
  20. import java.util.HashSet;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Set;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import com.google.gwt.core.client.Duration;
  27. import com.google.gwt.core.client.GWT;
  28. import com.google.gwt.core.client.JavaScriptObject;
  29. import com.google.gwt.core.client.JsArray;
  30. import com.google.gwt.core.client.JsArrayString;
  31. import com.google.gwt.core.client.Scheduler;
  32. import com.google.gwt.user.client.Command;
  33. import com.google.gwt.user.client.Timer;
  34. import com.google.gwt.user.client.ui.Widget;
  35. import com.vaadin.client.ApplicationConfiguration;
  36. import com.vaadin.client.ApplicationConnection;
  37. import com.vaadin.client.ApplicationConnection.ApplicationState;
  38. import com.vaadin.client.ApplicationConnection.MultiStepDuration;
  39. import com.vaadin.client.ApplicationConnection.ResponseHandlingStartedEvent;
  40. import com.vaadin.client.ComponentConnector;
  41. import com.vaadin.client.ConnectorHierarchyChangeEvent;
  42. import com.vaadin.client.ConnectorMap;
  43. import com.vaadin.client.FastStringSet;
  44. import com.vaadin.client.HasComponentsConnector;
  45. import com.vaadin.client.JsArrayObject;
  46. import com.vaadin.client.LayoutManager;
  47. import com.vaadin.client.LocaleService;
  48. import com.vaadin.client.Paintable;
  49. import com.vaadin.client.Profiler;
  50. import com.vaadin.client.ServerConnector;
  51. import com.vaadin.client.UIDL;
  52. import com.vaadin.client.Util;
  53. import com.vaadin.client.VCaption;
  54. import com.vaadin.client.VConsole;
  55. import com.vaadin.client.ValueMap;
  56. import com.vaadin.client.WidgetUtil;
  57. import com.vaadin.client.extensions.AbstractExtensionConnector;
  58. import com.vaadin.client.metadata.ConnectorBundleLoader;
  59. import com.vaadin.client.metadata.NoDataException;
  60. import com.vaadin.client.metadata.Property;
  61. import com.vaadin.client.metadata.Type;
  62. import com.vaadin.client.metadata.TypeData;
  63. import com.vaadin.client.ui.AbstractConnector;
  64. import com.vaadin.client.ui.VNotification;
  65. import com.vaadin.client.ui.dd.VDragAndDropManager;
  66. import com.vaadin.client.ui.ui.UIConnector;
  67. import com.vaadin.client.ui.window.WindowConnector;
  68. import com.vaadin.shared.ApplicationConstants;
  69. import com.vaadin.shared.communication.MethodInvocation;
  70. import com.vaadin.shared.communication.SharedState;
  71. import elemental.json.Json;
  72. import elemental.json.JsonArray;
  73. import elemental.json.JsonObject;
  74. /**
  75. * A MessageHandler is responsible for handling all incoming messages (JSON)
  76. * from the server (state changes, RPCs and other updates) and ensuring that the
  77. * connectors are updated accordingly.
  78. *
  79. * @since 7.6
  80. * @author Vaadin Ltd
  81. */
  82. public class MessageHandler {
  83. public static final String JSON_COMMUNICATION_PREFIX = "for(;;);[";
  84. public static final String JSON_COMMUNICATION_SUFFIX = "]";
  85. /**
  86. * Helper used to return two values when updating the connector hierarchy.
  87. */
  88. private static class ConnectorHierarchyUpdateResult {
  89. /**
  90. * Needed at a later point when the created events are fired
  91. */
  92. private JsArrayObject<ConnectorHierarchyChangeEvent> events = JavaScriptObject
  93. .createArray().cast();
  94. /**
  95. * Needed to know where captions might need to get updated
  96. */
  97. private FastStringSet parentChangedIds = FastStringSet.create();
  98. /**
  99. * Connectors for which the parent has been set to null
  100. */
  101. private FastStringSet detachedConnectorIds = FastStringSet.create();
  102. }
  103. /** The max timeout that response handling may be suspended */
  104. private static final int MAX_SUSPENDED_TIMEOUT = 5000;
  105. /**
  106. * The value of an undefined sync id.
  107. * <p>
  108. * This must be <code>-1</code>, because of the contract in
  109. * {@link #getLastSeenServerSyncId()}
  110. */
  111. private static final int UNDEFINED_SYNC_ID = -1;
  112. /**
  113. * If responseHandlingLocks contains any objects, response handling is
  114. * suspended until the collection is empty or a timeout has occurred.
  115. */
  116. private Set<Object> responseHandlingLocks = new HashSet<>();
  117. /**
  118. * Contains all UIDL messages received while response handling is suspended
  119. */
  120. private List<PendingUIDLMessage> pendingUIDLMessages = new ArrayList<>();
  121. // will hold the CSRF token once received
  122. private String csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE;
  123. // holds the push identifier once received
  124. private String pushId = null;
  125. /** Timer for automatic redirect to SessionExpiredURL */
  126. private Timer redirectTimer;
  127. /** redirectTimer scheduling interval in seconds */
  128. private int sessionExpirationInterval;
  129. /**
  130. * Holds the time spent rendering the last request.
  131. */
  132. protected int lastProcessingTime;
  133. /**
  134. * Holds the total time spent rendering requests during the lifetime of the
  135. * session.
  136. */
  137. protected int totalProcessingTime;
  138. /**
  139. * Holds the time it took to load the page and render the first view. -2
  140. * means that this value has not yet been calculated because the first view
  141. * has not yet been rendered (or that your browser is very fast). -1 means
  142. * that the browser does not support the performance.timing feature used to
  143. * get this measurement.
  144. *
  145. * Note: also used for tracking whether the first UIDL has been handled
  146. */
  147. private int bootstrapTime = 0;
  148. /**
  149. * true if state updates are currently being done
  150. */
  151. private boolean updatingState = false;
  152. /**
  153. * Holds the timing information from the server-side. How much time was
  154. * spent servicing the last request and how much time has been spent
  155. * servicing the session so far. These values are always one request behind,
  156. * since they cannot be measured before the request is finished.
  157. */
  158. private ValueMap serverTimingInfo;
  159. /**
  160. * Holds the last seen response id given by the server.
  161. * <p>
  162. * The server generates a strictly increasing id for each response to each
  163. * request from the client. This ID is then replayed back to the server on
  164. * each request. This helps the server in knowing in what state the client
  165. * is, and compare it to its own state. In short, it helps with concurrent
  166. * changes between the client and server.
  167. * <p>
  168. * Initial value, i.e. no responses received from the server, is
  169. * {@link #UNDEFINED_SYNC_ID} ({@value #UNDEFINED_SYNC_ID}). This happens
  170. * between the bootstrap HTML being loaded and the first UI being rendered;
  171. */
  172. private int lastSeenServerSyncId = UNDEFINED_SYNC_ID;
  173. private ApplicationConnection connection;
  174. /**
  175. * Data structure holding information about pending UIDL messages.
  176. */
  177. private static class PendingUIDLMessage {
  178. private ValueMap json;
  179. public PendingUIDLMessage(ValueMap json) {
  180. this.json = json;
  181. }
  182. public ValueMap getJson() {
  183. return json;
  184. }
  185. }
  186. /**
  187. * Sets the application connection this instance is connected to. Called
  188. * internally by the framework.
  189. *
  190. * @param connection
  191. * the application connection this instance is connected to
  192. */
  193. public void setConnection(ApplicationConnection connection) {
  194. this.connection = connection;
  195. }
  196. private static Logger getLogger() {
  197. return Logger.getLogger(MessageHandler.class.getName());
  198. }
  199. /**
  200. * Handles a received UIDL JSON text, parsing it, and passing it on to the
  201. * appropriate handlers, while logging timing information.
  202. *
  203. * @param json
  204. * The JSON to handle
  205. */
  206. public void handleMessage(final ValueMap json) {
  207. if (json == null) {
  208. throw new IllegalArgumentException(
  209. "The json to handle cannot be null");
  210. }
  211. if (getServerId(json) == -1) {
  212. getLogger().severe("Response didn't contain a server id. "
  213. + "Please verify that the server is up-to-date and that the response data has not been modified in transmission.");
  214. }
  215. if (connection.getApplicationState() == ApplicationState.RUNNING) {
  216. handleJSON(json);
  217. } else if (connection
  218. .getApplicationState() == ApplicationState.INITIALIZING) {
  219. // Application is starting up for the first time
  220. connection.setApplicationRunning(true);
  221. connection.executeWhenCSSLoaded(() -> handleJSON(json));
  222. } else {
  223. getLogger().warning(
  224. "Ignored received message because application has already been stopped");
  225. return;
  226. }
  227. }
  228. protected void handleJSON(final ValueMap json) {
  229. final int serverId = getServerId(json);
  230. if (isResynchronize(json) && !isNextExpectedMessage(serverId)) {
  231. // Resynchronize request. We must remove any old pending
  232. // messages and ensure this is handled next. Otherwise we
  233. // would keep waiting for an older message forever (if this
  234. // is triggered by forceHandleMessage)
  235. getLogger().info("Received resync message with id " + serverId
  236. + " while waiting for " + getExpectedServerId());
  237. lastSeenServerSyncId = serverId - 1;
  238. removeOldPendingMessages();
  239. }
  240. boolean locked = !responseHandlingLocks.isEmpty();
  241. if (locked || !isNextExpectedMessage(serverId)) {
  242. // Cannot or should not handle this message right now, either
  243. // because of locks or because it's an out-of-order message
  244. if (locked) {
  245. // Some component is doing something that can't be interrupted
  246. // (e.g. animation that should be smooth). Enqueue the UIDL
  247. // message for later processing.
  248. getLogger().info("Postponing UIDL handling due to lock...");
  249. } else {
  250. // Unexpected server id
  251. if (serverId <= lastSeenServerSyncId) {
  252. // Why is the server re-sending an old package? Ignore it
  253. getLogger().warning("Received message with server id "
  254. + serverId + " but have already seen "
  255. + lastSeenServerSyncId + ". Ignoring it");
  256. endRequestIfResponse(json);
  257. return;
  258. }
  259. // We are waiting for an earlier message...
  260. getLogger().info("Received message with server id " + serverId
  261. + " but expected " + getExpectedServerId()
  262. + ". Postponing handling until the missing message(s) have been received");
  263. }
  264. pendingUIDLMessages.add(new PendingUIDLMessage(json));
  265. if (!forceHandleMessage.isRunning()) {
  266. forceHandleMessage.schedule(MAX_SUSPENDED_TIMEOUT);
  267. }
  268. return;
  269. }
  270. final Date start = new Date();
  271. /*
  272. * Lock response handling to avoid a situation where something pushed
  273. * from the server gets processed while waiting for e.g. lazily loaded
  274. * connectors that are needed for processing the current message.
  275. */
  276. final Object lock = new Object();
  277. suspendReponseHandling(lock);
  278. getLogger().info("Handling message from server");
  279. connection.fireEvent(new ResponseHandlingStartedEvent(connection));
  280. // Client id must be updated before server id, as server id update can
  281. // cause a resync (which must use the updated id)
  282. if (json.containsKey(ApplicationConstants.CLIENT_TO_SERVER_ID)) {
  283. int serverNextExpected = json
  284. .getInt(ApplicationConstants.CLIENT_TO_SERVER_ID);
  285. getMessageSender().setClientToServerMessageId(serverNextExpected,
  286. isResynchronize(json));
  287. }
  288. if (serverId != -1) {
  289. /*
  290. * Use sync id unless explicitly set as undefined, as is done by
  291. * e.g. critical server-side notifications
  292. */
  293. lastSeenServerSyncId = serverId;
  294. }
  295. // Handle redirect
  296. if (json.containsKey("redirect")) {
  297. String url = json.getValueMap("redirect").getString("url");
  298. getLogger().info("redirecting to " + url);
  299. WidgetUtil.redirect(url);
  300. return;
  301. }
  302. final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
  303. // Get security key
  304. if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
  305. csrfToken = json
  306. .getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
  307. }
  308. // Get push id if present
  309. if (json.containsKey(ApplicationConstants.UIDL_PUSH_ID)) {
  310. pushId = json.getString(ApplicationConstants.UIDL_PUSH_ID);
  311. }
  312. getLogger().info(" * Handling resources from server");
  313. if (json.containsKey("resources")) {
  314. ValueMap resources = json.getValueMap("resources");
  315. JsArrayString keyArray = resources.getKeyArray();
  316. int l = keyArray.length();
  317. for (int i = 0; i < l; i++) {
  318. String key = keyArray.get(i);
  319. connection.setResource(key, resources.getAsString(key));
  320. }
  321. }
  322. handleUIDLDuration
  323. .logDuration(" * Handling resources from server completed", 10);
  324. getLogger().info(" * Handling type inheritance map from server");
  325. if (json.containsKey("typeInheritanceMap")) {
  326. connection.getConfiguration().addComponentInheritanceInfo(
  327. json.getValueMap("typeInheritanceMap"));
  328. }
  329. handleUIDLDuration.logDuration(
  330. " * Handling type inheritance map from server completed", 10);
  331. getLogger().info("Handling type mappings from server");
  332. if (json.containsKey("typeMappings")) {
  333. connection.getConfiguration().addComponentMappings(
  334. json.getValueMap("typeMappings"),
  335. connection.getWidgetSet());
  336. }
  337. getLogger().info("Handling resource dependencies");
  338. connection.getDependencyLoader().loadDependencies(json);
  339. handleUIDLDuration.logDuration(
  340. " * Handling type mappings from server completed", 10);
  341. /*
  342. * Hook for e.g. TestBench to get details about server peformance
  343. */
  344. if (json.containsKey("timings")) {
  345. serverTimingInfo = json.getValueMap("timings");
  346. }
  347. Command c = new Command() {
  348. private boolean onlyNoLayoutUpdates = true;
  349. @Override
  350. public void execute() {
  351. assert serverId == -1 || serverId == lastSeenServerSyncId;
  352. handleUIDLDuration.logDuration(" * Loading widgets completed",
  353. 10);
  354. Profiler.enter("Handling meta information");
  355. ValueMap meta = null;
  356. if (json.containsKey("meta")) {
  357. getLogger().info(" * Handling meta information");
  358. meta = json.getValueMap("meta");
  359. if (meta.containsKey("repaintAll")) {
  360. prepareRepaintAll();
  361. }
  362. if (meta.containsKey("timedRedirect")) {
  363. final ValueMap timedRedirect = meta
  364. .getValueMap("timedRedirect");
  365. if (redirectTimer != null) {
  366. redirectTimer.cancel();
  367. }
  368. redirectTimer = new Timer() {
  369. @Override
  370. public void run() {
  371. WidgetUtil.redirect(
  372. timedRedirect.getString("url"));
  373. }
  374. };
  375. sessionExpirationInterval = timedRedirect
  376. .getInt("interval");
  377. }
  378. }
  379. Profiler.leave("Handling meta information");
  380. if (redirectTimer != null) {
  381. redirectTimer.schedule(1000 * sessionExpirationInterval);
  382. }
  383. updatingState = true;
  384. double processUidlStart = Duration.currentTimeMillis();
  385. // Ensure that all connectors that we are about to update exist
  386. JsArrayString createdConnectorIds = createConnectorsIfNeeded(
  387. json);
  388. // Update states, do not fire events
  389. JsArrayObject<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(
  390. json, createdConnectorIds);
  391. /*
  392. * Doing this here so that locales are available also to the
  393. * connectors which get a state change event before the UI.
  394. */
  395. Profiler.enter("Handling locales");
  396. getLogger().info(" * Handling locales");
  397. // Store locale data
  398. LocaleService.addLocales(getUIConnector()
  399. .getState().localeServiceState.localeData);
  400. Profiler.leave("Handling locales");
  401. // Update hierarchy, do not fire events
  402. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(
  403. json);
  404. // Fire hierarchy change events
  405. sendHierarchyChangeEvents(
  406. connectorHierarchyUpdateResult.events);
  407. updateCaptions(pendingStateChangeEvents,
  408. connectorHierarchyUpdateResult.parentChangedIds);
  409. delegateToWidget(pendingStateChangeEvents);
  410. // Fire state change events.
  411. sendStateChangeEvents(pendingStateChangeEvents);
  412. // Update of legacy (UIDL) style connectors
  413. updateVaadin6StyleConnectors(json);
  414. // Handle any RPC invocations done on the server side
  415. handleRpcInvocations(json);
  416. if (json.containsKey("dd")) {
  417. // response contains data for drag and drop service
  418. VDragAndDropManager.get()
  419. .handleServerResponse(json.getValueMap("dd"));
  420. }
  421. unregisterRemovedConnectors(
  422. connectorHierarchyUpdateResult.detachedConnectorIds);
  423. getLogger().info("handleUIDLMessage: "
  424. + (Duration.currentTimeMillis() - processUidlStart)
  425. + " ms");
  426. updatingState = false;
  427. Profiler.enter("Layout processing");
  428. try {
  429. LayoutManager layoutManager = getLayoutManager();
  430. if (!onlyNoLayoutUpdates) {
  431. layoutManager.setEverythingNeedsMeasure();
  432. }
  433. if (layoutManager.isLayoutNeeded()) {
  434. layoutManager.layoutNow();
  435. }
  436. } catch (final Throwable e) {
  437. getLogger().log(Level.SEVERE, "Error processing layouts",
  438. e);
  439. }
  440. Profiler.leave("Layout processing");
  441. if (ApplicationConfiguration.isDebugMode()) {
  442. Profiler.enter("Dumping state changes to the console");
  443. getLogger().info(" * Dumping state changes to the console");
  444. VConsole.dirUIDL(json, connection);
  445. Profiler.leave("Dumping state changes to the console");
  446. }
  447. if (meta != null) {
  448. Profiler.enter("Error handling");
  449. if (meta.containsKey("appError")) {
  450. ValueMap error = meta.getValueMap("appError");
  451. VNotification.showError(connection,
  452. error.getString("caption"),
  453. error.getString("message"),
  454. error.getString("details"),
  455. error.getString("url"));
  456. connection.setApplicationRunning(false);
  457. }
  458. Profiler.leave("Error handling");
  459. }
  460. // TODO build profiling for widget impl loading time
  461. lastProcessingTime = (int) ((new Date().getTime())
  462. - start.getTime());
  463. totalProcessingTime += lastProcessingTime;
  464. if (bootstrapTime == 0) {
  465. double fetchStart = getFetchStartTime();
  466. if (fetchStart != 0) {
  467. int time = (int) (Duration.currentTimeMillis()
  468. - fetchStart);
  469. getLogger().log(Level.INFO, "First response processed "
  470. + time + " ms after fetchStart");
  471. }
  472. bootstrapTime = calculateBootstrapTime();
  473. if (Profiler.isEnabled() && bootstrapTime != -1) {
  474. Profiler.logBootstrapTimings();
  475. }
  476. }
  477. getLogger().info(" Processing time was "
  478. + String.valueOf(lastProcessingTime) + "ms");
  479. getLogger().info(
  480. "Referenced paintables: " + getConnectorMap().size());
  481. endRequestIfResponse(json);
  482. resumeResponseHandling(lock);
  483. ConnectorBundleLoader.get().ensureDeferredBundleLoaded();
  484. if (Profiler.isEnabled()) {
  485. Scheduler.get().scheduleDeferred(() -> {
  486. Profiler.logTimings();
  487. Profiler.reset();
  488. });
  489. }
  490. }
  491. /**
  492. * Properly clean up any old stuff to ensure everything is properly
  493. * reinitialized.
  494. */
  495. private void prepareRepaintAll() {
  496. String uiConnectorId = getUIConnector().getConnectorId();
  497. if (uiConnectorId == null) {
  498. // Nothing to clear yet
  499. return;
  500. }
  501. // Create fake server response that says that the uiConnector
  502. // has no children
  503. JsonObject fakeHierarchy = Json.createObject();
  504. fakeHierarchy.put(uiConnectorId, Json.createArray());
  505. JsonObject fakeJson = Json.createObject();
  506. fakeJson.put("hierarchy", fakeHierarchy);
  507. ValueMap fakeValueMap = ((JavaScriptObject) fakeJson.toNative())
  508. .cast();
  509. // Update hierarchy based on the fake response
  510. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(
  511. fakeValueMap);
  512. // Send hierarchy events based on the fake update
  513. sendHierarchyChangeEvents(
  514. connectorHierarchyUpdateResult.events);
  515. // Unregister all the old connectors that have now been removed
  516. unregisterRemovedConnectors(
  517. connectorHierarchyUpdateResult.detachedConnectorIds);
  518. }
  519. private void updateCaptions(
  520. JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
  521. FastStringSet parentChangedIds) {
  522. Profiler.enter("updateCaptions");
  523. /*
  524. * Find all components that might need a caption update based on
  525. * pending state and hierarchy changes
  526. */
  527. FastStringSet needsCaptionUpdate = FastStringSet.create();
  528. needsCaptionUpdate.addAll(parentChangedIds);
  529. // Find components with potentially changed caption state
  530. int size = pendingStateChangeEvents.size();
  531. for (int i = 0; i < size; i++) {
  532. StateChangeEvent event = pendingStateChangeEvents.get(i);
  533. if (VCaption.mightChange(event)) {
  534. ServerConnector connector = event.getConnector();
  535. needsCaptionUpdate.add(connector.getConnectorId());
  536. }
  537. }
  538. ConnectorMap connectorMap = getConnectorMap();
  539. // Update captions for all suitable candidates
  540. JsArrayString dump = needsCaptionUpdate.dump();
  541. int needsUpdateLength = dump.length();
  542. for (int i = 0; i < needsUpdateLength; i++) {
  543. String childId = dump.get(i);
  544. ServerConnector child = connectorMap.getConnector(childId);
  545. if (child instanceof ComponentConnector
  546. && ((ComponentConnector) child)
  547. .delegateCaptionHandling()) {
  548. ServerConnector parent = child.getParent();
  549. if (parent instanceof HasComponentsConnector) {
  550. Profiler.enter(
  551. "HasComponentsConnector.updateCaption");
  552. ((HasComponentsConnector) parent)
  553. .updateCaption((ComponentConnector) child);
  554. Profiler.leave(
  555. "HasComponentsConnector.updateCaption");
  556. }
  557. }
  558. }
  559. Profiler.leave("updateCaptions");
  560. }
  561. private void delegateToWidget(
  562. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  563. Profiler.enter("@DelegateToWidget");
  564. getLogger().info(" * Running @DelegateToWidget");
  565. // Keep track of types that have no @DelegateToWidget in their
  566. // state to optimize performance
  567. FastStringSet noOpTypes = FastStringSet.create();
  568. int size = pendingStateChangeEvents.size();
  569. for (int eventIndex = 0; eventIndex < size; eventIndex++) {
  570. StateChangeEvent sce = pendingStateChangeEvents
  571. .get(eventIndex);
  572. ServerConnector connector = sce.getConnector();
  573. if (connector instanceof ComponentConnector) {
  574. String className = connector.getClass().getName();
  575. if (noOpTypes.contains(className)) {
  576. continue;
  577. }
  578. ComponentConnector component = (ComponentConnector) connector;
  579. Type stateType = AbstractConnector
  580. .getStateType(component);
  581. JsArrayString delegateToWidgetProperties = stateType
  582. .getDelegateToWidgetProperties();
  583. if (delegateToWidgetProperties == null) {
  584. noOpTypes.add(className);
  585. continue;
  586. }
  587. int length = delegateToWidgetProperties.length();
  588. for (int i = 0; i < length; i++) {
  589. String propertyName = delegateToWidgetProperties
  590. .get(i);
  591. if (sce.hasPropertyChanged(propertyName)) {
  592. Property property = stateType
  593. .getProperty(propertyName);
  594. String method = property
  595. .getDelegateToWidgetMethodName();
  596. Profiler.enter("doDelegateToWidget");
  597. doDelegateToWidget(component, property, method);
  598. Profiler.leave("doDelegateToWidget");
  599. }
  600. }
  601. }
  602. }
  603. Profiler.leave("@DelegateToWidget");
  604. }
  605. private void doDelegateToWidget(ComponentConnector component,
  606. Property property, String methodName) {
  607. Type type = TypeData.getType(component.getClass());
  608. try {
  609. Type widgetType = type.getMethod("getWidget")
  610. .getReturnType();
  611. Widget widget = component.getWidget();
  612. Object propertyValue = property
  613. .getValue(component.getState());
  614. widgetType.getMethod(methodName).invoke(widget,
  615. propertyValue);
  616. } catch (NoDataException e) {
  617. throw new RuntimeException(
  618. "Missing data needed to invoke @DelegateToWidget for "
  619. + component.getClass().getSimpleName(),
  620. e);
  621. }
  622. }
  623. /**
  624. * Sends the state change events created while updating the state
  625. * information.
  626. *
  627. * This must be called after hierarchy change listeners have been
  628. * called. At least caption updates for the parent are strange if
  629. * fired from state change listeners and thus calls the parent
  630. * BEFORE the parent is aware of the child (through a
  631. * ConnectorHierarchyChangedEvent)
  632. *
  633. * @param pendingStateChangeEvents
  634. * The events to send
  635. */
  636. private void sendStateChangeEvents(
  637. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  638. Profiler.enter("sendStateChangeEvents");
  639. getLogger().info(" * Sending state change events");
  640. int size = pendingStateChangeEvents.size();
  641. for (int i = 0; i < size; i++) {
  642. StateChangeEvent sce = pendingStateChangeEvents.get(i);
  643. try {
  644. sce.getConnector().fireEvent(sce);
  645. } catch (final Throwable e) {
  646. getLogger().log(Level.SEVERE,
  647. "Error sending state change events", e);
  648. }
  649. }
  650. Profiler.leave("sendStateChangeEvents");
  651. }
  652. private void verifyConnectorHierarchy() {
  653. Profiler.enter(
  654. "verifyConnectorHierarchy - this is only performed in debug mode");
  655. JsArrayObject<ServerConnector> currentConnectors = getConnectorMap()
  656. .getConnectorsAsJsArray();
  657. int size = currentConnectors.size();
  658. for (int i = 0; i < size; i++) {
  659. ServerConnector c = currentConnectors.get(i);
  660. if (c.getParent() != null) {
  661. if (!c.getParent().getChildren().contains(c)) {
  662. getLogger().severe("ERROR: Connector "
  663. + c.getConnectorId()
  664. + " is connected to a parent but the parent ("
  665. + c.getParent().getConnectorId()
  666. + ") does not contain the connector");
  667. }
  668. } else if (c == getUIConnector()) {
  669. // UIConnector for this connection, ignore
  670. } else if (c instanceof WindowConnector && getUIConnector()
  671. .hasSubWindow((WindowConnector) c)) {
  672. // Sub window attached to this UIConnector, ignore
  673. } else {
  674. // The connector has been detached from the
  675. // hierarchy but was not unregistered.
  676. getLogger().severe("ERROR: Connector "
  677. + c.getConnectorId()
  678. + " is not attached to a parent but has not been unregistered");
  679. }
  680. }
  681. Profiler.leave(
  682. "verifyConnectorHierarchy - this is only performed in debug mode");
  683. }
  684. private void unregisterRemovedConnectors(
  685. FastStringSet detachedConnectors) {
  686. Profiler.enter("unregisterRemovedConnectors");
  687. JsArrayString detachedArray = detachedConnectors.dump();
  688. for (int i = 0; i < detachedArray.length(); i++) {
  689. ServerConnector connector = getConnectorMap()
  690. .getConnector(detachedArray.get(i));
  691. Profiler.enter(
  692. "unregisterRemovedConnectors unregisterConnector");
  693. getConnectorMap().unregisterConnector(connector);
  694. Profiler.leave(
  695. "unregisterRemovedConnectors unregisterConnector");
  696. }
  697. if (ApplicationConfiguration.isDebugMode()) {
  698. // Do some extra checking if we're in debug mode (i.e. debug
  699. // window is open)
  700. verifyConnectorHierarchy();
  701. }
  702. getLogger().info("* Unregistered " + detachedArray.length()
  703. + " connectors");
  704. Profiler.leave("unregisterRemovedConnectors");
  705. }
  706. private JsArrayString createConnectorsIfNeeded(ValueMap json) {
  707. getLogger().info(" * Creating connectors (if needed)");
  708. JsArrayString createdConnectors = JavaScriptObject.createArray()
  709. .cast();
  710. if (!json.containsKey("types")) {
  711. return createdConnectors;
  712. }
  713. Profiler.enter("Creating connectors");
  714. ValueMap types = json.getValueMap("types");
  715. JsArrayString keyArray = types.getKeyArray();
  716. for (int i = 0; i < keyArray.length(); i++) {
  717. try {
  718. String connectorId = keyArray.get(i);
  719. ServerConnector connector = getConnectorMap()
  720. .getConnector(connectorId);
  721. if (connector != null) {
  722. continue;
  723. }
  724. // Always do layouts if there's at least one new
  725. // connector
  726. onlyNoLayoutUpdates = false;
  727. int connectorType = Integer
  728. .parseInt(types.getString(connectorId));
  729. Class<? extends ServerConnector> connectorClass = connection
  730. .getConfiguration()
  731. .getConnectorClassByEncodedTag(connectorType);
  732. // Connector does not exist so we must create it
  733. if (connectorClass != getUIConnector().getClass()) {
  734. // create, initialize and register the paintable
  735. Profiler.enter(
  736. "ApplicationConnection.getConnector");
  737. connector = connection.getConnector(connectorId,
  738. connectorType);
  739. Profiler.leave(
  740. "ApplicationConnection.getConnector");
  741. createdConnectors.push(connectorId);
  742. } else {
  743. // First UIConnector update. Before this the
  744. // UIConnector has been created but not
  745. // initialized as the connector id has not been
  746. // known
  747. getConnectorMap().registerConnector(connectorId,
  748. getUIConnector());
  749. getUIConnector().doInit(connectorId, connection);
  750. createdConnectors.push(connectorId);
  751. }
  752. } catch (final Throwable e) {
  753. getLogger().log(Level.SEVERE,
  754. "Error handling type data", e);
  755. }
  756. }
  757. Profiler.leave("Creating connectors");
  758. return createdConnectors;
  759. }
  760. private void updateVaadin6StyleConnectors(ValueMap json) {
  761. Profiler.enter("updateVaadin6StyleConnectors");
  762. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  763. int length = changes.length();
  764. // Must always do layout if there's even a single legacy update
  765. if (length != 0) {
  766. onlyNoLayoutUpdates = false;
  767. }
  768. getLogger()
  769. .info(" * Passing UIDL to Vaadin 6 style connectors");
  770. // update paintables
  771. for (int i = 0; i < length; i++) {
  772. try {
  773. final UIDL change = changes.get(i).cast();
  774. final UIDL uidl = change.getChildUIDL(0);
  775. String connectorId = uidl.getId();
  776. final ComponentConnector legacyConnector = (ComponentConnector) getConnectorMap()
  777. .getConnector(connectorId);
  778. if (legacyConnector instanceof Paintable) {
  779. String key = null;
  780. if (Profiler.isEnabled()) {
  781. key = "updateFromUIDL for " + legacyConnector
  782. .getClass().getSimpleName();
  783. Profiler.enter(key);
  784. }
  785. ((Paintable) legacyConnector).updateFromUIDL(uidl,
  786. connection);
  787. if (Profiler.isEnabled()) {
  788. Profiler.leave(key);
  789. }
  790. } else if (legacyConnector == null) {
  791. getLogger().severe("Received update for "
  792. + uidl.getTag()
  793. + ", but there is no such paintable ("
  794. + connectorId + ") rendered.");
  795. } else {
  796. getLogger().severe(
  797. "Server sent Vaadin 6 style updates for "
  798. + Util.getConnectorString(
  799. legacyConnector)
  800. + " but this is not a Vaadin 6 Paintable");
  801. }
  802. } catch (final Throwable e) {
  803. getLogger().log(Level.SEVERE, "Error handling UIDL", e);
  804. }
  805. }
  806. Profiler.leave("updateVaadin6StyleConnectors");
  807. }
  808. private void sendHierarchyChangeEvents(
  809. JsArrayObject<ConnectorHierarchyChangeEvent> events) {
  810. int eventCount = events.size();
  811. if (eventCount == 0) {
  812. return;
  813. }
  814. Profiler.enter("sendHierarchyChangeEvents");
  815. getLogger().info(" * Sending hierarchy change events");
  816. for (int i = 0; i < eventCount; i++) {
  817. ConnectorHierarchyChangeEvent event = events.get(i);
  818. try {
  819. logHierarchyChange(event);
  820. event.getConnector().fireEvent(event);
  821. } catch (final Throwable e) {
  822. getLogger().log(Level.SEVERE,
  823. "Error sending hierarchy change events", e);
  824. }
  825. }
  826. Profiler.leave("sendHierarchyChangeEvents");
  827. }
  828. private void logHierarchyChange(
  829. ConnectorHierarchyChangeEvent event) {
  830. if (true) {
  831. // Always disabled for now. Can be enabled manually
  832. return;
  833. }
  834. getLogger().info("Hierarchy changed for "
  835. + Util.getConnectorString(event.getConnector()));
  836. String oldChildren = "* Old children: ";
  837. for (ComponentConnector child : event.getOldChildren()) {
  838. oldChildren += Util.getConnectorString(child) + " ";
  839. }
  840. getLogger().info(oldChildren);
  841. String newChildren = "* New children: ";
  842. HasComponentsConnector parent = (HasComponentsConnector) event
  843. .getConnector();
  844. for (ComponentConnector child : parent.getChildComponents()) {
  845. newChildren += Util.getConnectorString(child) + " ";
  846. }
  847. getLogger().info(newChildren);
  848. }
  849. private JsArrayObject<StateChangeEvent> updateConnectorState(
  850. ValueMap json, JsArrayString createdConnectorIds) {
  851. JsArrayObject<StateChangeEvent> events = JavaScriptObject
  852. .createArray().cast();
  853. getLogger().info(" * Updating connector states");
  854. if (!json.containsKey("state")) {
  855. return events;
  856. }
  857. Profiler.enter("updateConnectorState");
  858. FastStringSet remainingNewConnectors = FastStringSet.create();
  859. remainingNewConnectors.addAll(createdConnectorIds);
  860. // set states for all paintables mentioned in "state"
  861. ValueMap states = json.getValueMap("state");
  862. JsArrayString keyArray = states.getKeyArray();
  863. for (int i = 0; i < keyArray.length(); i++) {
  864. try {
  865. String connectorId = keyArray.get(i);
  866. ServerConnector connector = getConnectorMap()
  867. .getConnector(connectorId);
  868. if (null != connector) {
  869. Profiler.enter("updateConnectorState inner loop");
  870. if (Profiler.isEnabled()) {
  871. Profiler.enter("Decode connector state "
  872. + connector.getClass().getSimpleName());
  873. }
  874. JavaScriptObject jso = states
  875. .getJavaScriptObject(connectorId);
  876. JsonObject stateJson = Util.jso2json(jso);
  877. if (connector instanceof HasJavaScriptConnectorHelper) {
  878. ((HasJavaScriptConnectorHelper) connector)
  879. .getJavascriptConnectorHelper()
  880. .setNativeState(jso);
  881. }
  882. SharedState state = connector.getState();
  883. Type stateType = new Type(
  884. state.getClass().getName(), null);
  885. if (onlyNoLayoutUpdates) {
  886. Profiler.enter(
  887. "updateConnectorState @NoLayout handling");
  888. for (String propertyName : stateJson.keys()) {
  889. Property property = stateType
  890. .getProperty(propertyName);
  891. if (!property.isNoLayout()) {
  892. onlyNoLayoutUpdates = false;
  893. break;
  894. }
  895. }
  896. Profiler.leave(
  897. "updateConnectorState @NoLayout handling");
  898. }
  899. Profiler.enter("updateConnectorState decodeValue");
  900. JsonDecoder.decodeValue(stateType, stateJson, state,
  901. connection);
  902. Profiler.leave("updateConnectorState decodeValue");
  903. if (Profiler.isEnabled()) {
  904. Profiler.leave("Decode connector state "
  905. + connector.getClass().getSimpleName());
  906. }
  907. Profiler.enter("updateConnectorState create event");
  908. boolean isNewConnector = remainingNewConnectors
  909. .contains(connectorId);
  910. if (isNewConnector) {
  911. remainingNewConnectors.remove(connectorId);
  912. }
  913. StateChangeEvent event = new StateChangeEvent(
  914. connector, stateJson, isNewConnector);
  915. events.add(event);
  916. Profiler.leave("updateConnectorState create event");
  917. Profiler.leave("updateConnectorState inner loop");
  918. }
  919. } catch (final Throwable e) {
  920. getLogger().log(Level.SEVERE,
  921. "Error updating connector states", e);
  922. }
  923. }
  924. Profiler.enter("updateConnectorState newWithoutState");
  925. // Fire events for properties using the default value for newly
  926. // created connectors even if there were no state changes
  927. JsArrayString dump = remainingNewConnectors.dump();
  928. int length = dump.length();
  929. for (int i = 0; i < length; i++) {
  930. String connectorId = dump.get(i);
  931. ServerConnector connector = getConnectorMap()
  932. .getConnector(connectorId);
  933. StateChangeEvent event = new StateChangeEvent(connector,
  934. Json.createObject(), true);
  935. events.add(event);
  936. }
  937. Profiler.leave("updateConnectorState newWithoutState");
  938. Profiler.leave("updateConnectorState");
  939. return events;
  940. }
  941. /**
  942. * Updates the connector hierarchy and returns a list of events that
  943. * should be fired after update of the hierarchy and the state is
  944. * done.
  945. *
  946. * @param json
  947. * The JSON containing the hierarchy information
  948. * @return A collection of events that should be fired when update
  949. * of hierarchy and state is complete and a list of all
  950. * connectors for which the parent has changed
  951. */
  952. private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
  953. ValueMap json) {
  954. ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
  955. getLogger().info(" * Updating connector hierarchy");
  956. Profiler.enter("updateConnectorHierarchy");
  957. FastStringSet maybeDetached = FastStringSet.create();
  958. FastStringSet hasHierarchy = FastStringSet.create();
  959. // Process regular hierarchy data
  960. if (json.containsKey("hierarchy")) {
  961. ValueMap hierarchies = json.getValueMap("hierarchy");
  962. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  963. for (int i = 0; i < hierarchyKeys.length(); i++) {
  964. String connectorId = hierarchyKeys.get(i);
  965. JsArrayString childConnectorIds = hierarchies
  966. .getJSStringArray(connectorId);
  967. hasHierarchy.add(connectorId);
  968. updateConnectorHierarchy(connectorId, childConnectorIds,
  969. maybeDetached, result);
  970. }
  971. }
  972. // Assume empty hierarchy for connectors with state updates but
  973. // no hierarchy data
  974. if (json.containsKey("state")) {
  975. JsArrayString stateKeys = json.getValueMap("state")
  976. .getKeyArray();
  977. JsArrayString emptyArray = JavaScriptObject.createArray()
  978. .cast();
  979. for (int i = 0; i < stateKeys.length(); i++) {
  980. String connectorId = stateKeys.get(i);
  981. if (!hasHierarchy.contains(connectorId)) {
  982. updateConnectorHierarchy(connectorId, emptyArray,
  983. maybeDetached, result);
  984. }
  985. }
  986. }
  987. Profiler.enter(
  988. "updateConnectorHierarchy detach removed connectors");
  989. /*
  990. * Connector is in maybeDetached at this point if it has been
  991. * removed from its parent but not added to any other parent
  992. */
  993. JsArrayString maybeDetachedArray = maybeDetached.dump();
  994. for (int i = 0; i < maybeDetachedArray.length(); i++) {
  995. ServerConnector removed = getConnectorMap()
  996. .getConnector(maybeDetachedArray.get(i));
  997. recursivelyDetach(removed, result.events,
  998. result.detachedConnectorIds);
  999. }
  1000. Profiler.leave(
  1001. "updateConnectorHierarchy detach removed connectors");
  1002. if (result.events.size() != 0) {
  1003. onlyNoLayoutUpdates = false;
  1004. }
  1005. Profiler.leave("updateConnectorHierarchy");
  1006. return result;
  1007. }
  1008. /**
  1009. * Updates the hierarchy for a connector
  1010. *
  1011. * @param connectorId
  1012. * the id of the connector to update
  1013. * @param childConnectorIds
  1014. * array of child connector ids
  1015. * @param maybeDetached
  1016. * set of connectors that are maybe detached
  1017. * @param result
  1018. * the hierarchy update result
  1019. */
  1020. private void updateConnectorHierarchy(String connectorId,
  1021. JsArrayString childConnectorIds,
  1022. FastStringSet maybeDetached,
  1023. ConnectorHierarchyUpdateResult result) {
  1024. try {
  1025. Profiler.enter("updateConnectorHierarchy hierarchy entry");
  1026. ConnectorMap connectorMap = getConnectorMap();
  1027. ServerConnector parentConnector = connectorMap
  1028. .getConnector(connectorId);
  1029. int childConnectorSize = childConnectorIds.length();
  1030. Profiler.enter(
  1031. "updateConnectorHierarchy find new connectors");
  1032. List<ServerConnector> newChildren = new ArrayList<>();
  1033. List<ComponentConnector> newComponents = new ArrayList<>();
  1034. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  1035. String childConnectorId = childConnectorIds
  1036. .get(connectorIndex);
  1037. ServerConnector childConnector = connectorMap
  1038. .getConnector(childConnectorId);
  1039. if (childConnector == null) {
  1040. getLogger().severe("Hierarchy claims that "
  1041. + childConnectorId + " is a child for "
  1042. + connectorId + " ("
  1043. + parentConnector.getClass().getName()
  1044. + ") but no connector with id "
  1045. + childConnectorId
  1046. + " has been registered. "
  1047. + "More information might be available in the server-side log if assertions are enabled");
  1048. continue;
  1049. }
  1050. newChildren.add(childConnector);
  1051. if (childConnector instanceof ComponentConnector) {
  1052. newComponents
  1053. .add((ComponentConnector) childConnector);
  1054. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  1055. throw new IllegalStateException(Util
  1056. .getConnectorString(childConnector)
  1057. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  1058. }
  1059. if (childConnector.getParent() != parentConnector) {
  1060. childConnector.setParent(parentConnector);
  1061. result.parentChangedIds.add(childConnectorId);
  1062. // Not detached even if previously removed from
  1063. // parent
  1064. maybeDetached.remove(childConnectorId);
  1065. }
  1066. }
  1067. Profiler.leave(
  1068. "updateConnectorHierarchy find new connectors");
  1069. // TODO This check should be done on the server side in
  1070. // the future so the hierarchy update is only sent when
  1071. // something actually has changed
  1072. List<ServerConnector> oldChildren = parentConnector
  1073. .getChildren();
  1074. boolean actuallyChanged = !Util
  1075. .collectionsEquals(oldChildren, newChildren);
  1076. if (!actuallyChanged) {
  1077. return;
  1078. }
  1079. Profiler.enter(
  1080. "updateConnectorHierarchy handle HasComponentsConnector");
  1081. if (parentConnector instanceof HasComponentsConnector) {
  1082. HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
  1083. List<ComponentConnector> oldComponents = ccc
  1084. .getChildComponents();
  1085. if (!Util.collectionsEquals(oldComponents,
  1086. newComponents)) {
  1087. // Fire change event if the hierarchy has
  1088. // changed
  1089. ConnectorHierarchyChangeEvent event = GWT.create(
  1090. ConnectorHierarchyChangeEvent.class);
  1091. event.setOldChildren(oldComponents);
  1092. event.setConnector(parentConnector);
  1093. ccc.setChildComponents(newComponents);
  1094. result.events.add(event);
  1095. }
  1096. } else if (!newComponents.isEmpty()) {
  1097. getLogger().severe("Hierachy claims "
  1098. + Util.getConnectorString(parentConnector)
  1099. + " has component children even though it isn't a HasComponentsConnector");
  1100. }
  1101. Profiler.leave(
  1102. "updateConnectorHierarchy handle HasComponentsConnector");
  1103. Profiler.enter("updateConnectorHierarchy setChildren");
  1104. parentConnector.setChildren(newChildren);
  1105. Profiler.leave("updateConnectorHierarchy setChildren");
  1106. Profiler.enter(
  1107. "updateConnectorHierarchy find removed children");
  1108. /*
  1109. * Find children removed from this parent and mark for
  1110. * removal unless they are already attached to some other
  1111. * parent.
  1112. */
  1113. for (ServerConnector oldChild : oldChildren) {
  1114. if (oldChild.getParent() != parentConnector) {
  1115. // Ignore if moved to some other connector
  1116. continue;
  1117. }
  1118. if (!newChildren.contains(oldChild)) {
  1119. /*
  1120. * Consider child detached for now, will be cleared
  1121. * if it is later on added to some other parent.
  1122. */
  1123. maybeDetached.add(oldChild.getConnectorId());
  1124. }
  1125. }
  1126. Profiler.leave(
  1127. "updateConnectorHierarchy find removed children");
  1128. } catch (final Throwable e) {
  1129. getLogger().log(Level.SEVERE,
  1130. "Error updating connector hierarchy", e);
  1131. } finally {
  1132. Profiler.leave("updateConnectorHierarchy hierarchy entry");
  1133. }
  1134. }
  1135. private void recursivelyDetach(ServerConnector connector,
  1136. JsArrayObject<ConnectorHierarchyChangeEvent> events,
  1137. FastStringSet detachedConnectors) {
  1138. detachedConnectors.add(connector.getConnectorId());
  1139. /*
  1140. * Reset state in an attempt to keep it consistent with the
  1141. * hierarchy. No children and no parent is the initial situation
  1142. * for the hierarchy, so changing the state to its initial value
  1143. * is the closest we can get without data from the server.
  1144. * #10151
  1145. */
  1146. String prefix = getClass().getSimpleName() + " ";
  1147. Profiler.enter(prefix + "recursivelyDetach reset state");
  1148. try {
  1149. Profiler.enter(prefix
  1150. + "recursivelyDetach reset state - getStateType");
  1151. Type stateType = AbstractConnector.getStateType(connector);
  1152. Profiler.leave(prefix
  1153. + "recursivelyDetach reset state - getStateType");
  1154. // Empty state instance to get default property values from
  1155. Profiler.enter(prefix
  1156. + "recursivelyDetach reset state - createInstance");
  1157. Object defaultState = stateType.createInstance();
  1158. Profiler.leave(prefix
  1159. + "recursivelyDetach reset state - createInstance");
  1160. if (connector instanceof AbstractConnector) {
  1161. // optimization as the loop setting properties is very
  1162. // slow
  1163. replaceState((AbstractConnector) connector,
  1164. defaultState);
  1165. } else {
  1166. SharedState state = connector.getState();
  1167. Profiler.enter(prefix
  1168. + "recursivelyDetach reset state - properties");
  1169. JsArrayObject<Property> properties = stateType
  1170. .getPropertiesAsArray();
  1171. int size = properties.size();
  1172. for (int i = 0; i < size; i++) {
  1173. Property property = properties.get(i);
  1174. property.setValue(state,
  1175. property.getValue(defaultState));
  1176. }
  1177. Profiler.leave(prefix
  1178. + "recursivelyDetach reset state - properties");
  1179. }
  1180. } catch (NoDataException e) {
  1181. throw new RuntimeException("Can't reset state for "
  1182. + Util.getConnectorString(connector), e);
  1183. } finally {
  1184. Profiler.leave(prefix + "recursivelyDetach reset state");
  1185. }
  1186. Profiler.enter(prefix + "recursivelyDetach perform detach");
  1187. /*
  1188. * Recursively detach children to make sure they get
  1189. * setParent(null) and hierarchy change events as needed.
  1190. */
  1191. for (ServerConnector child : connector.getChildren()) {
  1192. /*
  1193. * Server doesn't send updated child data for removed
  1194. * connectors -> ignore child that still seems to be a child
  1195. * of this connector although it has been moved to some part
  1196. * of the hierarchy that is not detached.
  1197. */
  1198. if (child.getParent() != connector) {
  1199. continue;
  1200. }
  1201. recursivelyDetach(child, events, detachedConnectors);
  1202. }
  1203. Profiler.leave(prefix + "recursivelyDetach perform detach");
  1204. /*
  1205. * Clear child list and parent
  1206. */
  1207. Profiler.enter(
  1208. prefix + "recursivelyDetach clear children and parent");
  1209. connector
  1210. .setChildren(Collections.<ServerConnector> emptyList());
  1211. connector.setParent(null);
  1212. Profiler.leave(
  1213. prefix + "recursivelyDetach clear children and parent");
  1214. /*
  1215. * Create an artificial hierarchy event for containers to give
  1216. * it a chance to clean up after its children if it has any
  1217. */
  1218. Profiler.enter(
  1219. prefix + "recursivelyDetach create hierarchy event");
  1220. if (connector instanceof HasComponentsConnector) {
  1221. HasComponentsConnector ccc = (HasComponentsConnector) connector;
  1222. List<ComponentConnector> oldChildren = ccc
  1223. .getChildComponents();
  1224. if (!oldChildren.isEmpty()) {
  1225. /*
  1226. * HasComponentsConnector has a separate child component
  1227. * list that should also be cleared
  1228. */
  1229. ccc.setChildComponents(
  1230. Collections.<ComponentConnector> emptyList());
  1231. // Create event and add it to the list of pending events
  1232. ConnectorHierarchyChangeEvent event = GWT
  1233. .create(ConnectorHierarchyChangeEvent.class);
  1234. event.setConnector(connector);
  1235. event.setOldChildren(oldChildren);
  1236. events.add(event);
  1237. }
  1238. }
  1239. Profiler.leave(
  1240. prefix + "recursivelyDetach create hierarchy event");
  1241. }
  1242. private native void replaceState(AbstractConnector connector,
  1243. Object defaultState)
  1244. /*-{
  1245. connector.@com.vaadin.client.ui.AbstractConnector::state = defaultState;
  1246. }-*/;
  1247. private void handleRpcInvocations(ValueMap json) {
  1248. if (json.containsKey("rpc")) {
  1249. Profiler.enter("handleRpcInvocations");
  1250. getLogger()
  1251. .info(" * Performing server to client RPC calls");
  1252. JsonArray rpcCalls = Util
  1253. .jso2json(json.getJavaScriptObject("rpc"));
  1254. int rpcLength = rpcCalls.length();
  1255. for (int i = 0; i < rpcLength; i++) {
  1256. try {
  1257. JsonArray rpcCall = rpcCalls.getArray(i);
  1258. MethodInvocation invocation = getRpcManager()
  1259. .parseAndApplyInvocation(rpcCall,
  1260. connection);
  1261. if (onlyNoLayoutUpdates && !RpcManager
  1262. .getMethod(invocation).isNoLayout()) {
  1263. onlyNoLayoutUpdates = false;
  1264. }
  1265. } catch (final Throwable e) {
  1266. getLogger().log(Level.SEVERE,
  1267. "Error performing server to client RPC calls",
  1268. e);
  1269. }
  1270. }
  1271. Profiler.leave("handleRpcInvocations");
  1272. }
  1273. }
  1274. };
  1275. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  1276. }
  1277. private void endRequestIfResponse(ValueMap json) {
  1278. if (isResponse(json)) {
  1279. // End the request if the received message was a
  1280. // response, not sent asynchronously
  1281. getMessageSender().endRequest();
  1282. }
  1283. }
  1284. private boolean isResynchronize(ValueMap json) {
  1285. return json.containsKey(ApplicationConstants.RESYNCHRONIZE_ID);
  1286. }
  1287. private boolean isResponse(ValueMap json) {
  1288. ValueMap meta = json.getValueMap("meta");
  1289. if (meta == null || !meta.containsKey("async")) {
  1290. return true;
  1291. }
  1292. return false;
  1293. }
  1294. /**
  1295. * Checks if the given serverId is the one we are currently waiting for from
  1296. * the server
  1297. */
  1298. private boolean isNextExpectedMessage(int serverId) {
  1299. if (serverId == -1) {
  1300. return true;
  1301. }
  1302. if (serverId == getExpectedServerId()) {
  1303. return true;
  1304. }
  1305. if (lastSeenServerSyncId == UNDEFINED_SYNC_ID) {
  1306. // First message is always ok
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. private int getServerId(ValueMap json) {
  1312. if (json.containsKey(ApplicationConstants.SERVER_SYNC_ID)) {
  1313. return json.getInt(ApplicationConstants.SERVER_SYNC_ID);
  1314. } else {
  1315. return -1;
  1316. }
  1317. }
  1318. private int getExpectedServerId() {
  1319. return lastSeenServerSyncId + 1;
  1320. }
  1321. /**
  1322. * Timer used to make sure that no misbehaving components can delay response
  1323. * handling forever.
  1324. */
  1325. Timer forceHandleMessage = new Timer() {
  1326. @Override
  1327. public void run() {
  1328. if (!responseHandlingLocks.isEmpty()) {
  1329. // Lock which was never release -> bug in locker or things just
  1330. // too slow
  1331. getLogger().warning(
  1332. "WARNING: reponse handling was never resumed, forcibly removing locks...");
  1333. responseHandlingLocks.clear();
  1334. } else {
  1335. // Waited for out-of-order message which never arrived
  1336. // Do one final check and resynchronize if the message is not
  1337. // there. The final check is only a precaution as this timer
  1338. // should have been cancelled if the message has arrived
  1339. getLogger().warning("Gave up waiting for message "
  1340. + getExpectedServerId() + " from the server");
  1341. }
  1342. if (!handlePendingMessages() && !pendingUIDLMessages.isEmpty()) {
  1343. // There are messages but the next id was not found, likely it
  1344. // has been lost
  1345. // Drop pending messages and resynchronize
  1346. pendingUIDLMessages.clear();
  1347. getMessageSender().resynchronize();
  1348. }
  1349. }
  1350. };
  1351. /**
  1352. * This method can be used to postpone rendering of a response for a short
  1353. * period of time (e.g. to avoid the rendering process during animation).
  1354. *
  1355. * @param lock
  1356. */
  1357. public void suspendReponseHandling(Object lock) {
  1358. responseHandlingLocks.add(lock);
  1359. }
  1360. /**
  1361. * Resumes the rendering process once all locks have been removed.
  1362. *
  1363. * @param lock
  1364. */
  1365. public void resumeResponseHandling(Object lock) {
  1366. responseHandlingLocks.remove(lock);
  1367. if (responseHandlingLocks.isEmpty()) {
  1368. // Cancel timer that breaks the lock
  1369. forceHandleMessage.cancel();
  1370. if (!pendingUIDLMessages.isEmpty()) {
  1371. getLogger().info(
  1372. "No more response handling locks, handling pending requests.");
  1373. handlePendingMessages();
  1374. }
  1375. }
  1376. }
  1377. private static final native int calculateBootstrapTime()
  1378. /*-{
  1379. if ($wnd.performance && $wnd.performance.timing) {
  1380. return (new Date).getTime() - $wnd.performance.timing.responseStart;
  1381. } else {
  1382. // performance.timing not supported
  1383. return -1;
  1384. }
  1385. }-*/;
  1386. /**
  1387. * Finds the next pending UIDL message and handles it (next pending is
  1388. * decided based on the server id)
  1389. *
  1390. * @return true if a message was handled, false otherwise
  1391. */
  1392. private boolean handlePendingMessages() {
  1393. if (pendingUIDLMessages.isEmpty()) {
  1394. return false;
  1395. }
  1396. // Try to find the next expected message
  1397. PendingUIDLMessage toHandle = null;
  1398. for (PendingUIDLMessage message : pendingUIDLMessages) {
  1399. if (isNextExpectedMessage(getServerId(message.json))) {
  1400. toHandle = message;
  1401. break;
  1402. }
  1403. }
  1404. if (toHandle != null) {
  1405. pendingUIDLMessages.remove(toHandle);
  1406. handleJSON(toHandle.getJson());
  1407. // Any remaining messages will be handled when this is called
  1408. // again at the end of handleJSON
  1409. return true;
  1410. } else {
  1411. return false;
  1412. }
  1413. }
  1414. private void removeOldPendingMessages() {
  1415. Iterator<PendingUIDLMessage> i = pendingUIDLMessages.iterator();
  1416. while (i.hasNext()) {
  1417. PendingUIDLMessage m = i.next();
  1418. int serverId = getServerId(m.json);
  1419. if (serverId != -1 && serverId < getExpectedServerId()) {
  1420. getLogger().info("Removing old message with id " + serverId);
  1421. i.remove();
  1422. }
  1423. }
  1424. }
  1425. /**
  1426. * Gets the server id included in the last received response.
  1427. * <p>
  1428. * This id can be used by connectors to determine whether new data has been
  1429. * received from the server to avoid doing the same calculations multiple
  1430. * times.
  1431. * <p>
  1432. * No guarantees are made for the structure of the id other than that there
  1433. * will be a new unique value every time a new response with data from the
  1434. * server is received.
  1435. * <p>
  1436. * The initial id when no request has yet been processed is -1.
  1437. *
  1438. * @return an id identifying the response
  1439. */
  1440. public int getLastSeenServerSyncId() {
  1441. return lastSeenServerSyncId;
  1442. }
  1443. /**
  1444. * Gets the token (aka double submit cookie) that the server uses to protect
  1445. * against Cross Site Request Forgery attacks.
  1446. *
  1447. * @return the CSRF token string
  1448. */
  1449. public String getCsrfToken() {
  1450. return csrfToken;
  1451. }
  1452. /**
  1453. * Gets the push connection identifier for this session. Used when
  1454. * establishing a push connection with the client.
  1455. *
  1456. * @return the push connection identifier string
  1457. *
  1458. * @since 8.0.6
  1459. */
  1460. public String getPushId() {
  1461. return pushId;
  1462. }
  1463. /**
  1464. * Checks whether state changes are currently being processed. Certain
  1465. * operations are not allowed when the internal state of the application
  1466. * might be in an inconsistent state because some state changes have been
  1467. * applied but others not. This includes running layotus.
  1468. *
  1469. * @return <code>true</code> if the internal state might be inconsistent
  1470. * because changes are being processed; <code>false</code> if the
  1471. * state should be consistent
  1472. */
  1473. public boolean isUpdatingState() {
  1474. return updatingState;
  1475. }
  1476. /**
  1477. * Checks if the first UIDL has been handled.
  1478. *
  1479. * @return true if the initial UIDL has already been processed, false
  1480. * otherwise
  1481. */
  1482. public boolean isInitialUidlHandled() {
  1483. return bootstrapTime != 0;
  1484. }
  1485. private LayoutManager getLayoutManager() {
  1486. return LayoutManager.get(connection);
  1487. }
  1488. private ConnectorMap getConnectorMap() {
  1489. return ConnectorMap.get(connection);
  1490. }
  1491. private UIConnector getUIConnector() {
  1492. return connection.getUIConnector();
  1493. }
  1494. private RpcManager getRpcManager() {
  1495. return connection.getRpcManager();
  1496. }
  1497. private MessageSender getMessageSender() {
  1498. return connection.getMessageSender();
  1499. }
  1500. /**
  1501. * Strips the JSON wrapping from the given json string with wrapping.
  1502. *
  1503. * If the given string is not wrapped as expected, returns null
  1504. *
  1505. * @since 7.6
  1506. * @param jsonWithWrapping
  1507. * the JSON received from the server
  1508. * @return an unwrapped JSON string or null if the given string was not
  1509. * wrapped
  1510. */
  1511. public static String stripJSONWrapping(String jsonWithWrapping) {
  1512. if (jsonWithWrapping == null) {
  1513. return null;
  1514. }
  1515. if (!jsonWithWrapping.startsWith(JSON_COMMUNICATION_PREFIX)
  1516. || !jsonWithWrapping.endsWith(JSON_COMMUNICATION_SUFFIX)) {
  1517. return null;
  1518. }
  1519. return jsonWithWrapping.substring(JSON_COMMUNICATION_PREFIX.length(),
  1520. jsonWithWrapping.length() - JSON_COMMUNICATION_SUFFIX.length());
  1521. }
  1522. /**
  1523. * Unwraps and parses the given JSON, originating from the server.
  1524. *
  1525. * @param jsonText
  1526. * the json from the server
  1527. * @return A parsed ValueMap or null if the input could not be parsed (or
  1528. * was null)
  1529. */
  1530. public static ValueMap parseJson(String jsonText) {
  1531. if (jsonText == null) {
  1532. return null;
  1533. }
  1534. final double start = Profiler.getRelativeTimeMillis();
  1535. try {
  1536. ValueMap json = parseJSONResponse(jsonText);
  1537. getLogger().info("JSON parsing took "
  1538. + Util.round(Profiler.getRelativeTimeMillis() - start, 3)
  1539. + "ms");
  1540. return json;
  1541. } catch (final Exception e) {
  1542. getLogger().severe("Unable to parse JSON: " + jsonText);
  1543. return null;
  1544. }
  1545. }
  1546. private static native ValueMap parseJSONResponse(String jsonText)
  1547. /*-{
  1548. try {
  1549. return JSON.parse(jsonText);
  1550. } catch (ignored) {
  1551. return eval('(' + jsonText + ')');
  1552. }
  1553. }-*/;
  1554. /**
  1555. * Parse the given wrapped JSON, received from the server, to a ValueMap.
  1556. *
  1557. * @param wrappedJsonText
  1558. * the json, wrapped as done by the server
  1559. * @return a ValueMap, or null if the wrapping was incorrect or json could
  1560. * not be parsed
  1561. */
  1562. public static ValueMap parseWrappedJson(String wrappedJsonText) {
  1563. return parseJson(stripJSONWrapping(wrappedJsonText));
  1564. }
  1565. private static final native double getFetchStartTime()
  1566. /*-{
  1567. if ($wnd.performance && $wnd.performance.timing && $wnd.performance.timing.fetchStart) {
  1568. return $wnd.performance.timing.fetchStart;
  1569. } else {
  1570. return 0;
  1571. }
  1572. }-*/;
  1573. }