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