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

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