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.

MessageHandler.java 75KB

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