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 76KB

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