You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MessageHandler.java 73KB

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