Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

MessageHandler.java 75KB

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