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.

ServerMessageHandler.java 68KB

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