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

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