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

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