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

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