您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

MessageHandler.java 76KB

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