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

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