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

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