You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MessageHandler.java 76KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  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. int removed = unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  429. if (removed > 0 && !isResponse(json)) {
  430. // Must acknowledge the removal using an XHR or server
  431. // memory usage will keep growing
  432. getUIConnector().sendAck();
  433. }
  434. getLogger()
  435. .info("handleUIDLMessage: "
  436. + (Duration.currentTimeMillis() - processUidlStart)
  437. + " ms");
  438. updatingState = false;
  439. Profiler.enter("Layout processing");
  440. try {
  441. LayoutManager layoutManager = getLayoutManager();
  442. if (!onlyNoLayoutUpdates) {
  443. layoutManager.setEverythingNeedsMeasure();
  444. }
  445. if (layoutManager.isLayoutNeeded()) {
  446. layoutManager.layoutNow();
  447. }
  448. } catch (final Throwable e) {
  449. getLogger()
  450. .log(Level.SEVERE, "Error processing layouts", e);
  451. }
  452. Profiler.leave("Layout processing");
  453. if (ApplicationConfiguration.isDebugMode()) {
  454. Profiler.enter("Dumping state changes to the console");
  455. getLogger().info(" * Dumping state changes to the console");
  456. VConsole.dirUIDL(json, connection);
  457. Profiler.leave("Dumping state changes to the console");
  458. }
  459. if (meta != null) {
  460. Profiler.enter("Error handling");
  461. if (meta.containsKey("appError")) {
  462. ValueMap error = meta.getValueMap("appError");
  463. VNotification.showError(connection,
  464. error.getString("caption"),
  465. error.getString("message"),
  466. error.getString("details"),
  467. error.getString("url"));
  468. connection.setApplicationRunning(false);
  469. }
  470. Profiler.leave("Error handling");
  471. }
  472. // TODO build profiling for widget impl loading time
  473. lastProcessingTime = (int) ((new Date().getTime()) - start
  474. .getTime());
  475. totalProcessingTime += lastProcessingTime;
  476. if (bootstrapTime == 0) {
  477. double fetchStart = getFetchStartTime();
  478. if (fetchStart != 0) {
  479. int time = (int) (Duration.currentTimeMillis() - fetchStart);
  480. getLogger().log(
  481. Level.INFO,
  482. "First response processed " + time
  483. + " ms after fetchStart");
  484. }
  485. bootstrapTime = calculateBootstrapTime();
  486. if (Profiler.isEnabled() && bootstrapTime != -1) {
  487. Profiler.logBootstrapTimings();
  488. }
  489. }
  490. getLogger().info(
  491. " Processing time was "
  492. + String.valueOf(lastProcessingTime) + "ms");
  493. getLogger().info(
  494. "Referenced paintables: " + getConnectorMap().size());
  495. endRequestIfResponse(json);
  496. resumeResponseHandling(lock);
  497. if (Profiler.isEnabled()) {
  498. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  499. @Override
  500. public void execute() {
  501. Profiler.logTimings();
  502. Profiler.reset();
  503. }
  504. });
  505. }
  506. }
  507. /**
  508. * Properly clean up any old stuff to ensure everything is properly
  509. * reinitialized.
  510. */
  511. private void prepareRepaintAll() {
  512. String uiConnectorId = getUIConnector().getConnectorId();
  513. if (uiConnectorId == null) {
  514. // Nothing to clear yet
  515. return;
  516. }
  517. // Create fake server response that says that the uiConnector
  518. // has no children
  519. JsonObject fakeHierarchy = Json.createObject();
  520. fakeHierarchy.put(uiConnectorId, Json.createArray());
  521. JsonObject fakeJson = Json.createObject();
  522. fakeJson.put("hierarchy", fakeHierarchy);
  523. ValueMap fakeValueMap = ((JavaScriptObject) fakeJson.toNative())
  524. .cast();
  525. // Update hierarchy based on the fake response
  526. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
  527. // Send hierarchy events based on the fake update
  528. sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
  529. // Unregister all the old connectors that have now been removed
  530. unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  531. getLayoutManager().cleanMeasuredSizes();
  532. }
  533. private void updateCaptions(
  534. JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
  535. FastStringSet parentChangedIds) {
  536. Profiler.enter("updateCaptions");
  537. /*
  538. * Find all components that might need a caption update based on
  539. * pending state and hierarchy changes
  540. */
  541. FastStringSet needsCaptionUpdate = FastStringSet.create();
  542. needsCaptionUpdate.addAll(parentChangedIds);
  543. // Find components with potentially changed caption state
  544. int size = pendingStateChangeEvents.size();
  545. for (int i = 0; i < size; i++) {
  546. StateChangeEvent event = pendingStateChangeEvents.get(i);
  547. if (VCaption.mightChange(event)) {
  548. ServerConnector connector = event.getConnector();
  549. needsCaptionUpdate.add(connector.getConnectorId());
  550. }
  551. }
  552. ConnectorMap connectorMap = getConnectorMap();
  553. // Update captions for all suitable candidates
  554. JsArrayString dump = needsCaptionUpdate.dump();
  555. int needsUpdateLength = dump.length();
  556. for (int i = 0; i < needsUpdateLength; i++) {
  557. String childId = dump.get(i);
  558. ServerConnector child = connectorMap.getConnector(childId);
  559. if (child instanceof ComponentConnector
  560. && ((ComponentConnector) child)
  561. .delegateCaptionHandling()) {
  562. ServerConnector parent = child.getParent();
  563. if (parent instanceof HasComponentsConnector) {
  564. Profiler.enter("HasComponentsConnector.updateCaption");
  565. ((HasComponentsConnector) parent)
  566. .updateCaption((ComponentConnector) child);
  567. Profiler.leave("HasComponentsConnector.updateCaption");
  568. }
  569. }
  570. }
  571. Profiler.leave("updateCaptions");
  572. }
  573. private void delegateToWidget(
  574. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  575. Profiler.enter("@DelegateToWidget");
  576. getLogger().info(" * Running @DelegateToWidget");
  577. // Keep track of types that have no @DelegateToWidget in their
  578. // state to optimize performance
  579. FastStringSet noOpTypes = FastStringSet.create();
  580. int size = pendingStateChangeEvents.size();
  581. for (int eventIndex = 0; eventIndex < size; eventIndex++) {
  582. StateChangeEvent sce = pendingStateChangeEvents
  583. .get(eventIndex);
  584. ServerConnector connector = sce.getConnector();
  585. if (connector instanceof ComponentConnector) {
  586. String className = connector.getClass().getName();
  587. if (noOpTypes.contains(className)) {
  588. continue;
  589. }
  590. ComponentConnector component = (ComponentConnector) connector;
  591. Type stateType = AbstractConnector
  592. .getStateType(component);
  593. JsArrayString delegateToWidgetProperties = stateType
  594. .getDelegateToWidgetProperties();
  595. if (delegateToWidgetProperties == null) {
  596. noOpTypes.add(className);
  597. continue;
  598. }
  599. int length = delegateToWidgetProperties.length();
  600. for (int i = 0; i < length; i++) {
  601. String propertyName = delegateToWidgetProperties
  602. .get(i);
  603. if (sce.hasPropertyChanged(propertyName)) {
  604. Property property = stateType
  605. .getProperty(propertyName);
  606. String method = property
  607. .getDelegateToWidgetMethodName();
  608. Profiler.enter("doDelegateToWidget");
  609. doDelegateToWidget(component, property, method);
  610. Profiler.leave("doDelegateToWidget");
  611. }
  612. }
  613. }
  614. }
  615. Profiler.leave("@DelegateToWidget");
  616. }
  617. private void doDelegateToWidget(ComponentConnector component,
  618. Property property, String methodName) {
  619. Type type = TypeData.getType(component.getClass());
  620. try {
  621. Type widgetType = type.getMethod("getWidget")
  622. .getReturnType();
  623. Widget widget = component.getWidget();
  624. Object propertyValue = property.getValue(component
  625. .getState());
  626. widgetType.getMethod(methodName).invoke(widget,
  627. propertyValue);
  628. } catch (NoDataException e) {
  629. throw new RuntimeException(
  630. "Missing data needed to invoke @DelegateToWidget for "
  631. + component.getClass().getSimpleName(), e);
  632. }
  633. }
  634. /**
  635. * Sends the state change events created while updating the state
  636. * information.
  637. *
  638. * This must be called after hierarchy change listeners have been
  639. * called. At least caption updates for the parent are strange if
  640. * fired from state change listeners and thus calls the parent
  641. * BEFORE the parent is aware of the child (through a
  642. * ConnectorHierarchyChangedEvent)
  643. *
  644. * @param pendingStateChangeEvents
  645. * The events to send
  646. */
  647. private void sendStateChangeEvents(
  648. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  649. Profiler.enter("sendStateChangeEvents");
  650. getLogger().info(" * Sending state change events");
  651. int size = pendingStateChangeEvents.size();
  652. for (int i = 0; i < size; i++) {
  653. StateChangeEvent sce = pendingStateChangeEvents.get(i);
  654. try {
  655. sce.getConnector().fireEvent(sce);
  656. } catch (final Throwable e) {
  657. getLogger().log(Level.SEVERE,
  658. "Error sending state change events", e);
  659. }
  660. }
  661. Profiler.leave("sendStateChangeEvents");
  662. }
  663. private void verifyConnectorHierarchy() {
  664. Profiler.enter("verifyConnectorHierarchy - this is only performed in debug mode");
  665. JsArrayObject<ServerConnector> currentConnectors = getConnectorMap()
  666. .getConnectorsAsJsArray();
  667. int size = currentConnectors.size();
  668. for (int i = 0; i < size; i++) {
  669. ServerConnector c = currentConnectors.get(i);
  670. if (c.getParent() != null) {
  671. if (!c.getParent().getChildren().contains(c)) {
  672. getLogger()
  673. .severe("ERROR: Connector "
  674. + c.getConnectorId()
  675. + " is connected to a parent but the parent ("
  676. + c.getParent().getConnectorId()
  677. + ") does not contain the connector");
  678. }
  679. } else if (c == getUIConnector()) {
  680. // UIConnector for this connection, ignore
  681. } else if (c instanceof WindowConnector
  682. && getUIConnector().hasSubWindow(
  683. (WindowConnector) c)) {
  684. // Sub window attached to this UIConnector, ignore
  685. } else {
  686. // The connector has been detached from the
  687. // hierarchy but was not unregistered.
  688. getLogger()
  689. .severe("ERROR: Connector "
  690. + c.getConnectorId()
  691. + " is not attached to a parent but has not been unregistered");
  692. }
  693. }
  694. Profiler.leave("verifyConnectorHierarchy - this is only performed in debug mode");
  695. }
  696. private int unregisterRemovedConnectors(
  697. FastStringSet detachedConnectors) {
  698. Profiler.enter("unregisterRemovedConnectors");
  699. JsArrayString detachedArray = detachedConnectors.dump();
  700. int nrDetached = detachedArray.length();
  701. for (int i = 0; i < nrDetached; i++) {
  702. ServerConnector connector = getConnectorMap().getConnector(
  703. detachedArray.get(i));
  704. Profiler.enter("unregisterRemovedConnectors unregisterConnector");
  705. getConnectorMap().unregisterConnector(connector);
  706. Profiler.leave("unregisterRemovedConnectors unregisterConnector");
  707. }
  708. if (ApplicationConfiguration.isDebugMode()) {
  709. // Do some extra checking if we're in debug mode (i.e. debug
  710. // window is open)
  711. verifyConnectorHierarchy();
  712. }
  713. getLogger()
  714. .info("* Unregistered " + nrDetached + " connectors");
  715. Profiler.leave("unregisterRemovedConnectors");
  716. return nrDetached;
  717. }
  718. private JsArrayString createConnectorsIfNeeded(ValueMap json) {
  719. getLogger().info(" * Creating connectors (if needed)");
  720. JsArrayString createdConnectors = JavaScriptObject
  721. .createArray().cast();
  722. if (!json.containsKey("types")) {
  723. return createdConnectors;
  724. }
  725. Profiler.enter("Creating connectors");
  726. ValueMap types = json.getValueMap("types");
  727. JsArrayString keyArray = types.getKeyArray();
  728. for (int i = 0; i < keyArray.length(); i++) {
  729. try {
  730. String connectorId = keyArray.get(i);
  731. ServerConnector connector = getConnectorMap()
  732. .getConnector(connectorId);
  733. if (connector != null) {
  734. continue;
  735. }
  736. // Always do layouts if there's at least one new
  737. // connector
  738. onlyNoLayoutUpdates = false;
  739. int connectorType = Integer.parseInt(types
  740. .getString(connectorId));
  741. Class<? extends ServerConnector> connectorClass = connection
  742. .getConfiguration()
  743. .getConnectorClassByEncodedTag(connectorType);
  744. // Connector does not exist so we must create it
  745. if (connectorClass != getUIConnector().getClass()) {
  746. // create, initialize and register the paintable
  747. Profiler.enter("ApplicationConnection.getConnector");
  748. connector = connection.getConnector(connectorId,
  749. connectorType);
  750. Profiler.leave("ApplicationConnection.getConnector");
  751. createdConnectors.push(connectorId);
  752. } else {
  753. // First UIConnector update. Before this the
  754. // UIConnector has been created but not
  755. // initialized as the connector id has not been
  756. // known
  757. getConnectorMap().registerConnector(connectorId,
  758. getUIConnector());
  759. getUIConnector().doInit(connectorId, connection);
  760. createdConnectors.push(connectorId);
  761. }
  762. } catch (final Throwable e) {
  763. getLogger().log(Level.SEVERE,
  764. "Error handling type data", e);
  765. }
  766. }
  767. Profiler.leave("Creating connectors");
  768. return createdConnectors;
  769. }
  770. private void updateVaadin6StyleConnectors(ValueMap json) {
  771. Profiler.enter("updateVaadin6StyleConnectors");
  772. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  773. int length = changes.length();
  774. // Must always do layout if there's even a single legacy update
  775. if (length != 0) {
  776. onlyNoLayoutUpdates = false;
  777. }
  778. getLogger()
  779. .info(" * Passing UIDL to Vaadin 6 style connectors");
  780. // update paintables
  781. for (int i = 0; i < length; i++) {
  782. try {
  783. final UIDL change = changes.get(i).cast();
  784. final UIDL uidl = change.getChildUIDL(0);
  785. String connectorId = uidl.getId();
  786. final ComponentConnector legacyConnector = (ComponentConnector) getConnectorMap()
  787. .getConnector(connectorId);
  788. if (legacyConnector instanceof Paintable) {
  789. String key = null;
  790. if (Profiler.isEnabled()) {
  791. key = "updateFromUIDL for "
  792. + legacyConnector.getClass()
  793. .getSimpleName();
  794. Profiler.enter(key);
  795. }
  796. ((Paintable) legacyConnector).updateFromUIDL(uidl,
  797. connection);
  798. if (Profiler.isEnabled()) {
  799. Profiler.leave(key);
  800. }
  801. } else if (legacyConnector == null) {
  802. getLogger()
  803. .severe("Received update for "
  804. + uidl.getTag()
  805. + ", but there is no such paintable ("
  806. + connectorId + ") rendered.");
  807. } else {
  808. getLogger()
  809. .severe("Server sent Vaadin 6 style updates for "
  810. + Util.getConnectorString(legacyConnector)
  811. + " but this is not a Vaadin 6 Paintable");
  812. }
  813. } catch (final Throwable e) {
  814. getLogger().log(Level.SEVERE, "Error handling UIDL", e);
  815. }
  816. }
  817. Profiler.leave("updateVaadin6StyleConnectors");
  818. }
  819. private void sendHierarchyChangeEvents(
  820. JsArrayObject<ConnectorHierarchyChangeEvent> events) {
  821. int eventCount = events.size();
  822. if (eventCount == 0) {
  823. return;
  824. }
  825. Profiler.enter("sendHierarchyChangeEvents");
  826. getLogger().info(" * Sending hierarchy change events");
  827. for (int i = 0; i < eventCount; i++) {
  828. ConnectorHierarchyChangeEvent event = events.get(i);
  829. try {
  830. logHierarchyChange(event);
  831. event.getConnector().fireEvent(event);
  832. } catch (final Throwable e) {
  833. getLogger().log(Level.SEVERE,
  834. "Error sending hierarchy change events", e);
  835. }
  836. }
  837. Profiler.leave("sendHierarchyChangeEvents");
  838. }
  839. private void logHierarchyChange(ConnectorHierarchyChangeEvent event) {
  840. if (true) {
  841. // Always disabled for now. Can be enabled manually
  842. return;
  843. }
  844. getLogger()
  845. .info("Hierarchy changed for "
  846. + Util.getConnectorString(event.getConnector()));
  847. String oldChildren = "* Old children: ";
  848. for (ComponentConnector child : event.getOldChildren()) {
  849. oldChildren += Util.getConnectorString(child) + " ";
  850. }
  851. getLogger().info(oldChildren);
  852. String newChildren = "* New children: ";
  853. HasComponentsConnector parent = (HasComponentsConnector) event
  854. .getConnector();
  855. for (ComponentConnector child : parent.getChildComponents()) {
  856. newChildren += Util.getConnectorString(child) + " ";
  857. }
  858. getLogger().info(newChildren);
  859. }
  860. private JsArrayObject<StateChangeEvent> updateConnectorState(
  861. ValueMap json, JsArrayString createdConnectorIds) {
  862. JsArrayObject<StateChangeEvent> events = JavaScriptObject
  863. .createArray().cast();
  864. getLogger().info(" * Updating connector states");
  865. if (!json.containsKey("state")) {
  866. return events;
  867. }
  868. Profiler.enter("updateConnectorState");
  869. FastStringSet remainingNewConnectors = FastStringSet.create();
  870. remainingNewConnectors.addAll(createdConnectorIds);
  871. // set states for all paintables mentioned in "state"
  872. ValueMap states = json.getValueMap("state");
  873. JsArrayString keyArray = states.getKeyArray();
  874. for (int i = 0; i < keyArray.length(); i++) {
  875. try {
  876. String connectorId = keyArray.get(i);
  877. ServerConnector connector = getConnectorMap()
  878. .getConnector(connectorId);
  879. if (null != connector) {
  880. Profiler.enter("updateConnectorState inner loop");
  881. if (Profiler.isEnabled()) {
  882. Profiler.enter("Decode connector state "
  883. + connector.getClass().getSimpleName());
  884. }
  885. JavaScriptObject jso = states
  886. .getJavaScriptObject(connectorId);
  887. JsonObject stateJson = Util.jso2json(jso);
  888. if (connector instanceof HasJavaScriptConnectorHelper) {
  889. ((HasJavaScriptConnectorHelper) connector)
  890. .getJavascriptConnectorHelper()
  891. .setNativeState(jso);
  892. }
  893. SharedState state = connector.getState();
  894. Type stateType = new Type(state.getClass()
  895. .getName(), null);
  896. if (onlyNoLayoutUpdates) {
  897. Profiler.enter("updateConnectorState @NoLayout handling");
  898. for (String propertyName : stateJson.keys()) {
  899. Property property = stateType
  900. .getProperty(propertyName);
  901. if (!property.isNoLayout()) {
  902. onlyNoLayoutUpdates = false;
  903. break;
  904. }
  905. }
  906. Profiler.leave("updateConnectorState @NoLayout handling");
  907. }
  908. Profiler.enter("updateConnectorState decodeValue");
  909. JsonDecoder.decodeValue(stateType, stateJson,
  910. state, connection);
  911. Profiler.leave("updateConnectorState decodeValue");
  912. if (Profiler.isEnabled()) {
  913. Profiler.leave("Decode connector state "
  914. + connector.getClass().getSimpleName());
  915. }
  916. Profiler.enter("updateConnectorState create event");
  917. boolean isNewConnector = remainingNewConnectors
  918. .contains(connectorId);
  919. if (isNewConnector) {
  920. remainingNewConnectors.remove(connectorId);
  921. }
  922. StateChangeEvent event = new StateChangeEvent(
  923. connector, stateJson, isNewConnector);
  924. events.add(event);
  925. Profiler.leave("updateConnectorState create event");
  926. Profiler.leave("updateConnectorState inner loop");
  927. }
  928. } catch (final Throwable e) {
  929. getLogger().log(Level.SEVERE,
  930. "Error updating connector states", e);
  931. }
  932. }
  933. Profiler.enter("updateConnectorState newWithoutState");
  934. // Fire events for properties using the default value for newly
  935. // created connectors even if there were no state changes
  936. JsArrayString dump = remainingNewConnectors.dump();
  937. int length = dump.length();
  938. for (int i = 0; i < length; i++) {
  939. String connectorId = dump.get(i);
  940. ServerConnector connector = getConnectorMap().getConnector(
  941. connectorId);
  942. StateChangeEvent event = new StateChangeEvent(connector,
  943. Json.createObject(), true);
  944. events.add(event);
  945. }
  946. Profiler.leave("updateConnectorState newWithoutState");
  947. Profiler.leave("updateConnectorState");
  948. return events;
  949. }
  950. /**
  951. * Updates the connector hierarchy and returns a list of events that
  952. * should be fired after update of the hierarchy and the state is
  953. * done.
  954. *
  955. * @param json
  956. * The JSON containing the hierarchy information
  957. * @return A collection of events that should be fired when update
  958. * of hierarchy and state is complete and a list of all
  959. * connectors for which the parent has changed
  960. */
  961. private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
  962. ValueMap json) {
  963. ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
  964. getLogger().info(" * Updating connector hierarchy");
  965. Profiler.enter("updateConnectorHierarchy");
  966. FastStringSet maybeDetached = FastStringSet.create();
  967. FastStringSet hasHierarchy = FastStringSet.create();
  968. // Process regular hierarchy data
  969. if (json.containsKey("hierarchy")) {
  970. ValueMap hierarchies = json.getValueMap("hierarchy");
  971. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  972. for (int i = 0; i < hierarchyKeys.length(); i++) {
  973. String connectorId = hierarchyKeys.get(i);
  974. JsArrayString childConnectorIds = hierarchies
  975. .getJSStringArray(connectorId);
  976. hasHierarchy.add(connectorId);
  977. updateConnectorHierarchy(connectorId,
  978. childConnectorIds, maybeDetached, result);
  979. }
  980. }
  981. // Assume empty hierarchy for connectors with state updates but
  982. // no hierarchy data
  983. if (json.containsKey("state")) {
  984. JsArrayString stateKeys = json.getValueMap("state")
  985. .getKeyArray();
  986. JsArrayString emptyArray = JavaScriptObject.createArray()
  987. .cast();
  988. for (int i = 0; i < stateKeys.length(); i++) {
  989. String connectorId = stateKeys.get(i);
  990. if (!hasHierarchy.contains(connectorId)) {
  991. updateConnectorHierarchy(connectorId, emptyArray,
  992. maybeDetached, result);
  993. }
  994. }
  995. }
  996. Profiler.enter("updateConnectorHierarchy detach removed connectors");
  997. /*
  998. * Connector is in maybeDetached at this point if it has been
  999. * removed from its parent but not added to any other parent
  1000. */
  1001. JsArrayString maybeDetachedArray = maybeDetached.dump();
  1002. for (int i = 0; i < maybeDetachedArray.length(); i++) {
  1003. ServerConnector removed = getConnectorMap().getConnector(
  1004. maybeDetachedArray.get(i));
  1005. recursivelyDetach(removed, result.events,
  1006. result.detachedConnectorIds);
  1007. }
  1008. Profiler.leave("updateConnectorHierarchy detach removed connectors");
  1009. if (result.events.size() != 0) {
  1010. onlyNoLayoutUpdates = false;
  1011. }
  1012. Profiler.leave("updateConnectorHierarchy");
  1013. return result;
  1014. }
  1015. /**
  1016. * Updates the hierarchy for a connector
  1017. *
  1018. * @param connectorId
  1019. * the id of the connector to update
  1020. * @param childConnectorIds
  1021. * array of child connector ids
  1022. * @param maybeDetached
  1023. * set of connectors that are maybe detached
  1024. * @param result
  1025. * the hierarchy update result
  1026. */
  1027. private void updateConnectorHierarchy(String connectorId,
  1028. JsArrayString childConnectorIds,
  1029. FastStringSet maybeDetached,
  1030. ConnectorHierarchyUpdateResult result) {
  1031. try {
  1032. Profiler.enter("updateConnectorHierarchy hierarchy entry");
  1033. ConnectorMap connectorMap = getConnectorMap();
  1034. ServerConnector parentConnector = connectorMap
  1035. .getConnector(connectorId);
  1036. int childConnectorSize = childConnectorIds.length();
  1037. Profiler.enter("updateConnectorHierarchy find new connectors");
  1038. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  1039. List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
  1040. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  1041. String childConnectorId = childConnectorIds
  1042. .get(connectorIndex);
  1043. ServerConnector childConnector = connectorMap
  1044. .getConnector(childConnectorId);
  1045. if (childConnector == null) {
  1046. getLogger()
  1047. .severe("Hierarchy claims that "
  1048. + childConnectorId
  1049. + " is a child for "
  1050. + connectorId
  1051. + " ("
  1052. + parentConnector.getClass()
  1053. .getName()
  1054. + ") but no connector with id "
  1055. + childConnectorId
  1056. + " has been registered. "
  1057. + "More information might be available in the server-side log if assertions are enabled");
  1058. continue;
  1059. }
  1060. newChildren.add(childConnector);
  1061. if (childConnector instanceof ComponentConnector) {
  1062. newComponents
  1063. .add((ComponentConnector) childConnector);
  1064. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  1065. throw new IllegalStateException(
  1066. Util.getConnectorString(childConnector)
  1067. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  1068. }
  1069. if (childConnector.getParent() != parentConnector) {
  1070. childConnector.setParent(parentConnector);
  1071. result.parentChangedIds.add(childConnectorId);
  1072. // Not detached even if previously removed from
  1073. // parent
  1074. maybeDetached.remove(childConnectorId);
  1075. }
  1076. }
  1077. Profiler.leave("updateConnectorHierarchy find new connectors");
  1078. // TODO This check should be done on the server side in
  1079. // the future so the hierarchy update is only sent when
  1080. // something actually has changed
  1081. List<ServerConnector> oldChildren = parentConnector
  1082. .getChildren();
  1083. boolean actuallyChanged = !Util.collectionsEquals(
  1084. oldChildren, newChildren);
  1085. if (!actuallyChanged) {
  1086. return;
  1087. }
  1088. Profiler.enter("updateConnectorHierarchy handle HasComponentsConnector");
  1089. if (parentConnector instanceof HasComponentsConnector) {
  1090. HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
  1091. List<ComponentConnector> oldComponents = ccc
  1092. .getChildComponents();
  1093. if (!Util.collectionsEquals(oldComponents,
  1094. newComponents)) {
  1095. // Fire change event if the hierarchy has
  1096. // changed
  1097. ConnectorHierarchyChangeEvent event = GWT
  1098. .create(ConnectorHierarchyChangeEvent.class);
  1099. event.setOldChildren(oldComponents);
  1100. event.setConnector(parentConnector);
  1101. ccc.setChildComponents(newComponents);
  1102. result.events.add(event);
  1103. }
  1104. } else if (!newComponents.isEmpty()) {
  1105. getLogger()
  1106. .severe("Hierachy claims "
  1107. + Util.getConnectorString(parentConnector)
  1108. + " has component children even though it isn't a HasComponentsConnector");
  1109. }
  1110. Profiler.leave("updateConnectorHierarchy handle HasComponentsConnector");
  1111. Profiler.enter("updateConnectorHierarchy setChildren");
  1112. parentConnector.setChildren(newChildren);
  1113. Profiler.leave("updateConnectorHierarchy setChildren");
  1114. Profiler.enter("updateConnectorHierarchy find removed children");
  1115. /*
  1116. * Find children removed from this parent and mark for
  1117. * removal unless they are already attached to some other
  1118. * parent.
  1119. */
  1120. for (ServerConnector oldChild : oldChildren) {
  1121. if (oldChild.getParent() != parentConnector) {
  1122. // Ignore if moved to some other connector
  1123. continue;
  1124. }
  1125. if (!newChildren.contains(oldChild)) {
  1126. /*
  1127. * Consider child detached for now, will be cleared
  1128. * if it is later on added to some other parent.
  1129. */
  1130. maybeDetached.add(oldChild.getConnectorId());
  1131. }
  1132. }
  1133. Profiler.leave("updateConnectorHierarchy find removed children");
  1134. } catch (final Throwable e) {
  1135. getLogger().log(Level.SEVERE,
  1136. "Error updating connector hierarchy", e);
  1137. } finally {
  1138. Profiler.leave("updateConnectorHierarchy hierarchy entry");
  1139. }
  1140. }
  1141. private void recursivelyDetach(ServerConnector connector,
  1142. JsArrayObject<ConnectorHierarchyChangeEvent> events,
  1143. FastStringSet detachedConnectors) {
  1144. detachedConnectors.add(connector.getConnectorId());
  1145. /*
  1146. * Reset state in an attempt to keep it consistent with the
  1147. * hierarchy. No children and no parent is the initial situation
  1148. * for the hierarchy, so changing the state to its initial value
  1149. * is the closest we can get without data from the server.
  1150. * #10151
  1151. */
  1152. String prefix = getClass().getSimpleName() + " ";
  1153. Profiler.enter(prefix + "recursivelyDetach reset state");
  1154. try {
  1155. Profiler.enter(prefix
  1156. + "recursivelyDetach reset state - getStateType");
  1157. Type stateType = AbstractConnector.getStateType(connector);
  1158. Profiler.leave(prefix
  1159. + "recursivelyDetach reset state - getStateType");
  1160. // Empty state instance to get default property values from
  1161. Profiler.enter(prefix
  1162. + "recursivelyDetach reset state - createInstance");
  1163. Object defaultState = stateType.createInstance();
  1164. Profiler.leave(prefix
  1165. + "recursivelyDetach reset state - createInstance");
  1166. if (connector instanceof AbstractConnector) {
  1167. // optimization as the loop setting properties is very
  1168. // slow, especially on IE8
  1169. replaceState((AbstractConnector) connector,
  1170. defaultState);
  1171. } else {
  1172. SharedState state = connector.getState();
  1173. Profiler.enter(prefix
  1174. + "recursivelyDetach reset state - properties");
  1175. JsArrayObject<Property> properties = stateType
  1176. .getPropertiesAsArray();
  1177. int size = properties.size();
  1178. for (int i = 0; i < size; i++) {
  1179. Property property = properties.get(i);
  1180. property.setValue(state,
  1181. property.getValue(defaultState));
  1182. }
  1183. Profiler.leave(prefix
  1184. + "recursivelyDetach reset state - properties");
  1185. }
  1186. } catch (NoDataException e) {
  1187. throw new RuntimeException("Can't reset state for "
  1188. + Util.getConnectorString(connector), e);
  1189. } finally {
  1190. Profiler.leave(prefix + "recursivelyDetach reset state");
  1191. }
  1192. Profiler.enter(prefix + "recursivelyDetach perform detach");
  1193. /*
  1194. * Recursively detach children to make sure they get
  1195. * setParent(null) and hierarchy change events as needed.
  1196. */
  1197. for (ServerConnector child : connector.getChildren()) {
  1198. /*
  1199. * Server doesn't send updated child data for removed
  1200. * connectors -> ignore child that still seems to be a child
  1201. * of this connector although it has been moved to some part
  1202. * of the hierarchy that is not detached.
  1203. */
  1204. if (child.getParent() != connector) {
  1205. continue;
  1206. }
  1207. recursivelyDetach(child, events, detachedConnectors);
  1208. }
  1209. Profiler.leave(prefix + "recursivelyDetach perform detach");
  1210. /*
  1211. * Clear child list and parent
  1212. */
  1213. Profiler.enter(prefix
  1214. + "recursivelyDetach clear children and parent");
  1215. connector
  1216. .setChildren(Collections.<ServerConnector> emptyList());
  1217. connector.setParent(null);
  1218. Profiler.leave(prefix
  1219. + "recursivelyDetach clear children and parent");
  1220. /*
  1221. * Create an artificial hierarchy event for containers to give
  1222. * it a chance to clean up after its children if it has any
  1223. */
  1224. Profiler.enter(prefix
  1225. + "recursivelyDetach create hierarchy event");
  1226. if (connector instanceof HasComponentsConnector) {
  1227. HasComponentsConnector ccc = (HasComponentsConnector) connector;
  1228. List<ComponentConnector> oldChildren = ccc
  1229. .getChildComponents();
  1230. if (!oldChildren.isEmpty()) {
  1231. /*
  1232. * HasComponentsConnector has a separate child component
  1233. * list that should also be cleared
  1234. */
  1235. ccc.setChildComponents(Collections
  1236. .<ComponentConnector> emptyList());
  1237. // Create event and add it to the list of pending events
  1238. ConnectorHierarchyChangeEvent event = GWT
  1239. .create(ConnectorHierarchyChangeEvent.class);
  1240. event.setConnector(connector);
  1241. event.setOldChildren(oldChildren);
  1242. events.add(event);
  1243. }
  1244. }
  1245. Profiler.leave(prefix
  1246. + "recursivelyDetach create hierarchy event");
  1247. }
  1248. private native void replaceState(AbstractConnector connector,
  1249. Object defaultState)
  1250. /*-{
  1251. connector.@com.vaadin.client.ui.AbstractConnector::state = defaultState;
  1252. }-*/;
  1253. private void handleRpcInvocations(ValueMap json) {
  1254. if (json.containsKey("rpc")) {
  1255. Profiler.enter("handleRpcInvocations");
  1256. getLogger()
  1257. .info(" * Performing server to client RPC calls");
  1258. JsonArray rpcCalls = Util.jso2json(json
  1259. .getJavaScriptObject("rpc"));
  1260. int rpcLength = rpcCalls.length();
  1261. for (int i = 0; i < rpcLength; i++) {
  1262. try {
  1263. JsonArray rpcCall = rpcCalls.getArray(i);
  1264. MethodInvocation invocation = getRpcManager()
  1265. .parseAndApplyInvocation(rpcCall,
  1266. connection);
  1267. if (onlyNoLayoutUpdates
  1268. && !RpcManager.getMethod(invocation)
  1269. .isNoLayout()) {
  1270. onlyNoLayoutUpdates = false;
  1271. }
  1272. } catch (final Throwable e) {
  1273. getLogger()
  1274. .log(Level.SEVERE,
  1275. "Error performing server to client RPC calls",
  1276. e);
  1277. }
  1278. }
  1279. Profiler.leave("handleRpcInvocations");
  1280. }
  1281. }
  1282. };
  1283. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  1284. }
  1285. private void endRequestIfResponse(ValueMap json) {
  1286. if (isResponse(json)) {
  1287. // End the request if the received message was a
  1288. // response, not sent asynchronously
  1289. getMessageSender().endRequest();
  1290. }
  1291. }
  1292. private boolean isResynchronize(ValueMap json) {
  1293. return json.containsKey(ApplicationConstants.RESYNCHRONIZE_ID);
  1294. }
  1295. private boolean isResponse(ValueMap json) {
  1296. ValueMap meta = json.getValueMap("meta");
  1297. if (meta == null || !meta.containsKey("async")) {
  1298. return true;
  1299. }
  1300. return false;
  1301. }
  1302. /**
  1303. * Checks if the given serverId is the one we are currently waiting for from
  1304. * the server
  1305. */
  1306. private boolean isNextExpectedMessage(int serverId) {
  1307. if (serverId == -1) {
  1308. return true;
  1309. }
  1310. if (serverId == getExpectedServerId()) {
  1311. return true;
  1312. }
  1313. if (lastSeenServerSyncId == UNDEFINED_SYNC_ID) {
  1314. // First message is always ok
  1315. return true;
  1316. }
  1317. return false;
  1318. }
  1319. private int getServerId(ValueMap json) {
  1320. if (json.containsKey(ApplicationConstants.SERVER_SYNC_ID)) {
  1321. return json.getInt(ApplicationConstants.SERVER_SYNC_ID);
  1322. } else {
  1323. return -1;
  1324. }
  1325. }
  1326. private int getExpectedServerId() {
  1327. return lastSeenServerSyncId + 1;
  1328. }
  1329. /**
  1330. * Timer used to make sure that no misbehaving components can delay response
  1331. * handling forever.
  1332. */
  1333. Timer forceHandleMessage = new Timer() {
  1334. @Override
  1335. public void run() {
  1336. if (!responseHandlingLocks.isEmpty()) {
  1337. // Lock which was never release -> bug in locker or things just
  1338. // too slow
  1339. getLogger()
  1340. .warning(
  1341. "WARNING: reponse handling was never resumed, forcibly removing locks...");
  1342. responseHandlingLocks.clear();
  1343. } else {
  1344. // Waited for out-of-order message which never arrived
  1345. // Do one final check and resynchronize if the message is not
  1346. // there. The final check is only a precaution as this timer
  1347. // should have been cancelled if the message has arrived
  1348. getLogger().warning(
  1349. "Gave up waiting for message " + getExpectedServerId()
  1350. + " from the server");
  1351. }
  1352. if (!handlePendingMessages() && !pendingUIDLMessages.isEmpty()) {
  1353. // There are messages but the next id was not found, likely it
  1354. // has been lost
  1355. // Drop pending messages and resynchronize
  1356. pendingUIDLMessages.clear();
  1357. getMessageSender().resynchronize();
  1358. }
  1359. }
  1360. };
  1361. /**
  1362. * This method can be used to postpone rendering of a response for a short
  1363. * period of time (e.g. to avoid the rendering process during animation).
  1364. *
  1365. * @param lock
  1366. */
  1367. public void suspendReponseHandling(Object lock) {
  1368. responseHandlingLocks.add(lock);
  1369. }
  1370. /**
  1371. * Resumes the rendering process once all locks have been removed.
  1372. *
  1373. * @param lock
  1374. */
  1375. public void resumeResponseHandling(Object lock) {
  1376. responseHandlingLocks.remove(lock);
  1377. if (responseHandlingLocks.isEmpty()) {
  1378. // Cancel timer that breaks the lock
  1379. forceHandleMessage.cancel();
  1380. if (!pendingUIDLMessages.isEmpty()) {
  1381. getLogger()
  1382. .info("No more response handling locks, handling pending requests.");
  1383. handlePendingMessages();
  1384. }
  1385. }
  1386. }
  1387. private static native final int calculateBootstrapTime()
  1388. /*-{
  1389. if ($wnd.performance && $wnd.performance.timing) {
  1390. return (new Date).getTime() - $wnd.performance.timing.responseStart;
  1391. } else {
  1392. // performance.timing not supported
  1393. return -1;
  1394. }
  1395. }-*/;
  1396. /**
  1397. * Finds the next pending UIDL message and handles it (next pending is
  1398. * decided based on the server id)
  1399. *
  1400. * @return true if a message was handled, false otherwise
  1401. */
  1402. private boolean handlePendingMessages() {
  1403. if (pendingUIDLMessages.isEmpty()) {
  1404. return false;
  1405. }
  1406. // Try to find the next expected message
  1407. PendingUIDLMessage toHandle = null;
  1408. for (PendingUIDLMessage message : pendingUIDLMessages) {
  1409. if (isNextExpectedMessage(getServerId(message.json))) {
  1410. toHandle = message;
  1411. break;
  1412. }
  1413. }
  1414. if (toHandle != null) {
  1415. pendingUIDLMessages.remove(toHandle);
  1416. handleJSON(toHandle.getJson());
  1417. // Any remaining messages will be handled when this is called
  1418. // again at the end of handleJSON
  1419. return true;
  1420. } else {
  1421. return false;
  1422. }
  1423. }
  1424. private void removeOldPendingMessages() {
  1425. Iterator<PendingUIDLMessage> i = pendingUIDLMessages.iterator();
  1426. while (i.hasNext()) {
  1427. PendingUIDLMessage m = i.next();
  1428. int serverId = getServerId(m.json);
  1429. if (serverId != -1 && serverId < getExpectedServerId()) {
  1430. getLogger().info("Removing old message with id " + serverId);
  1431. i.remove();
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * Gets the server id included in the last received response.
  1437. * <p>
  1438. * This id can be used by connectors to determine whether new data has been
  1439. * received from the server to avoid doing the same calculations multiple
  1440. * times.
  1441. * <p>
  1442. * No guarantees are made for the structure of the id other than that there
  1443. * will be a new unique value every time a new response with data from the
  1444. * server is received.
  1445. * <p>
  1446. * The initial id when no request has yet been processed is -1.
  1447. *
  1448. * @return an id identifying the response
  1449. */
  1450. public int getLastSeenServerSyncId() {
  1451. return lastSeenServerSyncId;
  1452. }
  1453. /**
  1454. * Gets the token (aka double submit cookie) that the server uses to protect
  1455. * against Cross Site Request Forgery attacks.
  1456. *
  1457. * @return the CSRF token string
  1458. */
  1459. public String getCsrfToken() {
  1460. return csrfToken;
  1461. }
  1462. /**
  1463. * Checks whether state changes are currently being processed. Certain
  1464. * operations are not allowed when the internal state of the application
  1465. * might be in an inconsistent state because some state changes have been
  1466. * applied but others not. This includes running layotus.
  1467. *
  1468. * @return <code>true</code> if the internal state might be inconsistent
  1469. * because changes are being processed; <code>false</code> if the
  1470. * state should be consistent
  1471. */
  1472. public boolean isUpdatingState() {
  1473. return updatingState;
  1474. }
  1475. /**
  1476. * Checks if the first UIDL has been handled
  1477. *
  1478. * @return true if the initial UIDL has already been processed, false
  1479. * otherwise
  1480. */
  1481. public boolean isInitialUidlHandled() {
  1482. return bootstrapTime != 0;
  1483. }
  1484. private LayoutManager getLayoutManager() {
  1485. return LayoutManager.get(connection);
  1486. }
  1487. private ConnectorMap getConnectorMap() {
  1488. return ConnectorMap.get(connection);
  1489. }
  1490. private UIConnector getUIConnector() {
  1491. return connection.getUIConnector();
  1492. }
  1493. private RpcManager getRpcManager() {
  1494. return connection.getRpcManager();
  1495. }
  1496. private MessageSender getMessageSender() {
  1497. return connection.getMessageSender();
  1498. }
  1499. /**
  1500. * Strips the JSON wrapping from the given json string with wrapping.
  1501. *
  1502. * If the given string is not wrapped as expected, returns null
  1503. *
  1504. * @since 7.6
  1505. * @param jsonWithWrapping
  1506. * the JSON received from the server
  1507. * @return an unwrapped JSON string or null if the given string was not
  1508. * wrapped
  1509. */
  1510. public static String stripJSONWrapping(String jsonWithWrapping) {
  1511. if (jsonWithWrapping == null) {
  1512. return null;
  1513. }
  1514. if (!jsonWithWrapping.startsWith(JSON_COMMUNICATION_PREFIX)
  1515. || !jsonWithWrapping.endsWith(JSON_COMMUNICATION_SUFFIX)) {
  1516. return null;
  1517. }
  1518. return jsonWithWrapping.substring(JSON_COMMUNICATION_PREFIX.length(),
  1519. jsonWithWrapping.length() - JSON_COMMUNICATION_SUFFIX.length());
  1520. }
  1521. /**
  1522. * Unwraps and parses the given JSON, originating from the server
  1523. *
  1524. * @param jsonText
  1525. * the json from the server
  1526. * @return A parsed ValueMap or null if the input could not be parsed (or
  1527. * was null)
  1528. */
  1529. public static ValueMap parseJson(String jsonText) {
  1530. if (jsonText == null) {
  1531. return null;
  1532. }
  1533. final double start = Profiler.getRelativeTimeMillis();
  1534. try {
  1535. ValueMap json = parseJSONResponse(jsonText);
  1536. getLogger().info(
  1537. "JSON parsing took "
  1538. + Util.round(Profiler.getRelativeTimeMillis()
  1539. - start, 3) + "ms");
  1540. return json;
  1541. } catch (final Exception e) {
  1542. getLogger().severe("Unable to parse JSON: " + jsonText);
  1543. return null;
  1544. }
  1545. }
  1546. private static native ValueMap parseJSONResponse(String jsonText)
  1547. /*-{
  1548. try {
  1549. return JSON.parse(jsonText);
  1550. } catch (ignored) {
  1551. return eval('(' + jsonText + ')');
  1552. }
  1553. }-*/;
  1554. /**
  1555. * Parse the given wrapped JSON, received from the server, to a ValueMap
  1556. *
  1557. * @param wrappedJsonText
  1558. * the json, wrapped as done by the server
  1559. * @return a ValueMap, or null if the wrapping was incorrect or json could
  1560. * not be parsed
  1561. */
  1562. public static ValueMap parseWrappedJson(String wrappedJsonText) {
  1563. return parseJson(stripJSONWrapping(wrappedJsonText));
  1564. }
  1565. private static final native double getFetchStartTime()
  1566. /*-{
  1567. if ($wnd.performance && $wnd.performance.timing && $wnd.performance.timing.fetchStart) {
  1568. return $wnd.performance.timing.fetchStart;
  1569. } else {
  1570. return 0;
  1571. }
  1572. }-*/;
  1573. }