Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

MessageHandler.java 74KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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. if (!json.containsKey("hierarchy")) {
  960. return result;
  961. }
  962. Profiler.enter("updateConnectorHierarchy");
  963. FastStringSet maybeDetached = FastStringSet.create();
  964. ValueMap hierarchies = json.getValueMap("hierarchy");
  965. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  966. for (int i = 0; i < hierarchyKeys.length(); i++) {
  967. try {
  968. Profiler.enter("updateConnectorHierarchy hierarchy entry");
  969. String connectorId = hierarchyKeys.get(i);
  970. ServerConnector parentConnector = getConnectorMap()
  971. .getConnector(connectorId);
  972. JsArrayString childConnectorIds = hierarchies
  973. .getJSStringArray(connectorId);
  974. int childConnectorSize = childConnectorIds.length();
  975. Profiler.enter("updateConnectorHierarchy find new connectors");
  976. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  977. List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
  978. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  979. String childConnectorId = childConnectorIds
  980. .get(connectorIndex);
  981. ServerConnector childConnector = getConnectorMap()
  982. .getConnector(childConnectorId);
  983. if (childConnector == null) {
  984. getLogger()
  985. .severe("Hierarchy claims that "
  986. + childConnectorId
  987. + " is a child for "
  988. + connectorId
  989. + " ("
  990. + parentConnector.getClass()
  991. .getName()
  992. + ") but no connector with id "
  993. + childConnectorId
  994. + " has been registered. "
  995. + "More information might be available in the server-side log if assertions are enabled");
  996. continue;
  997. }
  998. newChildren.add(childConnector);
  999. if (childConnector instanceof ComponentConnector) {
  1000. newComponents
  1001. .add((ComponentConnector) childConnector);
  1002. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  1003. throw new IllegalStateException(
  1004. Util.getConnectorString(childConnector)
  1005. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  1006. }
  1007. if (childConnector.getParent() != parentConnector) {
  1008. childConnector.setParent(parentConnector);
  1009. result.parentChangedIds.add(childConnectorId);
  1010. // Not detached even if previously removed from
  1011. // parent
  1012. maybeDetached.remove(childConnectorId);
  1013. }
  1014. }
  1015. Profiler.leave("updateConnectorHierarchy find new connectors");
  1016. // TODO This check should be done on the server side in
  1017. // the future so the hierarchy update is only sent when
  1018. // something actually has changed
  1019. List<ServerConnector> oldChildren = parentConnector
  1020. .getChildren();
  1021. boolean actuallyChanged = !Util.collectionsEquals(
  1022. oldChildren, newChildren);
  1023. if (!actuallyChanged) {
  1024. continue;
  1025. }
  1026. Profiler.enter("updateConnectorHierarchy handle HasComponentsConnector");
  1027. if (parentConnector instanceof HasComponentsConnector) {
  1028. HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
  1029. List<ComponentConnector> oldComponents = ccc
  1030. .getChildComponents();
  1031. if (!Util.collectionsEquals(oldComponents,
  1032. newComponents)) {
  1033. // Fire change event if the hierarchy has
  1034. // changed
  1035. ConnectorHierarchyChangeEvent event = GWT
  1036. .create(ConnectorHierarchyChangeEvent.class);
  1037. event.setOldChildren(oldComponents);
  1038. event.setConnector(parentConnector);
  1039. ccc.setChildComponents(newComponents);
  1040. result.events.add(event);
  1041. }
  1042. } else if (!newComponents.isEmpty()) {
  1043. getLogger()
  1044. .severe("Hierachy claims "
  1045. + Util.getConnectorString(parentConnector)
  1046. + " has component children even though it isn't a HasComponentsConnector");
  1047. }
  1048. Profiler.leave("updateConnectorHierarchy handle HasComponentsConnector");
  1049. Profiler.enter("updateConnectorHierarchy setChildren");
  1050. parentConnector.setChildren(newChildren);
  1051. Profiler.leave("updateConnectorHierarchy setChildren");
  1052. Profiler.enter("updateConnectorHierarchy find removed children");
  1053. /*
  1054. * Find children removed from this parent and mark for
  1055. * removal unless they are already attached to some
  1056. * other parent.
  1057. */
  1058. for (ServerConnector oldChild : oldChildren) {
  1059. if (oldChild.getParent() != parentConnector) {
  1060. // Ignore if moved to some other connector
  1061. continue;
  1062. }
  1063. if (!newChildren.contains(oldChild)) {
  1064. /*
  1065. * Consider child detached for now, will be
  1066. * cleared if it is later on added to some other
  1067. * parent.
  1068. */
  1069. maybeDetached.add(oldChild.getConnectorId());
  1070. }
  1071. }
  1072. Profiler.leave("updateConnectorHierarchy find removed children");
  1073. } catch (final Throwable e) {
  1074. getLogger().log(Level.SEVERE,
  1075. "Error updating connector hierarchy", e);
  1076. } finally {
  1077. Profiler.leave("updateConnectorHierarchy hierarchy entry");
  1078. }
  1079. }
  1080. Profiler.enter("updateConnectorHierarchy detach removed connectors");
  1081. /*
  1082. * Connector is in maybeDetached at this point if it has been
  1083. * removed from its parent but not added to any other parent
  1084. */
  1085. JsArrayString maybeDetachedArray = maybeDetached.dump();
  1086. for (int i = 0; i < maybeDetachedArray.length(); i++) {
  1087. ServerConnector removed = getConnectorMap().getConnector(
  1088. maybeDetachedArray.get(i));
  1089. recursivelyDetach(removed, result.events,
  1090. result.detachedConnectorIds);
  1091. }
  1092. Profiler.leave("updateConnectorHierarchy detach removed connectors");
  1093. if (result.events.size() != 0) {
  1094. onlyNoLayoutUpdates = false;
  1095. }
  1096. Profiler.leave("updateConnectorHierarchy");
  1097. return result;
  1098. }
  1099. private void recursivelyDetach(ServerConnector connector,
  1100. JsArrayObject<ConnectorHierarchyChangeEvent> events,
  1101. FastStringSet detachedConnectors) {
  1102. detachedConnectors.add(connector.getConnectorId());
  1103. /*
  1104. * Reset state in an attempt to keep it consistent with the
  1105. * hierarchy. No children and no parent is the initial situation
  1106. * for the hierarchy, so changing the state to its initial value
  1107. * is the closest we can get without data from the server.
  1108. * #10151
  1109. */
  1110. String prefix = getClass().getSimpleName() + " ";
  1111. Profiler.enter(prefix + "recursivelyDetach reset state");
  1112. try {
  1113. Profiler.enter(prefix
  1114. + "recursivelyDetach reset state - getStateType");
  1115. Type stateType = AbstractConnector.getStateType(connector);
  1116. Profiler.leave(prefix
  1117. + "recursivelyDetach reset state - getStateType");
  1118. // Empty state instance to get default property values from
  1119. Profiler.enter(prefix
  1120. + "recursivelyDetach reset state - createInstance");
  1121. Object defaultState = stateType.createInstance();
  1122. Profiler.leave(prefix
  1123. + "recursivelyDetach reset state - createInstance");
  1124. if (connector instanceof AbstractConnector) {
  1125. // optimization as the loop setting properties is very
  1126. // slow, especially on IE8
  1127. replaceState((AbstractConnector) connector,
  1128. defaultState);
  1129. } else {
  1130. SharedState state = connector.getState();
  1131. Profiler.enter(prefix
  1132. + "recursivelyDetach reset state - properties");
  1133. JsArrayObject<Property> properties = stateType
  1134. .getPropertiesAsArray();
  1135. int size = properties.size();
  1136. for (int i = 0; i < size; i++) {
  1137. Property property = properties.get(i);
  1138. property.setValue(state,
  1139. property.getValue(defaultState));
  1140. }
  1141. Profiler.leave(prefix
  1142. + "recursivelyDetach reset state - properties");
  1143. }
  1144. } catch (NoDataException e) {
  1145. throw new RuntimeException("Can't reset state for "
  1146. + Util.getConnectorString(connector), e);
  1147. } finally {
  1148. Profiler.leave(prefix + "recursivelyDetach reset state");
  1149. }
  1150. Profiler.enter(prefix + "recursivelyDetach perform detach");
  1151. /*
  1152. * Recursively detach children to make sure they get
  1153. * setParent(null) and hierarchy change events as needed.
  1154. */
  1155. for (ServerConnector child : connector.getChildren()) {
  1156. /*
  1157. * Server doesn't send updated child data for removed
  1158. * connectors -> ignore child that still seems to be a child
  1159. * of this connector although it has been moved to some part
  1160. * of the hierarchy that is not detached.
  1161. */
  1162. if (child.getParent() != connector) {
  1163. continue;
  1164. }
  1165. recursivelyDetach(child, events, detachedConnectors);
  1166. }
  1167. Profiler.leave(prefix + "recursivelyDetach perform detach");
  1168. /*
  1169. * Clear child list and parent
  1170. */
  1171. Profiler.enter(prefix
  1172. + "recursivelyDetach clear children and parent");
  1173. connector
  1174. .setChildren(Collections.<ServerConnector> emptyList());
  1175. connector.setParent(null);
  1176. Profiler.leave(prefix
  1177. + "recursivelyDetach clear children and parent");
  1178. /*
  1179. * Create an artificial hierarchy event for containers to give
  1180. * it a chance to clean up after its children if it has any
  1181. */
  1182. Profiler.enter(prefix
  1183. + "recursivelyDetach create hierarchy event");
  1184. if (connector instanceof HasComponentsConnector) {
  1185. HasComponentsConnector ccc = (HasComponentsConnector) connector;
  1186. List<ComponentConnector> oldChildren = ccc
  1187. .getChildComponents();
  1188. if (!oldChildren.isEmpty()) {
  1189. /*
  1190. * HasComponentsConnector has a separate child component
  1191. * list that should also be cleared
  1192. */
  1193. ccc.setChildComponents(Collections
  1194. .<ComponentConnector> emptyList());
  1195. // Create event and add it to the list of pending events
  1196. ConnectorHierarchyChangeEvent event = GWT
  1197. .create(ConnectorHierarchyChangeEvent.class);
  1198. event.setConnector(connector);
  1199. event.setOldChildren(oldChildren);
  1200. events.add(event);
  1201. }
  1202. }
  1203. Profiler.leave(prefix
  1204. + "recursivelyDetach create hierarchy event");
  1205. }
  1206. private native void replaceState(AbstractConnector connector,
  1207. Object defaultState)
  1208. /*-{
  1209. connector.@com.vaadin.client.ui.AbstractConnector::state = defaultState;
  1210. }-*/;
  1211. private void handleRpcInvocations(ValueMap json) {
  1212. if (json.containsKey("rpc")) {
  1213. Profiler.enter("handleRpcInvocations");
  1214. getLogger()
  1215. .info(" * Performing server to client RPC calls");
  1216. JsonArray rpcCalls = Util.jso2json(json
  1217. .getJavaScriptObject("rpc"));
  1218. int rpcLength = rpcCalls.length();
  1219. for (int i = 0; i < rpcLength; i++) {
  1220. try {
  1221. JsonArray rpcCall = rpcCalls.getArray(i);
  1222. MethodInvocation invocation = getRpcManager()
  1223. .parseAndApplyInvocation(rpcCall,
  1224. connection);
  1225. if (onlyNoLayoutUpdates
  1226. && !RpcManager.getMethod(invocation)
  1227. .isNoLayout()) {
  1228. onlyNoLayoutUpdates = false;
  1229. }
  1230. } catch (final Throwable e) {
  1231. getLogger()
  1232. .log(Level.SEVERE,
  1233. "Error performing server to client RPC calls",
  1234. e);
  1235. }
  1236. }
  1237. Profiler.leave("handleRpcInvocations");
  1238. }
  1239. }
  1240. };
  1241. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  1242. }
  1243. private void endRequestIfResponse(ValueMap json) {
  1244. if (isResponse(json)) {
  1245. // End the request if the received message was a
  1246. // response, not sent asynchronously
  1247. getMessageSender().endRequest();
  1248. }
  1249. }
  1250. private boolean isResynchronize(ValueMap json) {
  1251. return json.containsKey(ApplicationConstants.RESYNCHRONIZE_ID);
  1252. }
  1253. private boolean isResponse(ValueMap json) {
  1254. ValueMap meta = json.getValueMap("meta");
  1255. if (meta == null || !meta.containsKey("async")) {
  1256. return true;
  1257. }
  1258. return false;
  1259. }
  1260. /**
  1261. * Checks if the given serverId is the one we are currently waiting for from
  1262. * the server
  1263. */
  1264. private boolean isNextExpectedMessage(int serverId) {
  1265. if (serverId == -1) {
  1266. return true;
  1267. }
  1268. if (serverId == getExpectedServerId()) {
  1269. return true;
  1270. }
  1271. if (lastSeenServerSyncId == UNDEFINED_SYNC_ID) {
  1272. // First message is always ok
  1273. return true;
  1274. }
  1275. return false;
  1276. }
  1277. private int getServerId(ValueMap json) {
  1278. if (json.containsKey(ApplicationConstants.SERVER_SYNC_ID)) {
  1279. return json.getInt(ApplicationConstants.SERVER_SYNC_ID);
  1280. } else {
  1281. return -1;
  1282. }
  1283. }
  1284. private int getExpectedServerId() {
  1285. return lastSeenServerSyncId + 1;
  1286. }
  1287. /**
  1288. * Timer used to make sure that no misbehaving components can delay response
  1289. * handling forever.
  1290. */
  1291. Timer forceHandleMessage = new Timer() {
  1292. @Override
  1293. public void run() {
  1294. if (!responseHandlingLocks.isEmpty()) {
  1295. // Lock which was never release -> bug in locker or things just
  1296. // too slow
  1297. getLogger()
  1298. .warning(
  1299. "WARNING: reponse handling was never resumed, forcibly removing locks...");
  1300. responseHandlingLocks.clear();
  1301. } else {
  1302. // Waited for out-of-order message which never arrived
  1303. // Do one final check and resynchronize if the message is not
  1304. // there. The final check is only a precaution as this timer
  1305. // should have been cancelled if the message has arrived
  1306. getLogger().warning(
  1307. "Gave up waiting for message " + getExpectedServerId()
  1308. + " from the server");
  1309. }
  1310. if (!handlePendingMessages() && !pendingUIDLMessages.isEmpty()) {
  1311. // There are messages but the next id was not found, likely it
  1312. // has been lost
  1313. // Drop pending messages and resynchronize
  1314. pendingUIDLMessages.clear();
  1315. getMessageSender().resynchronize();
  1316. }
  1317. }
  1318. };
  1319. /**
  1320. * This method can be used to postpone rendering of a response for a short
  1321. * period of time (e.g. to avoid the rendering process during animation).
  1322. *
  1323. * @param lock
  1324. */
  1325. public void suspendReponseHandling(Object lock) {
  1326. responseHandlingLocks.add(lock);
  1327. }
  1328. /**
  1329. * Resumes the rendering process once all locks have been removed.
  1330. *
  1331. * @param lock
  1332. */
  1333. public void resumeResponseHandling(Object lock) {
  1334. responseHandlingLocks.remove(lock);
  1335. if (responseHandlingLocks.isEmpty()) {
  1336. // Cancel timer that breaks the lock
  1337. forceHandleMessage.cancel();
  1338. if (!pendingUIDLMessages.isEmpty()) {
  1339. getLogger()
  1340. .info("No more response handling locks, handling pending requests.");
  1341. handlePendingMessages();
  1342. }
  1343. }
  1344. }
  1345. private static native final int calculateBootstrapTime()
  1346. /*-{
  1347. if ($wnd.performance && $wnd.performance.timing) {
  1348. return (new Date).getTime() - $wnd.performance.timing.responseStart;
  1349. } else {
  1350. // performance.timing not supported
  1351. return -1;
  1352. }
  1353. }-*/;
  1354. /**
  1355. * Finds the next pending UIDL message and handles it (next pending is
  1356. * decided based on the server id)
  1357. *
  1358. * @return true if a message was handled, false otherwise
  1359. */
  1360. private boolean handlePendingMessages() {
  1361. if (pendingUIDLMessages.isEmpty()) {
  1362. return false;
  1363. }
  1364. // Try to find the next expected message
  1365. PendingUIDLMessage toHandle = null;
  1366. for (PendingUIDLMessage message : pendingUIDLMessages) {
  1367. if (isNextExpectedMessage(getServerId(message.json))) {
  1368. toHandle = message;
  1369. break;
  1370. }
  1371. }
  1372. if (toHandle != null) {
  1373. pendingUIDLMessages.remove(toHandle);
  1374. handleJSON(toHandle.getJson());
  1375. // Any remaining messages will be handled when this is called
  1376. // again at the end of handleJSON
  1377. return true;
  1378. } else {
  1379. return false;
  1380. }
  1381. }
  1382. private void removeOldPendingMessages() {
  1383. Iterator<PendingUIDLMessage> i = pendingUIDLMessages.iterator();
  1384. while (i.hasNext()) {
  1385. PendingUIDLMessage m = i.next();
  1386. int serverId = getServerId(m.json);
  1387. if (serverId != -1 && serverId < getExpectedServerId()) {
  1388. getLogger().info("Removing old message with id " + serverId);
  1389. i.remove();
  1390. }
  1391. }
  1392. }
  1393. /**
  1394. * Gets the server id included in the last received response.
  1395. * <p>
  1396. * This id can be used by connectors to determine whether new data has been
  1397. * received from the server to avoid doing the same calculations multiple
  1398. * times.
  1399. * <p>
  1400. * No guarantees are made for the structure of the id other than that there
  1401. * will be a new unique value every time a new response with data from the
  1402. * server is received.
  1403. * <p>
  1404. * The initial id when no request has yet been processed is -1.
  1405. *
  1406. * @return an id identifying the response
  1407. */
  1408. public int getLastSeenServerSyncId() {
  1409. return lastSeenServerSyncId;
  1410. }
  1411. /**
  1412. * Gets the token (aka double submit cookie) that the server uses to protect
  1413. * against Cross Site Request Forgery attacks.
  1414. *
  1415. * @return the CSRF token string
  1416. */
  1417. public String getCsrfToken() {
  1418. return csrfToken;
  1419. }
  1420. /**
  1421. * Checks whether state changes are currently being processed. Certain
  1422. * operations are not allowed when the internal state of the application
  1423. * might be in an inconsistent state because some state changes have been
  1424. * applied but others not. This includes running layotus.
  1425. *
  1426. * @return <code>true</code> if the internal state might be inconsistent
  1427. * because changes are being processed; <code>false</code> if the
  1428. * state should be consistent
  1429. */
  1430. public boolean isUpdatingState() {
  1431. return updatingState;
  1432. }
  1433. /**
  1434. * Checks if the first UIDL has been handled
  1435. *
  1436. * @return true if the initial UIDL has already been processed, false
  1437. * otherwise
  1438. */
  1439. public boolean isInitialUidlHandled() {
  1440. return bootstrapTime != 0;
  1441. }
  1442. private LayoutManager getLayoutManager() {
  1443. return LayoutManager.get(connection);
  1444. }
  1445. private ConnectorMap getConnectorMap() {
  1446. return ConnectorMap.get(connection);
  1447. }
  1448. private UIConnector getUIConnector() {
  1449. return connection.getUIConnector();
  1450. }
  1451. private RpcManager getRpcManager() {
  1452. return connection.getRpcManager();
  1453. }
  1454. private MessageSender getMessageSender() {
  1455. return connection.getMessageSender();
  1456. }
  1457. /**
  1458. * Strips the JSON wrapping from the given json string with wrapping.
  1459. *
  1460. * If the given string is not wrapped as expected, returns null
  1461. *
  1462. * @since 7.6
  1463. * @param jsonWithWrapping
  1464. * the JSON received from the server
  1465. * @return an unwrapped JSON string or null if the given string was not
  1466. * wrapped
  1467. */
  1468. public static String stripJSONWrapping(String jsonWithWrapping) {
  1469. if (jsonWithWrapping == null) {
  1470. return null;
  1471. }
  1472. if (!jsonWithWrapping.startsWith(JSON_COMMUNICATION_PREFIX)
  1473. || !jsonWithWrapping.endsWith(JSON_COMMUNICATION_SUFFIX)) {
  1474. return null;
  1475. }
  1476. return jsonWithWrapping.substring(JSON_COMMUNICATION_PREFIX.length(),
  1477. jsonWithWrapping.length() - JSON_COMMUNICATION_SUFFIX.length());
  1478. }
  1479. /**
  1480. * Unwraps and parses the given JSON, originating from the server
  1481. *
  1482. * @param jsonText
  1483. * the json from the server
  1484. * @return A parsed ValueMap or null if the input could not be parsed (or
  1485. * was null)
  1486. */
  1487. public static ValueMap parseJson(String jsonText) {
  1488. if (jsonText == null) {
  1489. return null;
  1490. }
  1491. final double start = Profiler.getRelativeTimeMillis();
  1492. try {
  1493. ValueMap json = parseJSONResponse(jsonText);
  1494. getLogger().info(
  1495. "JSON parsing took "
  1496. + Util.round(Profiler.getRelativeTimeMillis()
  1497. - start, 3) + "ms");
  1498. return json;
  1499. } catch (final Exception e) {
  1500. getLogger().severe("Unable to parse JSON: " + jsonText);
  1501. return null;
  1502. }
  1503. }
  1504. private static native ValueMap parseJSONResponse(String jsonText)
  1505. /*-{
  1506. return JSON.parse(jsonText);
  1507. }-*/;
  1508. /**
  1509. * Parse the given wrapped JSON, received from the server, to a ValueMap
  1510. *
  1511. * @param wrappedJsonText
  1512. * the json, wrapped as done by the server
  1513. * @return a ValueMap, or null if the wrapping was incorrect or json could
  1514. * not be parsed
  1515. */
  1516. public static ValueMap parseWrappedJson(String wrappedJsonText) {
  1517. return parseJson(stripJSONWrapping(wrappedJsonText));
  1518. }
  1519. private static final native double getFetchStartTime()
  1520. /*-{
  1521. if ($wnd.performance && $wnd.performance.timing && $wnd.performance.timing.fetchStart) {
  1522. return $wnd.performance.timing.fetchStart;
  1523. } else {
  1524. return 0;
  1525. }
  1526. }-*/;
  1527. }