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

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