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.

ApplicationConnection.java 143KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727
  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;
  17. import java.util.ArrayList;
  18. import java.util.Collections;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.logging.Logger;
  28. import com.google.gwt.aria.client.LiveValue;
  29. import com.google.gwt.aria.client.RelevantValue;
  30. import com.google.gwt.aria.client.Roles;
  31. import com.google.gwt.core.client.Duration;
  32. import com.google.gwt.core.client.GWT;
  33. import com.google.gwt.core.client.JavaScriptObject;
  34. import com.google.gwt.core.client.JsArray;
  35. import com.google.gwt.core.client.JsArrayString;
  36. import com.google.gwt.core.client.Scheduler;
  37. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  38. import com.google.gwt.dom.client.Element;
  39. import com.google.gwt.event.shared.EventBus;
  40. import com.google.gwt.event.shared.EventHandler;
  41. import com.google.gwt.event.shared.GwtEvent;
  42. import com.google.gwt.event.shared.HandlerRegistration;
  43. import com.google.gwt.event.shared.HasHandlers;
  44. import com.google.gwt.event.shared.SimpleEventBus;
  45. import com.google.gwt.http.client.Request;
  46. import com.google.gwt.http.client.RequestBuilder;
  47. import com.google.gwt.http.client.RequestCallback;
  48. import com.google.gwt.http.client.RequestException;
  49. import com.google.gwt.http.client.Response;
  50. import com.google.gwt.http.client.URL;
  51. import com.google.gwt.regexp.shared.MatchResult;
  52. import com.google.gwt.regexp.shared.RegExp;
  53. import com.google.gwt.user.client.Command;
  54. import com.google.gwt.user.client.DOM;
  55. import com.google.gwt.user.client.Timer;
  56. import com.google.gwt.user.client.Window;
  57. import com.google.gwt.user.client.Window.ClosingEvent;
  58. import com.google.gwt.user.client.Window.ClosingHandler;
  59. import com.google.gwt.user.client.ui.HasWidgets;
  60. import com.google.gwt.user.client.ui.Widget;
  61. import com.vaadin.client.ApplicationConfiguration.ErrorMessage;
  62. import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
  63. import com.vaadin.client.ResourceLoader.ResourceLoadListener;
  64. import com.vaadin.client.communication.HasJavaScriptConnectorHelper;
  65. import com.vaadin.client.communication.Heartbeat;
  66. import com.vaadin.client.communication.JavaScriptMethodInvocation;
  67. import com.vaadin.client.communication.JsonDecoder;
  68. import com.vaadin.client.communication.JsonEncoder;
  69. import com.vaadin.client.communication.PushConnection;
  70. import com.vaadin.client.communication.RpcManager;
  71. import com.vaadin.client.communication.StateChangeEvent;
  72. import com.vaadin.client.componentlocator.ComponentLocator;
  73. import com.vaadin.client.extensions.AbstractExtensionConnector;
  74. import com.vaadin.client.metadata.ConnectorBundleLoader;
  75. import com.vaadin.client.metadata.Method;
  76. import com.vaadin.client.metadata.NoDataException;
  77. import com.vaadin.client.metadata.Property;
  78. import com.vaadin.client.metadata.Type;
  79. import com.vaadin.client.metadata.TypeData;
  80. import com.vaadin.client.metadata.TypeDataStore;
  81. import com.vaadin.client.ui.AbstractComponentConnector;
  82. import com.vaadin.client.ui.AbstractConnector;
  83. import com.vaadin.client.ui.FontIcon;
  84. import com.vaadin.client.ui.Icon;
  85. import com.vaadin.client.ui.ImageIcon;
  86. import com.vaadin.client.ui.VContextMenu;
  87. import com.vaadin.client.ui.VNotification;
  88. import com.vaadin.client.ui.VNotification.HideEvent;
  89. import com.vaadin.client.ui.VOverlay;
  90. import com.vaadin.client.ui.dd.VDragAndDropManager;
  91. import com.vaadin.client.ui.ui.UIConnector;
  92. import com.vaadin.client.ui.window.WindowConnector;
  93. import com.vaadin.shared.AbstractComponentState;
  94. import com.vaadin.shared.ApplicationConstants;
  95. import com.vaadin.shared.JsonConstants;
  96. import com.vaadin.shared.VaadinUriResolver;
  97. import com.vaadin.shared.Version;
  98. import com.vaadin.shared.communication.LegacyChangeVariablesInvocation;
  99. import com.vaadin.shared.communication.MethodInvocation;
  100. import com.vaadin.shared.communication.SharedState;
  101. import com.vaadin.shared.ui.ui.UIConstants;
  102. import com.vaadin.shared.ui.ui.UIState.PushConfigurationState;
  103. import com.vaadin.shared.util.SharedUtil;
  104. import elemental.json.Json;
  105. import elemental.json.JsonArray;
  106. import elemental.json.JsonObject;
  107. import elemental.json.JsonValue;
  108. /**
  109. * This is the client side communication "engine", managing client-server
  110. * communication with its server side counterpart
  111. * com.vaadin.server.VaadinService.
  112. *
  113. * Client-side connectors receive updates from the corresponding server-side
  114. * connector (typically component) as state updates or RPC calls. The connector
  115. * has the possibility to communicate back with its server side counter part
  116. * through RPC calls.
  117. *
  118. * TODO document better
  119. *
  120. * Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
  121. */
  122. public class ApplicationConnection implements HasHandlers {
  123. /**
  124. * Helper used to return two values when updating the connector hierarchy.
  125. */
  126. private static class ConnectorHierarchyUpdateResult {
  127. /**
  128. * Needed at a later point when the created events are fired
  129. */
  130. private JsArrayObject<ConnectorHierarchyChangeEvent> events = JavaScriptObject
  131. .createArray().cast();
  132. /**
  133. * Needed to know where captions might need to get updated
  134. */
  135. private FastStringSet parentChangedIds = FastStringSet.create();
  136. /**
  137. * Connectors for which the parent has been set to null
  138. */
  139. private FastStringSet detachedConnectorIds = FastStringSet.create();
  140. }
  141. @Deprecated
  142. public static final String MODIFIED_CLASSNAME = StyleConstants.MODIFIED;
  143. @Deprecated
  144. public static final String DISABLED_CLASSNAME = StyleConstants.DISABLED;
  145. @Deprecated
  146. public static final String REQUIRED_CLASSNAME = StyleConstants.REQUIRED;
  147. @Deprecated
  148. public static final String REQUIRED_CLASSNAME_EXT = StyleConstants.REQUIRED_EXT;
  149. @Deprecated
  150. public static final String ERROR_CLASSNAME_EXT = StyleConstants.ERROR_EXT;
  151. /**
  152. * A string that, if found in a non-JSON response to a UIDL request, will
  153. * cause the browser to refresh the page. If followed by a colon, optional
  154. * whitespace, and a URI, causes the browser to synchronously load the URI.
  155. *
  156. * <p>
  157. * This allows, for instance, a servlet filter to redirect the application
  158. * to a custom login page when the session expires. For example:
  159. * </p>
  160. *
  161. * <pre>
  162. * if (sessionExpired) {
  163. * response.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
  164. * response.getWriter().write(
  165. * myLoginPageHtml + &quot;&lt;!-- Vaadin-Refresh: &quot;
  166. * + request.getContextPath() + &quot; --&gt;&quot;);
  167. * }
  168. * </pre>
  169. */
  170. public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
  171. // will hold the CSRF token once received
  172. private String csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE;
  173. private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
  174. /**
  175. * The pending method invocations that will be send to the server by
  176. * {@link #sendPendingCommand}. The key is defined differently based on
  177. * whether the method invocation is enqueued with lastonly. With lastonly
  178. * enabled, the method signature ( {@link MethodInvocation#getLastOnlyTag()}
  179. * ) is used as the key to make enable removing a previously enqueued
  180. * invocation. Without lastonly, an incremental id based on
  181. * {@link #lastInvocationTag} is used to get unique values.
  182. */
  183. private LinkedHashMap<String, MethodInvocation> pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
  184. private int lastInvocationTag = 0;
  185. private WidgetSet widgetSet;
  186. private VContextMenu contextMenu = null;
  187. private final UIConnector uIConnector;
  188. protected boolean applicationRunning = false;
  189. private boolean hasActiveRequest = false;
  190. /**
  191. * Webkit will ignore outgoing requests while waiting for a response to a
  192. * navigation event (indicated by a beforeunload event). When this happens,
  193. * we should keep trying to send the request every now and then until there
  194. * is a response or until it throws an exception saying that it is already
  195. * being sent.
  196. */
  197. private boolean webkitMaybeIgnoringRequests = false;
  198. protected boolean cssLoaded = false;
  199. /** Parameters for this application connection loaded from the web-page */
  200. private ApplicationConfiguration configuration;
  201. /** List of pending variable change bursts that must be submitted in order */
  202. private final ArrayList<LinkedHashMap<String, MethodInvocation>> pendingBursts = new ArrayList<LinkedHashMap<String, MethodInvocation>>();
  203. /** Timer for automatic refirect to SessionExpiredURL */
  204. private Timer redirectTimer;
  205. /** redirectTimer scheduling interval in seconds */
  206. private int sessionExpirationInterval;
  207. private Date requestStartTime;
  208. private final LayoutManager layoutManager;
  209. private final RpcManager rpcManager;
  210. private PushConnection push;
  211. /**
  212. * If responseHandlingLocks contains any objects, response handling is
  213. * suspended until the collection is empty or a timeout has occurred.
  214. */
  215. private Set<Object> responseHandlingLocks = new HashSet<Object>();
  216. /**
  217. * Data structure holding information about pending UIDL messages.
  218. */
  219. private class PendingUIDLMessage {
  220. private Date start;
  221. private String jsonText;
  222. private ValueMap json;
  223. public PendingUIDLMessage(Date start, String jsonText, ValueMap json) {
  224. this.start = start;
  225. this.jsonText = jsonText;
  226. this.json = json;
  227. }
  228. public Date getStart() {
  229. return start;
  230. }
  231. public String getJsonText() {
  232. return jsonText;
  233. }
  234. public ValueMap getJson() {
  235. return json;
  236. }
  237. }
  238. /** Contains all UIDL messages received while response handling is suspended */
  239. private List<PendingUIDLMessage> pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
  240. /** The max timeout that response handling may be suspended */
  241. private static final int MAX_SUSPENDED_TIMEOUT = 5000;
  242. /** Event bus for communication events */
  243. private EventBus eventBus = GWT.create(SimpleEventBus.class);
  244. /**
  245. * The communication handler methods are called at certain points during
  246. * communication with the server. This allows for making add-ons that keep
  247. * track of different aspects of the communication.
  248. */
  249. public interface CommunicationHandler extends EventHandler {
  250. void onRequestStarting(RequestStartingEvent e);
  251. void onResponseHandlingStarted(ResponseHandlingStartedEvent e);
  252. void onResponseHandlingEnded(ResponseHandlingEndedEvent e);
  253. }
  254. public static class RequestStartingEvent extends ApplicationConnectionEvent {
  255. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  256. public RequestStartingEvent(ApplicationConnection connection) {
  257. super(connection);
  258. }
  259. @Override
  260. public Type<CommunicationHandler> getAssociatedType() {
  261. return TYPE;
  262. }
  263. @Override
  264. protected void dispatch(CommunicationHandler handler) {
  265. handler.onRequestStarting(this);
  266. }
  267. }
  268. public static class ResponseHandlingEndedEvent extends
  269. ApplicationConnectionEvent {
  270. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  271. public ResponseHandlingEndedEvent(ApplicationConnection connection) {
  272. super(connection);
  273. }
  274. @Override
  275. public Type<CommunicationHandler> getAssociatedType() {
  276. return TYPE;
  277. }
  278. @Override
  279. protected void dispatch(CommunicationHandler handler) {
  280. handler.onResponseHandlingEnded(this);
  281. }
  282. }
  283. public static abstract class ApplicationConnectionEvent extends
  284. GwtEvent<CommunicationHandler> {
  285. private ApplicationConnection connection;
  286. protected ApplicationConnectionEvent(ApplicationConnection connection) {
  287. this.connection = connection;
  288. }
  289. public ApplicationConnection getConnection() {
  290. return connection;
  291. }
  292. }
  293. /**
  294. * Event triggered when a XHR request has finished with the status code of
  295. * the response.
  296. *
  297. * Useful for handlers observing network failures like online/off-line
  298. * monitors.
  299. */
  300. public static class ConnectionStatusEvent extends
  301. GwtEvent<ConnectionStatusEvent.ConnectionStatusHandler> {
  302. private int status;
  303. public static interface ConnectionStatusHandler extends EventHandler {
  304. public void onConnectionStatusChange(ConnectionStatusEvent event);
  305. }
  306. public ConnectionStatusEvent(int status) {
  307. this.status = status;
  308. }
  309. public int getStatus() {
  310. return status;
  311. }
  312. public final static Type<ConnectionStatusHandler> TYPE = new Type<ConnectionStatusHandler>();
  313. @Override
  314. public Type<ConnectionStatusHandler> getAssociatedType() {
  315. return TYPE;
  316. }
  317. @Override
  318. protected void dispatch(ConnectionStatusHandler handler) {
  319. handler.onConnectionStatusChange(this);
  320. }
  321. }
  322. public static class ResponseHandlingStartedEvent extends
  323. ApplicationConnectionEvent {
  324. public ResponseHandlingStartedEvent(ApplicationConnection connection) {
  325. super(connection);
  326. }
  327. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  328. @Override
  329. public Type<CommunicationHandler> getAssociatedType() {
  330. return TYPE;
  331. }
  332. @Override
  333. protected void dispatch(CommunicationHandler handler) {
  334. handler.onResponseHandlingStarted(this);
  335. }
  336. }
  337. /**
  338. * Event triggered when a application is stopped by calling
  339. * {@link ApplicationConnection#setApplicationRunning(false)}.
  340. *
  341. * To listen for the event add a {@link ApplicationStoppedHandler} by
  342. * invoking
  343. * {@link ApplicationConnection#addHandler(ApplicationConnection.ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
  344. * to the {@link ApplicationConnection}
  345. *
  346. * @since 7.1.8
  347. * @author Vaadin Ltd
  348. */
  349. public static class ApplicationStoppedEvent extends
  350. GwtEvent<ApplicationStoppedHandler> {
  351. public static Type<ApplicationStoppedHandler> TYPE = new Type<ApplicationStoppedHandler>();
  352. @Override
  353. public Type<ApplicationStoppedHandler> getAssociatedType() {
  354. return TYPE;
  355. }
  356. @Override
  357. protected void dispatch(ApplicationStoppedHandler listener) {
  358. listener.onApplicationStopped(this);
  359. }
  360. }
  361. /**
  362. * Allows custom handling of communication errors.
  363. */
  364. public interface CommunicationErrorHandler {
  365. /**
  366. * Called when a communication error has occurred. Returning
  367. * <code>true</code> from this method suppresses error handling.
  368. *
  369. * @param details
  370. * A string describing the error.
  371. * @param statusCode
  372. * The HTTP status code (e.g. 404, etc).
  373. * @return true if the error reporting should be suppressed, false to
  374. * perform normal error reporting.
  375. */
  376. public boolean onError(String details, int statusCode);
  377. }
  378. /**
  379. * A listener for listening to application stopped events. The listener can
  380. * be added to a {@link ApplicationConnection} by invoking
  381. * {@link ApplicationConnection#addHandler(ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
  382. *
  383. * @since 7.1.8
  384. * @author Vaadin Ltd
  385. */
  386. public interface ApplicationStoppedHandler extends EventHandler {
  387. /**
  388. * Triggered when the {@link ApplicationConnection} marks a previously
  389. * running application as stopped by invoking
  390. * {@link ApplicationConnection#setApplicationRunning(false)}
  391. *
  392. * @param event
  393. * the event triggered by the {@link ApplicationConnection}
  394. */
  395. void onApplicationStopped(ApplicationStoppedEvent event);
  396. }
  397. private CommunicationErrorHandler communicationErrorDelegate = null;
  398. private VLoadingIndicator loadingIndicator;
  399. private Heartbeat heartbeat = GWT.create(Heartbeat.class);
  400. private boolean tooltipInitialized = false;
  401. private final VaadinUriResolver uriResolver = new VaadinUriResolver() {
  402. @Override
  403. protected String getVaadinDirUrl() {
  404. return getConfiguration().getVaadinDirUrl();
  405. }
  406. @Override
  407. protected String getServiceUrlParameterName() {
  408. return getConfiguration().getServiceUrlParameterName();
  409. }
  410. @Override
  411. protected String getServiceUrl() {
  412. return getConfiguration().getServiceUrl();
  413. }
  414. @Override
  415. protected String getThemeUri() {
  416. return ApplicationConnection.this.getThemeUri();
  417. }
  418. @Override
  419. protected String encodeQueryStringParameterValue(String queryString) {
  420. return URL.encodeQueryString(queryString);
  421. }
  422. };
  423. public static class MultiStepDuration extends Duration {
  424. private int previousStep = elapsedMillis();
  425. public void logDuration(String message) {
  426. logDuration(message, 0);
  427. }
  428. public void logDuration(String message, int minDuration) {
  429. int currentTime = elapsedMillis();
  430. int stepDuration = currentTime - previousStep;
  431. if (stepDuration >= minDuration) {
  432. VConsole.log(message + ": " + stepDuration + " ms");
  433. }
  434. previousStep = currentTime;
  435. }
  436. }
  437. private boolean updatingState = false;
  438. public ApplicationConnection() {
  439. // Assuming UI data is eagerly loaded
  440. ConnectorBundleLoader.get().loadBundle(
  441. ConnectorBundleLoader.EAGER_BUNDLE_NAME, null);
  442. uIConnector = GWT.create(UIConnector.class);
  443. rpcManager = GWT.create(RpcManager.class);
  444. layoutManager = GWT.create(LayoutManager.class);
  445. layoutManager.setConnection(this);
  446. tooltip = GWT.create(VTooltip.class);
  447. loadingIndicator = GWT.create(VLoadingIndicator.class);
  448. loadingIndicator.setConnection(this);
  449. }
  450. public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
  451. VConsole.log("Starting application " + cnf.getRootPanelId());
  452. VConsole.log("Using theme: " + cnf.getThemeName());
  453. VConsole.log("Vaadin application servlet version: "
  454. + cnf.getServletVersion());
  455. if (!cnf.getServletVersion().equals(Version.getFullVersion())) {
  456. VConsole.error("Warning: your widget set seems to be built with a different "
  457. + "version than the one used on server. Unexpected "
  458. + "behavior may occur.");
  459. }
  460. this.widgetSet = widgetSet;
  461. configuration = cnf;
  462. ComponentLocator componentLocator = new ComponentLocator(this);
  463. String appRootPanelName = cnf.getRootPanelId();
  464. // remove the end (window name) of autogenerated rootpanel id
  465. appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
  466. initializeTestbenchHooks(componentLocator, appRootPanelName);
  467. initializeClientHooks();
  468. uIConnector.init(cnf.getRootPanelId(), this);
  469. tooltip.setOwner(uIConnector.getWidget());
  470. getLoadingIndicator().show();
  471. heartbeat.init(this);
  472. Window.addWindowClosingHandler(new ClosingHandler() {
  473. @Override
  474. public void onWindowClosing(ClosingEvent event) {
  475. webkitMaybeIgnoringRequests = true;
  476. }
  477. });
  478. // Ensure the overlay container is added to the dom and set as a live
  479. // area for assistive devices
  480. Element overlayContainer = VOverlay.getOverlayContainer(this);
  481. Roles.getAlertRole().setAriaLiveProperty(overlayContainer,
  482. LiveValue.ASSERTIVE);
  483. VOverlay.setOverlayContainerLabel(this,
  484. getUIConnector().getState().overlayContainerLabel);
  485. Roles.getAlertRole().setAriaRelevantProperty(overlayContainer,
  486. RelevantValue.ADDITIONS);
  487. }
  488. /**
  489. * Starts this application. Don't call this method directly - it's called by
  490. * {@link ApplicationConfiguration#startNextApplication()}, which should be
  491. * called once this application has started (first response received) or
  492. * failed to start. This ensures that the applications are started in order,
  493. * to avoid session-id problems.
  494. *
  495. */
  496. public void start() {
  497. String jsonText = configuration.getUIDL();
  498. if (jsonText == null) {
  499. // inital UIDL not in DOM, request later
  500. repaintAll();
  501. } else {
  502. // Update counter so TestBench knows something is still going on
  503. hasActiveRequest = true;
  504. // initial UIDL provided in DOM, continue as if returned by request
  505. handleJSONText(jsonText, -1);
  506. }
  507. // Tooltip can't be created earlier because the
  508. // necessary fields are not setup to add it in the
  509. // correct place in the DOM
  510. if (!tooltipInitialized) {
  511. tooltipInitialized = true;
  512. ApplicationConfiguration.runWhenDependenciesLoaded(new Command() {
  513. @Override
  514. public void execute() {
  515. getVTooltip().initializeAssistiveTooltips();
  516. }
  517. });
  518. }
  519. }
  520. /**
  521. * Checks if there is some work to be done on the client side
  522. *
  523. * @return true if the client has some work to be done, false otherwise
  524. */
  525. private boolean isActive() {
  526. return isWorkPending() || hasActiveRequest()
  527. || isExecutingDeferredCommands();
  528. }
  529. private native void initializeTestbenchHooks(
  530. ComponentLocator componentLocator, String TTAppId)
  531. /*-{
  532. var ap = this;
  533. var client = {};
  534. client.isActive = $entry(function() {
  535. return ap.@com.vaadin.client.ApplicationConnection::isActive()();
  536. });
  537. var vi = ap.@com.vaadin.client.ApplicationConnection::getVersionInfo()();
  538. if (vi) {
  539. client.getVersionInfo = function() {
  540. return vi;
  541. }
  542. }
  543. client.getProfilingData = $entry(function() {
  544. var pd = [
  545. ap.@com.vaadin.client.ApplicationConnection::lastProcessingTime,
  546. ap.@com.vaadin.client.ApplicationConnection::totalProcessingTime
  547. ];
  548. pd = pd.concat(ap.@com.vaadin.client.ApplicationConnection::serverTimingInfo);
  549. pd[pd.length] = ap.@com.vaadin.client.ApplicationConnection::bootstrapTime;
  550. return pd;
  551. });
  552. client.getElementByPath = $entry(function(id) {
  553. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
  554. });
  555. client.getElementByPathStartingAt = $entry(function(id, element) {
  556. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementByPathStartingAt(Ljava/lang/String;Lcom/google/gwt/dom/client/Element;)(id, element);
  557. });
  558. client.getElementsByPath = $entry(function(id) {
  559. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementsByPath(Ljava/lang/String;)(id);
  560. });
  561. client.getElementsByPathStartingAt = $entry(function(id, element) {
  562. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementsByPathStartingAt(Ljava/lang/String;Lcom/google/gwt/dom/client/Element;)(id, element);
  563. });
  564. client.getPathForElement = $entry(function(element) {
  565. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getPathForElement(Lcom/google/gwt/dom/client/Element;)(element);
  566. });
  567. client.initializing = false;
  568. $wnd.vaadin.clients[TTAppId] = client;
  569. }-*/;
  570. private static native final int calculateBootstrapTime()
  571. /*-{
  572. if ($wnd.performance && $wnd.performance.timing) {
  573. return (new Date).getTime() - $wnd.performance.timing.responseStart;
  574. } else {
  575. // performance.timing not supported
  576. return -1;
  577. }
  578. }-*/;
  579. /**
  580. * Helper for tt initialization
  581. */
  582. private JavaScriptObject getVersionInfo() {
  583. return configuration.getVersionInfoJSObject();
  584. }
  585. /**
  586. * Publishes a JavaScript API for mash-up applications.
  587. * <ul>
  588. * <li><code>vaadin.forceSync()</code> sends pending variable changes, in
  589. * effect synchronizing the server and client state. This is done for all
  590. * applications on host page.</li>
  591. * <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
  592. * called after each XHR made by vaadin application. Note, that it is
  593. * attaching js functions responsibility to create the variable like this:
  594. *
  595. * <code><pre>
  596. * if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
  597. * postRequestHooks.myHook = function(appId) {
  598. * if(appId == "MyAppOfInterest") {
  599. * // do the staff you need on xhr activity
  600. * }
  601. * }
  602. * </pre></code> First parameter passed to these functions is the identifier
  603. * of Vaadin application that made the request.
  604. * </ul>
  605. *
  606. * TODO make this multi-app aware
  607. */
  608. private native void initializeClientHooks()
  609. /*-{
  610. var app = this;
  611. var oldSync;
  612. if ($wnd.vaadin.forceSync) {
  613. oldSync = $wnd.vaadin.forceSync;
  614. }
  615. $wnd.vaadin.forceSync = $entry(function() {
  616. if (oldSync) {
  617. oldSync();
  618. }
  619. app.@com.vaadin.client.ApplicationConnection::sendPendingVariableChanges()();
  620. });
  621. var oldForceLayout;
  622. if ($wnd.vaadin.forceLayout) {
  623. oldForceLayout = $wnd.vaadin.forceLayout;
  624. }
  625. $wnd.vaadin.forceLayout = $entry(function() {
  626. if (oldForceLayout) {
  627. oldForceLayout();
  628. }
  629. app.@com.vaadin.client.ApplicationConnection::forceLayout()();
  630. });
  631. }-*/;
  632. /**
  633. * Runs possibly registered client side post request hooks. This is expected
  634. * to be run after each uidl request made by Vaadin application.
  635. *
  636. * @param appId
  637. */
  638. private static native void runPostRequestHooks(String appId)
  639. /*-{
  640. if ($wnd.vaadin.postRequestHooks) {
  641. for ( var hook in $wnd.vaadin.postRequestHooks) {
  642. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  643. try {
  644. $wnd.vaadin.postRequestHooks[hook](appId);
  645. } catch (e) {
  646. }
  647. }
  648. }
  649. }
  650. }-*/;
  651. /**
  652. * If on Liferay and logged in, ask the client side session management
  653. * JavaScript to extend the session duration.
  654. *
  655. * Otherwise, Liferay client side JavaScript will explicitly expire the
  656. * session even though the server side considers the session to be active.
  657. * See ticket #8305 for more information.
  658. */
  659. protected native void extendLiferaySession()
  660. /*-{
  661. if ($wnd.Liferay && $wnd.Liferay.Session) {
  662. $wnd.Liferay.Session.extend();
  663. // if the extend banner is visible, hide it
  664. if ($wnd.Liferay.Session.banner) {
  665. $wnd.Liferay.Session.banner.remove();
  666. }
  667. }
  668. }-*/;
  669. /**
  670. * Indicates whether or not there are currently active UIDL requests. Used
  671. * internally to sequence requests properly, seldom needed in Widgets.
  672. *
  673. * @return true if there are active requests
  674. */
  675. public boolean hasActiveRequest() {
  676. return hasActiveRequest;
  677. }
  678. private String getRepaintAllParameters() {
  679. String parameters = ApplicationConstants.URL_PARAMETER_REPAINT_ALL
  680. + "=1";
  681. return parameters;
  682. }
  683. protected void repaintAll() {
  684. makeUidlRequest(Json.createArray(), getRepaintAllParameters());
  685. }
  686. /**
  687. * Requests an analyze of layouts, to find inconsistencies. Exclusively used
  688. * for debugging during development.
  689. *
  690. * @deprecated as of 7.1. Replaced by {@link UIConnector#analyzeLayouts()}
  691. */
  692. @Deprecated
  693. public void analyzeLayouts() {
  694. getUIConnector().analyzeLayouts();
  695. }
  696. /**
  697. * Sends a request to the server to print details to console that will help
  698. * the developer to locate the corresponding server-side connector in the
  699. * source code.
  700. *
  701. * @param serverConnector
  702. * @deprecated as of 7.1. Replaced by
  703. * {@link UIConnector#showServerDebugInfo(ServerConnector)}
  704. */
  705. @Deprecated
  706. void highlightConnector(ServerConnector serverConnector) {
  707. getUIConnector().showServerDebugInfo(serverConnector);
  708. }
  709. /**
  710. * Makes an UIDL request to the server.
  711. *
  712. * @param reqInvocations
  713. * Data containing RPC invocations and all related information.
  714. * @param extraParams
  715. * Parameters that are added as GET parameters to the url.
  716. * Contains key=value pairs joined by & characters or is empty if
  717. * no parameters should be added. Should not start with any
  718. * special character.
  719. */
  720. protected void makeUidlRequest(final JsonArray reqInvocations,
  721. final String extraParams) {
  722. startRequest();
  723. JsonObject payload = Json.createObject();
  724. if (!getCsrfToken().equals(
  725. ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE)) {
  726. payload.put(ApplicationConstants.CSRF_TOKEN, getCsrfToken());
  727. }
  728. payload.put(ApplicationConstants.RPC_INVOCATIONS, reqInvocations);
  729. payload.put(ApplicationConstants.SERVER_SYNC_ID, lastSeenServerSyncId);
  730. VConsole.log("Making UIDL Request with params: " + payload.toJson());
  731. String uri = translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  732. + ApplicationConstants.UIDL_PATH + '/');
  733. if (extraParams != null && extraParams.length() > 0) {
  734. uri = SharedUtil.addGetParameters(uri, extraParams);
  735. }
  736. uri = SharedUtil.addGetParameters(uri, UIConstants.UI_ID_PARAMETER
  737. + "=" + configuration.getUIId());
  738. doUidlRequest(uri, payload);
  739. }
  740. /**
  741. * Sends an asynchronous or synchronous UIDL request to the server using the
  742. * given URI.
  743. *
  744. * @param uri
  745. * The URI to use for the request. May includes GET parameters
  746. * @param payload
  747. * The contents of the request to send
  748. */
  749. protected void doUidlRequest(final String uri, final JsonObject payload) {
  750. doUidlRequest(uri, payload, true);
  751. }
  752. /**
  753. * Sends an asynchronous or synchronous UIDL request to the server using the
  754. * given URI.
  755. *
  756. * @param uri
  757. * The URI to use for the request. May includes GET parameters
  758. * @param payload
  759. * The contents of the request to send
  760. * @param retry
  761. * true when a status code 0 should be retried
  762. * @since 7.3.7
  763. */
  764. protected void doUidlRequest(final String uri, final JsonObject payload,
  765. final boolean retry) {
  766. RequestCallback requestCallback = new RequestCallback() {
  767. @Override
  768. public void onError(Request request, Throwable exception) {
  769. handleCommunicationError(exception.getMessage(), -1);
  770. }
  771. private void handleCommunicationError(String details, int statusCode) {
  772. if (!handleErrorInDelegate(details, statusCode)) {
  773. showCommunicationError(details, statusCode);
  774. }
  775. endRequest();
  776. // Consider application not running any more and prevent all
  777. // future requests
  778. setApplicationRunning(false);
  779. }
  780. @Override
  781. public void onResponseReceived(Request request, Response response) {
  782. VConsole.log("Server visit took "
  783. + String.valueOf((new Date()).getTime()
  784. - requestStartTime.getTime()) + "ms");
  785. int statusCode = response.getStatusCode();
  786. // Notify network observers about response status
  787. fireEvent(new ConnectionStatusEvent(statusCode));
  788. switch (statusCode) {
  789. case 0:
  790. if (retry) {
  791. /*
  792. * There are 2 situations where the error can pop up:
  793. *
  794. * 1) Request was most likely canceled because the
  795. * browser is maybe navigating away from the page. Just
  796. * send the request again without displaying any error
  797. * in case the navigation isn't carried through.
  798. *
  799. * 2) The browser failed to establish a network
  800. * connection. This was observed with keep-alive
  801. * requests, and under wi-fi roaming conditions.
  802. *
  803. * Status code 0 does indicate that there was no server
  804. * side processing, so we can retry the request.
  805. */
  806. VConsole.log("Status code 0, retrying");
  807. (new Timer() {
  808. @Override
  809. public void run() {
  810. doUidlRequest(uri, payload, false);
  811. }
  812. }).schedule(100);
  813. } else {
  814. handleCommunicationError(
  815. "Invalid status code 0 (server down?)",
  816. statusCode);
  817. }
  818. return;
  819. case 401:
  820. /*
  821. * Authorization has failed. Could be that the session has
  822. * timed out and the container is redirecting to a login
  823. * page.
  824. */
  825. showAuthenticationError("");
  826. endRequest();
  827. return;
  828. case 503:
  829. /*
  830. * We'll assume msec instead of the usual seconds. If
  831. * there's no Retry-After header, handle the error like a
  832. * 500, as per RFC 2616 section 10.5.4.
  833. */
  834. String delay = response.getHeader("Retry-After");
  835. if (delay != null) {
  836. VConsole.log("503, retrying in " + delay + "msec");
  837. (new Timer() {
  838. @Override
  839. public void run() {
  840. doUidlRequest(uri, payload);
  841. }
  842. }).schedule(Integer.parseInt(delay));
  843. return;
  844. }
  845. }
  846. if ((statusCode / 100) == 4) {
  847. // Handle all 4xx errors the same way as (they are
  848. // all permanent errors)
  849. showCommunicationError(
  850. "UIDL could not be read from server. Check servlets mappings. Error code: "
  851. + statusCode, statusCode);
  852. endRequest();
  853. return;
  854. } else if ((statusCode / 100) == 5) {
  855. // Something's wrong on the server, there's nothing the
  856. // client can do except maybe try again.
  857. handleCommunicationError("Server error. Error code: "
  858. + statusCode, statusCode);
  859. return;
  860. }
  861. String contentType = response.getHeader("Content-Type");
  862. if (contentType == null
  863. || !contentType.startsWith("application/json")) {
  864. /*
  865. * A servlet filter or equivalent may have intercepted the
  866. * request and served non-UIDL content (for instance, a
  867. * login page if the session has expired.) If the response
  868. * contains a magic substring, do a synchronous refresh. See
  869. * #8241.
  870. */
  871. MatchResult refreshToken = RegExp.compile(
  872. UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)").exec(
  873. response.getText());
  874. if (refreshToken != null) {
  875. redirect(refreshToken.getGroup(2));
  876. return;
  877. }
  878. }
  879. // for(;;);[realjson]
  880. final String jsonText = response.getText().substring(9,
  881. response.getText().length() - 1);
  882. handleJSONText(jsonText, statusCode);
  883. }
  884. };
  885. if (push != null) {
  886. push.push(payload);
  887. } else {
  888. try {
  889. doAjaxRequest(uri, payload, requestCallback);
  890. } catch (RequestException e) {
  891. VConsole.error(e);
  892. endRequest();
  893. fireEvent(new ConnectionStatusEvent(0));
  894. }
  895. }
  896. }
  897. /**
  898. * Handles received UIDL JSON text, parsing it, and passing it on to the
  899. * appropriate handlers, while logging timing information.
  900. *
  901. * @param jsonText
  902. * @param statusCode
  903. */
  904. private void handleJSONText(String jsonText, int statusCode) {
  905. final Date start = new Date();
  906. final ValueMap json;
  907. try {
  908. json = parseJSONResponse(jsonText);
  909. } catch (final Exception e) {
  910. endRequest();
  911. showCommunicationError(e.getMessage() + " - Original JSON-text:"
  912. + jsonText, statusCode);
  913. return;
  914. }
  915. VConsole.log("JSON parsing took "
  916. + (new Date().getTime() - start.getTime()) + "ms");
  917. if (isApplicationRunning()) {
  918. handleReceivedJSONMessage(start, jsonText, json);
  919. } else {
  920. if (!cssLoaded) {
  921. // Application is starting up for the first time
  922. setApplicationRunning(true);
  923. handleWhenCSSLoaded(jsonText, json);
  924. } else {
  925. getLogger()
  926. .warning(
  927. "Ignored received message because application has already been stopped");
  928. return;
  929. }
  930. }
  931. }
  932. /**
  933. * Sends an asynchronous UIDL request to the server using the given URI.
  934. *
  935. * @param uri
  936. * The URI to use for the request. May includes GET parameters
  937. * @param payload
  938. * The contents of the request to send
  939. * @param requestCallback
  940. * The handler for the response
  941. * @throws RequestException
  942. * if the request could not be sent
  943. */
  944. protected void doAjaxRequest(String uri, JsonObject payload,
  945. RequestCallback requestCallback) throws RequestException {
  946. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  947. // TODO enable timeout
  948. // rb.setTimeoutMillis(timeoutMillis);
  949. // TODO this should be configurable
  950. rb.setHeader("Content-Type", JsonConstants.JSON_CONTENT_TYPE);
  951. rb.setRequestData(payload.toJson());
  952. rb.setCallback(requestCallback);
  953. final Request request = rb.send();
  954. if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
  955. final int retryTimeout = 250;
  956. new Timer() {
  957. @Override
  958. public void run() {
  959. // Use native js to access private field in Request
  960. if (resendRequest(request) && webkitMaybeIgnoringRequests) {
  961. // Schedule retry if still needed
  962. schedule(retryTimeout);
  963. }
  964. }
  965. }.schedule(retryTimeout);
  966. }
  967. }
  968. private static native boolean resendRequest(Request request)
  969. /*-{
  970. var xhr = request.@com.google.gwt.http.client.Request::xmlHttpRequest
  971. if (xhr.readyState != 1) {
  972. // Progressed to some other readyState -> no longer blocked
  973. return false;
  974. }
  975. try {
  976. xhr.send();
  977. return true;
  978. } catch (e) {
  979. // send throws exception if it is running for real
  980. return false;
  981. }
  982. }-*/;
  983. int cssWaits = 0;
  984. /**
  985. * Holds the time spent rendering the last request
  986. */
  987. protected int lastProcessingTime;
  988. /**
  989. * Holds the total time spent rendering requests during the lifetime of the
  990. * session.
  991. */
  992. protected int totalProcessingTime;
  993. /**
  994. * Holds the time it took to load the page and render the first view. 0
  995. * means that this value has not yet been calculated because the first view
  996. * has not yet been rendered (or that your browser is very fast). -1 means
  997. * that the browser does not support the performance.timing feature used to
  998. * get this measurement.
  999. */
  1000. private int bootstrapTime;
  1001. /**
  1002. * Holds the timing information from the server-side. How much time was
  1003. * spent servicing the last request and how much time has been spent
  1004. * servicing the session so far. These values are always one request behind,
  1005. * since they cannot be measured before the request is finished.
  1006. */
  1007. private ValueMap serverTimingInfo;
  1008. /**
  1009. * Holds the last seen response id given by the server.
  1010. * <p>
  1011. * The server generates a strictly increasing id for each response to each
  1012. * request from the client. This ID is then replayed back to the server on
  1013. * each request. This helps the server in knowing in what state the client
  1014. * is, and compare it to its own state. In short, it helps with concurrent
  1015. * changes between the client and server.
  1016. * <p>
  1017. * Initial value, i.e. no responses received from the server, is
  1018. * {@link #UNDEFINED_SYNC_ID} ({@value #UNDEFINED_SYNC_ID}). This happens
  1019. * between the bootstrap HTML being loaded and the first UI being rendered;
  1020. */
  1021. private int lastSeenServerSyncId = UNDEFINED_SYNC_ID;
  1022. /**
  1023. * The value of an undefined sync id.
  1024. * <p>
  1025. * This must be <code>-1</code>, because of the contract in
  1026. * {@link #getLastResponseId()}
  1027. */
  1028. private static final int UNDEFINED_SYNC_ID = -1;
  1029. static final int MAX_CSS_WAITS = 100;
  1030. protected void handleWhenCSSLoaded(final String jsonText,
  1031. final ValueMap json) {
  1032. if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
  1033. (new Timer() {
  1034. @Override
  1035. public void run() {
  1036. handleWhenCSSLoaded(jsonText, json);
  1037. }
  1038. }).schedule(50);
  1039. // Show this message just once
  1040. if (cssWaits++ == 0) {
  1041. VConsole.log("Assuming CSS loading is not complete, "
  1042. + "postponing render phase. "
  1043. + "(.v-loading-indicator height == 0)");
  1044. }
  1045. } else {
  1046. cssLoaded = true;
  1047. if (cssWaits >= MAX_CSS_WAITS) {
  1048. getLogger().severe("CSS files may have not loaded properly.");
  1049. }
  1050. handleReceivedJSONMessage(new Date(), jsonText, json);
  1051. }
  1052. }
  1053. /**
  1054. * Checks whether or not the CSS is loaded. By default checks the size of
  1055. * the loading indicator element.
  1056. *
  1057. * @return
  1058. */
  1059. protected boolean isCSSLoaded() {
  1060. return cssLoaded
  1061. || getLoadingIndicator().getElement().getOffsetHeight() != 0;
  1062. }
  1063. /**
  1064. * Shows the communication error notification.
  1065. *
  1066. * @param details
  1067. * Optional details for debugging.
  1068. * @param statusCode
  1069. * The status code returned for the request
  1070. *
  1071. */
  1072. protected void showCommunicationError(String details, int statusCode) {
  1073. VConsole.error("Communication error: " + details);
  1074. showError(details, configuration.getCommunicationError());
  1075. }
  1076. /**
  1077. * Shows the authentication error notification.
  1078. *
  1079. * @param details
  1080. * Optional details for debugging.
  1081. */
  1082. protected void showAuthenticationError(String details) {
  1083. VConsole.error("Authentication error: " + details);
  1084. showError(details, configuration.getAuthorizationError());
  1085. }
  1086. /**
  1087. * Shows the session expiration notification.
  1088. *
  1089. * @param details
  1090. * Optional details for debugging.
  1091. */
  1092. public void showSessionExpiredError(String details) {
  1093. VConsole.error("Session expired: " + details);
  1094. showError(details, configuration.getSessionExpiredError());
  1095. }
  1096. /**
  1097. * Shows an error notification.
  1098. *
  1099. * @param details
  1100. * Optional details for debugging.
  1101. * @param message
  1102. * An ErrorMessage describing the error.
  1103. */
  1104. protected void showError(String details, ErrorMessage message) {
  1105. showError(details, message.getCaption(), message.getMessage(),
  1106. message.getUrl());
  1107. }
  1108. /**
  1109. * Shows the error notification.
  1110. *
  1111. * @param details
  1112. * Optional details for debugging.
  1113. */
  1114. private void showError(String details, String caption, String message,
  1115. String url) {
  1116. StringBuilder html = new StringBuilder();
  1117. if (caption != null) {
  1118. html.append("<h1>");
  1119. html.append(caption);
  1120. html.append("</h1>");
  1121. }
  1122. if (message != null) {
  1123. html.append("<p>");
  1124. html.append(message);
  1125. html.append("</p>");
  1126. }
  1127. if (html.length() > 0) {
  1128. // Add error description
  1129. if (details != null) {
  1130. html.append("<p><i style=\"font-size:0.7em\">");
  1131. html.append(details);
  1132. html.append("</i></p>");
  1133. }
  1134. VNotification n = VNotification.createNotification(1000 * 60 * 45,
  1135. uIConnector.getWidget());
  1136. n.addEventListener(new NotificationRedirect(url));
  1137. n.show(html.toString(), VNotification.CENTERED_TOP,
  1138. VNotification.STYLE_SYSTEM);
  1139. } else {
  1140. redirect(url);
  1141. }
  1142. }
  1143. protected void startRequest() {
  1144. if (hasActiveRequest) {
  1145. VConsole.error("Trying to start a new request while another is active");
  1146. }
  1147. hasActiveRequest = true;
  1148. requestStartTime = new Date();
  1149. eventBus.fireEvent(new RequestStartingEvent(this));
  1150. }
  1151. protected void endRequest() {
  1152. if (!hasActiveRequest) {
  1153. VConsole.error("No active request");
  1154. }
  1155. // After checkForPendingVariableBursts() there may be a new active
  1156. // request, so we must set hasActiveRequest to false before, not after,
  1157. // the call. Active requests used to be tracked with an integer counter,
  1158. // so setting it after used to work but not with the #8505 changes.
  1159. hasActiveRequest = false;
  1160. webkitMaybeIgnoringRequests = false;
  1161. if (isApplicationRunning()) {
  1162. checkForPendingVariableBursts();
  1163. runPostRequestHooks(configuration.getRootPanelId());
  1164. }
  1165. // deferring to avoid flickering
  1166. Scheduler.get().scheduleDeferred(new Command() {
  1167. @Override
  1168. public void execute() {
  1169. if (!isApplicationRunning()
  1170. || !(hasActiveRequest() || deferredSendPending)) {
  1171. getLoadingIndicator().hide();
  1172. // If on Liferay and session expiration management is in
  1173. // use, extend session duration on each request.
  1174. // Doing it here rather than before the request to improve
  1175. // responsiveness.
  1176. // Postponed until the end of the next request if other
  1177. // requests still pending.
  1178. extendLiferaySession();
  1179. }
  1180. }
  1181. });
  1182. eventBus.fireEvent(new ResponseHandlingEndedEvent(this));
  1183. }
  1184. /**
  1185. * This method is called after applying uidl change set to application.
  1186. *
  1187. * It will clean current and queued variable change sets. And send next
  1188. * change set if it exists.
  1189. */
  1190. private void checkForPendingVariableBursts() {
  1191. cleanVariableBurst(pendingInvocations);
  1192. if (pendingBursts.size() > 0) {
  1193. for (LinkedHashMap<String, MethodInvocation> pendingBurst : pendingBursts) {
  1194. cleanVariableBurst(pendingBurst);
  1195. }
  1196. LinkedHashMap<String, MethodInvocation> nextBurst = pendingBursts
  1197. .remove(0);
  1198. buildAndSendVariableBurst(nextBurst);
  1199. }
  1200. }
  1201. /**
  1202. * Cleans given queue of variable changes of such changes that came from
  1203. * components that do not exist anymore.
  1204. *
  1205. * @param variableBurst
  1206. */
  1207. private void cleanVariableBurst(
  1208. LinkedHashMap<String, MethodInvocation> variableBurst) {
  1209. Iterator<MethodInvocation> iterator = variableBurst.values().iterator();
  1210. while (iterator.hasNext()) {
  1211. String id = iterator.next().getConnectorId();
  1212. if (!getConnectorMap().hasConnector(id)
  1213. && !getConnectorMap().isDragAndDropPaintable(id)) {
  1214. // variable owner does not exist anymore
  1215. iterator.remove();
  1216. VConsole.log("Removed variable from removed component: " + id);
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * Checks if the client has running or scheduled commands
  1222. */
  1223. private boolean isWorkPending() {
  1224. ConnectorMap connectorMap = getConnectorMap();
  1225. JsArrayObject<ServerConnector> connectors = connectorMap
  1226. .getConnectorsAsJsArray();
  1227. int size = connectors.size();
  1228. for (int i = 0; i < size; i++) {
  1229. ServerConnector conn = connectors.get(i);
  1230. ComponentConnector compConn = null;
  1231. if (conn instanceof ComponentConnector) {
  1232. compConn = (ComponentConnector) conn;
  1233. Widget wgt = compConn.getWidget();
  1234. if (wgt instanceof DeferredWorker) {
  1235. if (((DeferredWorker) wgt).isWorkPending()) {
  1236. return true;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. return false;
  1242. }
  1243. /**
  1244. * Checks if deferred commands are (potentially) still being executed as a
  1245. * result of an update from the server. Returns true if a deferred command
  1246. * might still be executing, false otherwise. This will not work correctly
  1247. * if a deferred command is added in another deferred command.
  1248. * <p>
  1249. * Used by the native "client.isActive" function.
  1250. * </p>
  1251. *
  1252. * @return true if deferred commands are (potentially) being executed, false
  1253. * otherwise
  1254. */
  1255. private boolean isExecutingDeferredCommands() {
  1256. Scheduler s = Scheduler.get();
  1257. if (s instanceof VSchedulerImpl) {
  1258. return ((VSchedulerImpl) s).hasWorkQueued();
  1259. } else {
  1260. return false;
  1261. }
  1262. }
  1263. /**
  1264. * Returns the loading indicator used by this ApplicationConnection
  1265. *
  1266. * @return The loading indicator for this ApplicationConnection
  1267. */
  1268. public VLoadingIndicator getLoadingIndicator() {
  1269. return loadingIndicator;
  1270. }
  1271. /**
  1272. * Determines whether or not the loading indicator is showing.
  1273. *
  1274. * @return true if the loading indicator is visible
  1275. * @deprecated As of 7.1. Use {@link #getLoadingIndicator()} and
  1276. * {@link VLoadingIndicator#isVisible()}.isVisible() instead.
  1277. */
  1278. @Deprecated
  1279. public boolean isLoadingIndicatorVisible() {
  1280. return getLoadingIndicator().isVisible();
  1281. }
  1282. private static native ValueMap parseJSONResponse(String jsonText)
  1283. /*-{
  1284. try {
  1285. return JSON.parse(jsonText);
  1286. } catch (ignored) {
  1287. return eval('(' + jsonText + ')');
  1288. }
  1289. }-*/;
  1290. private void handleReceivedJSONMessage(Date start, String jsonText,
  1291. ValueMap json) {
  1292. handleUIDLMessage(start, jsonText, json);
  1293. }
  1294. /**
  1295. * Gets the id of the last received response. This id can be used by
  1296. * connectors to determine whether new data has been received from the
  1297. * server to avoid doing the same calculations multiple times.
  1298. * <p>
  1299. * No guarantees are made for the structure of the id other than that there
  1300. * will be a new unique value every time a new response with data from the
  1301. * server is received.
  1302. * <p>
  1303. * The initial id when no request has yet been processed is -1.
  1304. *
  1305. * @return and id identifying the response
  1306. */
  1307. public int getLastResponseId() {
  1308. /*
  1309. * The discrepancy between field name and getter name is simply historic
  1310. * - API can't be changed, but the field was repurposed in a more
  1311. * general, yet compatible, use. "Response id" was deemed unsuitable a
  1312. * name, so it was called "server sync id" instead.
  1313. */
  1314. return lastSeenServerSyncId;
  1315. }
  1316. protected void handleUIDLMessage(final Date start, final String jsonText,
  1317. final ValueMap json) {
  1318. if (!responseHandlingLocks.isEmpty()) {
  1319. // Some component is doing something that can't be interrupted
  1320. // (e.g. animation that should be smooth). Enqueue the UIDL
  1321. // message for later processing.
  1322. VConsole.log("Postponing UIDL handling due to lock...");
  1323. pendingUIDLMessages.add(new PendingUIDLMessage(start, jsonText,
  1324. json));
  1325. if (!forceHandleMessage.isRunning()) {
  1326. forceHandleMessage.schedule(MAX_SUSPENDED_TIMEOUT);
  1327. }
  1328. return;
  1329. }
  1330. /*
  1331. * Lock response handling to avoid a situation where something pushed
  1332. * from the server gets processed while waiting for e.g. lazily loaded
  1333. * connectors that are needed for processing the current message.
  1334. */
  1335. final Object lock = new Object();
  1336. suspendReponseHandling(lock);
  1337. VConsole.log("Handling message from server");
  1338. eventBus.fireEvent(new ResponseHandlingStartedEvent(this));
  1339. final int syncId;
  1340. if (json.containsKey(ApplicationConstants.SERVER_SYNC_ID)) {
  1341. syncId = json.getInt(ApplicationConstants.SERVER_SYNC_ID);
  1342. /*
  1343. * Use sync id unless explicitly set as undefined, as is done by
  1344. * e.g. critical server-side notifications
  1345. */
  1346. if (syncId != -1) {
  1347. assert (lastSeenServerSyncId == UNDEFINED_SYNC_ID || syncId == lastSeenServerSyncId + 1) : "Newly retrieved server sync id was not exactly one larger than the previous one (new: "
  1348. + syncId + ", last seen: " + lastSeenServerSyncId + ")";
  1349. lastSeenServerSyncId = syncId;
  1350. }
  1351. } else {
  1352. syncId = -1;
  1353. VConsole.error("Server response didn't contain a sync id. "
  1354. + "Please verify that the server is up-to-date and that the response data has not been modified in transmission.");
  1355. }
  1356. // Handle redirect
  1357. if (json.containsKey("redirect")) {
  1358. String url = json.getValueMap("redirect").getString("url");
  1359. VConsole.log("redirecting to " + url);
  1360. redirect(url);
  1361. return;
  1362. }
  1363. final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
  1364. // Get security key
  1365. if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
  1366. csrfToken = json
  1367. .getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
  1368. }
  1369. VConsole.log(" * Handling resources from server");
  1370. if (json.containsKey("resources")) {
  1371. ValueMap resources = json.getValueMap("resources");
  1372. JsArrayString keyArray = resources.getKeyArray();
  1373. int l = keyArray.length();
  1374. for (int i = 0; i < l; i++) {
  1375. String key = keyArray.get(i);
  1376. resourcesMap.put(key, resources.getAsString(key));
  1377. }
  1378. }
  1379. handleUIDLDuration.logDuration(
  1380. " * Handling resources from server completed", 10);
  1381. VConsole.log(" * Handling type inheritance map from server");
  1382. if (json.containsKey("typeInheritanceMap")) {
  1383. configuration.addComponentInheritanceInfo(json
  1384. .getValueMap("typeInheritanceMap"));
  1385. }
  1386. handleUIDLDuration.logDuration(
  1387. " * Handling type inheritance map from server completed", 10);
  1388. VConsole.log("Handling type mappings from server");
  1389. if (json.containsKey("typeMappings")) {
  1390. configuration.addComponentMappings(
  1391. json.getValueMap("typeMappings"), widgetSet);
  1392. }
  1393. VConsole.log("Handling resource dependencies");
  1394. if (json.containsKey("scriptDependencies")) {
  1395. loadScriptDependencies(json.getJSStringArray("scriptDependencies"));
  1396. }
  1397. if (json.containsKey("styleDependencies")) {
  1398. loadStyleDependencies(json.getJSStringArray("styleDependencies"));
  1399. }
  1400. handleUIDLDuration.logDuration(
  1401. " * Handling type mappings from server completed", 10);
  1402. /*
  1403. * Hook for e.g. TestBench to get details about server peformance
  1404. */
  1405. if (json.containsKey("timings")) {
  1406. serverTimingInfo = json.getValueMap("timings");
  1407. }
  1408. Command c = new Command() {
  1409. private boolean onlyNoLayoutUpdates = true;
  1410. @Override
  1411. public void execute() {
  1412. assert syncId == -1 || syncId == lastSeenServerSyncId;
  1413. handleUIDLDuration.logDuration(" * Loading widgets completed",
  1414. 10);
  1415. Profiler.enter("Handling meta information");
  1416. ValueMap meta = null;
  1417. if (json.containsKey("meta")) {
  1418. VConsole.log(" * Handling meta information");
  1419. meta = json.getValueMap("meta");
  1420. if (meta.containsKey("repaintAll")) {
  1421. prepareRepaintAll();
  1422. }
  1423. if (meta.containsKey("timedRedirect")) {
  1424. final ValueMap timedRedirect = meta
  1425. .getValueMap("timedRedirect");
  1426. if (redirectTimer != null) {
  1427. redirectTimer.cancel();
  1428. }
  1429. redirectTimer = new Timer() {
  1430. @Override
  1431. public void run() {
  1432. redirect(timedRedirect.getString("url"));
  1433. }
  1434. };
  1435. sessionExpirationInterval = timedRedirect
  1436. .getInt("interval");
  1437. }
  1438. }
  1439. Profiler.leave("Handling meta information");
  1440. if (redirectTimer != null) {
  1441. redirectTimer.schedule(1000 * sessionExpirationInterval);
  1442. }
  1443. updatingState = true;
  1444. double processUidlStart = Duration.currentTimeMillis();
  1445. // Ensure that all connectors that we are about to update exist
  1446. JsArrayString createdConnectorIds = createConnectorsIfNeeded(json);
  1447. // Update states, do not fire events
  1448. JsArrayObject<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(
  1449. json, createdConnectorIds);
  1450. /*
  1451. * Doing this here so that locales are available also to the
  1452. * connectors which get a state change event before the UI.
  1453. */
  1454. Profiler.enter("Handling locales");
  1455. VConsole.log(" * Handling locales");
  1456. // Store locale data
  1457. LocaleService
  1458. .addLocales(getUIConnector().getState().localeServiceState.localeData);
  1459. Profiler.leave("Handling locales");
  1460. // Update hierarchy, do not fire events
  1461. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(json);
  1462. // Fire hierarchy change events
  1463. sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
  1464. updateCaptions(pendingStateChangeEvents,
  1465. connectorHierarchyUpdateResult.parentChangedIds);
  1466. delegateToWidget(pendingStateChangeEvents);
  1467. // Fire state change events.
  1468. sendStateChangeEvents(pendingStateChangeEvents);
  1469. // Update of legacy (UIDL) style connectors
  1470. updateVaadin6StyleConnectors(json);
  1471. // Handle any RPC invocations done on the server side
  1472. handleRpcInvocations(json);
  1473. if (json.containsKey("dd")) {
  1474. // response contains data for drag and drop service
  1475. VDragAndDropManager.get().handleServerResponse(
  1476. json.getValueMap("dd"));
  1477. }
  1478. unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  1479. VConsole.log("handleUIDLMessage: "
  1480. + (Duration.currentTimeMillis() - processUidlStart)
  1481. + " ms");
  1482. updatingState = false;
  1483. if (!onlyNoLayoutUpdates) {
  1484. Profiler.enter("Layout processing");
  1485. try {
  1486. LayoutManager layoutManager = getLayoutManager();
  1487. layoutManager.setEverythingNeedsMeasure();
  1488. layoutManager.layoutNow();
  1489. } catch (final Throwable e) {
  1490. VConsole.error(e);
  1491. }
  1492. Profiler.leave("Layout processing");
  1493. }
  1494. if (ApplicationConfiguration.isDebugMode()) {
  1495. Profiler.enter("Dumping state changes to the console");
  1496. VConsole.log(" * Dumping state changes to the console");
  1497. VConsole.dirUIDL(json, ApplicationConnection.this);
  1498. Profiler.leave("Dumping state changes to the console");
  1499. }
  1500. if (meta != null) {
  1501. Profiler.enter("Error handling");
  1502. if (meta.containsKey("appError")) {
  1503. ValueMap error = meta.getValueMap("appError");
  1504. showError(null, error.getString("caption"),
  1505. error.getString("message"),
  1506. error.getString("url"));
  1507. setApplicationRunning(false);
  1508. }
  1509. Profiler.leave("Error handling");
  1510. }
  1511. // TODO build profiling for widget impl loading time
  1512. lastProcessingTime = (int) ((new Date().getTime()) - start
  1513. .getTime());
  1514. totalProcessingTime += lastProcessingTime;
  1515. if (bootstrapTime == 0) {
  1516. bootstrapTime = calculateBootstrapTime();
  1517. if (Profiler.isEnabled() && bootstrapTime != -1) {
  1518. Profiler.logBootstrapTimings();
  1519. }
  1520. }
  1521. VConsole.log(" Processing time was "
  1522. + String.valueOf(lastProcessingTime) + "ms for "
  1523. + jsonText.length() + " characters of JSON");
  1524. VConsole.log("Referenced paintables: " + connectorMap.size());
  1525. if (meta == null || !meta.containsKey("async")) {
  1526. // End the request if the received message was a response,
  1527. // not sent asynchronously
  1528. endRequest();
  1529. }
  1530. resumeResponseHandling(lock);
  1531. if (Profiler.isEnabled()) {
  1532. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1533. @Override
  1534. public void execute() {
  1535. Profiler.logTimings();
  1536. Profiler.reset();
  1537. }
  1538. });
  1539. }
  1540. }
  1541. /**
  1542. * Properly clean up any old stuff to ensure everything is properly
  1543. * reinitialized.
  1544. */
  1545. private void prepareRepaintAll() {
  1546. String uiConnectorId = uIConnector.getConnectorId();
  1547. if (uiConnectorId == null) {
  1548. // Nothing to clear yet
  1549. return;
  1550. }
  1551. // Create fake server response that says that the uiConnector
  1552. // has no children
  1553. JsonObject fakeHierarchy = Json.createObject();
  1554. fakeHierarchy.put(uiConnectorId, Json.createArray());
  1555. JsonObject fakeJson = Json.createObject();
  1556. fakeJson.put("hierarchy", fakeHierarchy);
  1557. ValueMap fakeValueMap = ((JavaScriptObject) fakeJson.toNative())
  1558. .cast();
  1559. // Update hierarchy based on the fake response
  1560. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
  1561. // Send hierarchy events based on the fake update
  1562. sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
  1563. // Unregister all the old connectors that have now been removed
  1564. unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  1565. getLayoutManager().cleanMeasuredSizes();
  1566. }
  1567. private void updateCaptions(
  1568. JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
  1569. FastStringSet parentChangedIds) {
  1570. Profiler.enter("updateCaptions");
  1571. /*
  1572. * Find all components that might need a caption update based on
  1573. * pending state and hierarchy changes
  1574. */
  1575. FastStringSet needsCaptionUpdate = FastStringSet.create();
  1576. needsCaptionUpdate.addAll(parentChangedIds);
  1577. // Find components with potentially changed caption state
  1578. int size = pendingStateChangeEvents.size();
  1579. for (int i = 0; i < size; i++) {
  1580. StateChangeEvent event = pendingStateChangeEvents.get(i);
  1581. if (VCaption.mightChange(event)) {
  1582. ServerConnector connector = event.getConnector();
  1583. needsCaptionUpdate.add(connector.getConnectorId());
  1584. }
  1585. }
  1586. ConnectorMap connectorMap = getConnectorMap();
  1587. // Update captions for all suitable candidates
  1588. JsArrayString dump = needsCaptionUpdate.dump();
  1589. int needsUpdateLength = dump.length();
  1590. for (int i = 0; i < needsUpdateLength; i++) {
  1591. String childId = dump.get(i);
  1592. ServerConnector child = connectorMap.getConnector(childId);
  1593. if (child instanceof ComponentConnector
  1594. && ((ComponentConnector) child)
  1595. .delegateCaptionHandling()) {
  1596. ServerConnector parent = child.getParent();
  1597. if (parent instanceof HasComponentsConnector) {
  1598. Profiler.enter("HasComponentsConnector.updateCaption");
  1599. ((HasComponentsConnector) parent)
  1600. .updateCaption((ComponentConnector) child);
  1601. Profiler.leave("HasComponentsConnector.updateCaption");
  1602. }
  1603. }
  1604. }
  1605. Profiler.leave("updateCaptions");
  1606. }
  1607. private void delegateToWidget(
  1608. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  1609. Profiler.enter("@DelegateToWidget");
  1610. VConsole.log(" * Running @DelegateToWidget");
  1611. // Keep track of types that have no @DelegateToWidget in their
  1612. // state to optimize performance
  1613. FastStringSet noOpTypes = FastStringSet.create();
  1614. int size = pendingStateChangeEvents.size();
  1615. for (int eventIndex = 0; eventIndex < size; eventIndex++) {
  1616. StateChangeEvent sce = pendingStateChangeEvents
  1617. .get(eventIndex);
  1618. ServerConnector connector = sce.getConnector();
  1619. if (connector instanceof ComponentConnector) {
  1620. String className = connector.getClass().getName();
  1621. if (noOpTypes.contains(className)) {
  1622. continue;
  1623. }
  1624. ComponentConnector component = (ComponentConnector) connector;
  1625. Type stateType = AbstractConnector
  1626. .getStateType(component);
  1627. JsArrayString delegateToWidgetProperties = stateType
  1628. .getDelegateToWidgetProperties();
  1629. if (delegateToWidgetProperties == null) {
  1630. noOpTypes.add(className);
  1631. continue;
  1632. }
  1633. int length = delegateToWidgetProperties.length();
  1634. for (int i = 0; i < length; i++) {
  1635. String propertyName = delegateToWidgetProperties
  1636. .get(i);
  1637. if (sce.hasPropertyChanged(propertyName)) {
  1638. Property property = stateType
  1639. .getProperty(propertyName);
  1640. String method = property
  1641. .getDelegateToWidgetMethodName();
  1642. Profiler.enter("doDelegateToWidget");
  1643. doDelegateToWidget(component, property, method);
  1644. Profiler.leave("doDelegateToWidget");
  1645. }
  1646. }
  1647. }
  1648. }
  1649. Profiler.leave("@DelegateToWidget");
  1650. }
  1651. private void doDelegateToWidget(ComponentConnector component,
  1652. Property property, String methodName) {
  1653. Type type = TypeData.getType(component.getClass());
  1654. try {
  1655. Type widgetType = type.getMethod("getWidget")
  1656. .getReturnType();
  1657. Widget widget = component.getWidget();
  1658. Object propertyValue = property.getValue(component
  1659. .getState());
  1660. widgetType.getMethod(methodName).invoke(widget,
  1661. propertyValue);
  1662. } catch (NoDataException e) {
  1663. throw new RuntimeException(
  1664. "Missing data needed to invoke @DelegateToWidget for "
  1665. + component.getClass().getSimpleName(), e);
  1666. }
  1667. }
  1668. /**
  1669. * Sends the state change events created while updating the state
  1670. * information.
  1671. *
  1672. * This must be called after hierarchy change listeners have been
  1673. * called. At least caption updates for the parent are strange if
  1674. * fired from state change listeners and thus calls the parent
  1675. * BEFORE the parent is aware of the child (through a
  1676. * ConnectorHierarchyChangedEvent)
  1677. *
  1678. * @param pendingStateChangeEvents
  1679. * The events to send
  1680. */
  1681. private void sendStateChangeEvents(
  1682. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  1683. Profiler.enter("sendStateChangeEvents");
  1684. VConsole.log(" * Sending state change events");
  1685. int size = pendingStateChangeEvents.size();
  1686. for (int i = 0; i < size; i++) {
  1687. StateChangeEvent sce = pendingStateChangeEvents.get(i);
  1688. try {
  1689. sce.getConnector().fireEvent(sce);
  1690. } catch (final Throwable e) {
  1691. VConsole.error(e);
  1692. }
  1693. }
  1694. Profiler.leave("sendStateChangeEvents");
  1695. }
  1696. private void verifyConnectorHierarchy() {
  1697. Profiler.enter("verifyConnectorHierarchy - this is only performed in debug mode");
  1698. JsArrayObject<ServerConnector> currentConnectors = connectorMap
  1699. .getConnectorsAsJsArray();
  1700. int size = currentConnectors.size();
  1701. for (int i = 0; i < size; i++) {
  1702. ServerConnector c = currentConnectors.get(i);
  1703. if (c.getParent() != null) {
  1704. if (!c.getParent().getChildren().contains(c)) {
  1705. VConsole.error("ERROR: Connector "
  1706. + c.getConnectorId()
  1707. + " is connected to a parent but the parent ("
  1708. + c.getParent().getConnectorId()
  1709. + ") does not contain the connector");
  1710. }
  1711. } else if (c == getUIConnector()) {
  1712. // UIConnector for this connection, ignore
  1713. } else if (c instanceof WindowConnector
  1714. && getUIConnector().hasSubWindow(
  1715. (WindowConnector) c)) {
  1716. // Sub window attached to this UIConnector, ignore
  1717. } else {
  1718. // The connector has been detached from the
  1719. // hierarchy but was not unregistered.
  1720. VConsole.error("ERROR: Connector "
  1721. + c.getConnectorId()
  1722. + " is not attached to a parent but has not been unregistered");
  1723. }
  1724. }
  1725. Profiler.leave("verifyConnectorHierarchy - this is only performed in debug mode");
  1726. }
  1727. private void unregisterRemovedConnectors(
  1728. FastStringSet detachedConnectors) {
  1729. Profiler.enter("unregisterRemovedConnectors");
  1730. JsArrayString detachedArray = detachedConnectors.dump();
  1731. for (int i = 0; i < detachedArray.length(); i++) {
  1732. ServerConnector connector = connectorMap
  1733. .getConnector(detachedArray.get(i));
  1734. Profiler.enter("unregisterRemovedConnectors unregisterConnector");
  1735. connectorMap.unregisterConnector(connector);
  1736. Profiler.leave("unregisterRemovedConnectors unregisterConnector");
  1737. }
  1738. if (ApplicationConfiguration.isDebugMode()) {
  1739. // Do some extra checking if we're in debug mode (i.e. debug
  1740. // window is open)
  1741. verifyConnectorHierarchy();
  1742. }
  1743. VConsole.log("* Unregistered " + detachedArray.length()
  1744. + " connectors");
  1745. Profiler.leave("unregisterRemovedConnectors");
  1746. }
  1747. private JsArrayString createConnectorsIfNeeded(ValueMap json) {
  1748. VConsole.log(" * Creating connectors (if needed)");
  1749. JsArrayString createdConnectors = JavaScriptObject
  1750. .createArray().cast();
  1751. if (!json.containsKey("types")) {
  1752. return createdConnectors;
  1753. }
  1754. Profiler.enter("Creating connectors");
  1755. ValueMap types = json.getValueMap("types");
  1756. JsArrayString keyArray = types.getKeyArray();
  1757. for (int i = 0; i < keyArray.length(); i++) {
  1758. try {
  1759. String connectorId = keyArray.get(i);
  1760. ServerConnector connector = connectorMap
  1761. .getConnector(connectorId);
  1762. if (connector != null) {
  1763. continue;
  1764. }
  1765. // Always do layouts if there's at least one new
  1766. // connector
  1767. onlyNoLayoutUpdates = false;
  1768. int connectorType = Integer.parseInt(types
  1769. .getString(connectorId));
  1770. Class<? extends ServerConnector> connectorClass = configuration
  1771. .getConnectorClassByEncodedTag(connectorType);
  1772. // Connector does not exist so we must create it
  1773. if (connectorClass != uIConnector.getClass()) {
  1774. // create, initialize and register the paintable
  1775. Profiler.enter("ApplicationConnection.getConnector");
  1776. connector = getConnector(connectorId, connectorType);
  1777. Profiler.leave("ApplicationConnection.getConnector");
  1778. createdConnectors.push(connectorId);
  1779. } else {
  1780. // First UIConnector update. Before this the
  1781. // UIConnector has been created but not
  1782. // initialized as the connector id has not been
  1783. // known
  1784. connectorMap.registerConnector(connectorId,
  1785. uIConnector);
  1786. uIConnector.doInit(connectorId,
  1787. ApplicationConnection.this);
  1788. createdConnectors.push(connectorId);
  1789. }
  1790. } catch (final Throwable e) {
  1791. VConsole.error(e);
  1792. }
  1793. }
  1794. Profiler.leave("Creating connectors");
  1795. return createdConnectors;
  1796. }
  1797. private void updateVaadin6StyleConnectors(ValueMap json) {
  1798. Profiler.enter("updateVaadin6StyleConnectors");
  1799. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  1800. int length = changes.length();
  1801. // Must always do layout if there's even a single legacy update
  1802. if (length != 0) {
  1803. onlyNoLayoutUpdates = false;
  1804. }
  1805. VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
  1806. // update paintables
  1807. for (int i = 0; i < length; i++) {
  1808. try {
  1809. final UIDL change = changes.get(i).cast();
  1810. final UIDL uidl = change.getChildUIDL(0);
  1811. String connectorId = uidl.getId();
  1812. final ComponentConnector legacyConnector = (ComponentConnector) connectorMap
  1813. .getConnector(connectorId);
  1814. if (legacyConnector instanceof Paintable) {
  1815. String key = null;
  1816. if (Profiler.isEnabled()) {
  1817. key = "updateFromUIDL for "
  1818. + legacyConnector.getClass()
  1819. .getSimpleName();
  1820. Profiler.enter(key);
  1821. }
  1822. ((Paintable) legacyConnector).updateFromUIDL(uidl,
  1823. ApplicationConnection.this);
  1824. if (Profiler.isEnabled()) {
  1825. Profiler.leave(key);
  1826. }
  1827. } else if (legacyConnector == null) {
  1828. VConsole.error("Received update for "
  1829. + uidl.getTag()
  1830. + ", but there is no such paintable ("
  1831. + connectorId + ") rendered.");
  1832. } else {
  1833. VConsole.error("Server sent Vaadin 6 style updates for "
  1834. + Util.getConnectorString(legacyConnector)
  1835. + " but this is not a Vaadin 6 Paintable");
  1836. }
  1837. } catch (final Throwable e) {
  1838. VConsole.error(e);
  1839. }
  1840. }
  1841. Profiler.leave("updateVaadin6StyleConnectors");
  1842. }
  1843. private void sendHierarchyChangeEvents(
  1844. JsArrayObject<ConnectorHierarchyChangeEvent> events) {
  1845. int eventCount = events.size();
  1846. if (eventCount == 0) {
  1847. return;
  1848. }
  1849. Profiler.enter("sendHierarchyChangeEvents");
  1850. VConsole.log(" * Sending hierarchy change events");
  1851. for (int i = 0; i < eventCount; i++) {
  1852. ConnectorHierarchyChangeEvent event = events.get(i);
  1853. try {
  1854. logHierarchyChange(event);
  1855. event.getConnector().fireEvent(event);
  1856. } catch (final Throwable e) {
  1857. VConsole.error(e);
  1858. }
  1859. }
  1860. Profiler.leave("sendHierarchyChangeEvents");
  1861. }
  1862. private void logHierarchyChange(ConnectorHierarchyChangeEvent event) {
  1863. if (true) {
  1864. // Always disabled for now. Can be enabled manually
  1865. return;
  1866. }
  1867. VConsole.log("Hierarchy changed for "
  1868. + Util.getConnectorString(event.getConnector()));
  1869. String oldChildren = "* Old children: ";
  1870. for (ComponentConnector child : event.getOldChildren()) {
  1871. oldChildren += Util.getConnectorString(child) + " ";
  1872. }
  1873. VConsole.log(oldChildren);
  1874. String newChildren = "* New children: ";
  1875. HasComponentsConnector parent = (HasComponentsConnector) event
  1876. .getConnector();
  1877. for (ComponentConnector child : parent.getChildComponents()) {
  1878. newChildren += Util.getConnectorString(child) + " ";
  1879. }
  1880. VConsole.log(newChildren);
  1881. }
  1882. private JsArrayObject<StateChangeEvent> updateConnectorState(
  1883. ValueMap json, JsArrayString createdConnectorIds) {
  1884. JsArrayObject<StateChangeEvent> events = JavaScriptObject
  1885. .createArray().cast();
  1886. VConsole.log(" * Updating connector states");
  1887. if (!json.containsKey("state")) {
  1888. return events;
  1889. }
  1890. Profiler.enter("updateConnectorState");
  1891. FastStringSet remainingNewConnectors = FastStringSet.create();
  1892. remainingNewConnectors.addAll(createdConnectorIds);
  1893. // set states for all paintables mentioned in "state"
  1894. ValueMap states = json.getValueMap("state");
  1895. JsArrayString keyArray = states.getKeyArray();
  1896. for (int i = 0; i < keyArray.length(); i++) {
  1897. try {
  1898. String connectorId = keyArray.get(i);
  1899. ServerConnector connector = connectorMap
  1900. .getConnector(connectorId);
  1901. if (null != connector) {
  1902. Profiler.enter("updateConnectorState inner loop");
  1903. if (Profiler.isEnabled()) {
  1904. Profiler.enter("Decode connector state "
  1905. + connector.getClass().getSimpleName());
  1906. }
  1907. JavaScriptObject jso = states
  1908. .getJavaScriptObject(connectorId);
  1909. JsonObject stateJson = Util.jso2json(jso);
  1910. if (connector instanceof HasJavaScriptConnectorHelper) {
  1911. ((HasJavaScriptConnectorHelper) connector)
  1912. .getJavascriptConnectorHelper()
  1913. .setNativeState(jso);
  1914. }
  1915. SharedState state = connector.getState();
  1916. Type stateType = new Type(state.getClass()
  1917. .getName(), null);
  1918. if (onlyNoLayoutUpdates) {
  1919. Profiler.enter("updateConnectorState @NoLayout handling");
  1920. for (String propertyName : stateJson.keys()) {
  1921. Property property = stateType
  1922. .getProperty(propertyName);
  1923. if (!property.isNoLayout()) {
  1924. onlyNoLayoutUpdates = false;
  1925. break;
  1926. }
  1927. }
  1928. Profiler.leave("updateConnectorState @NoLayout handling");
  1929. }
  1930. Profiler.enter("updateConnectorState decodeValue");
  1931. JsonDecoder.decodeValue(stateType, stateJson,
  1932. state, ApplicationConnection.this);
  1933. Profiler.leave("updateConnectorState decodeValue");
  1934. if (Profiler.isEnabled()) {
  1935. Profiler.leave("Decode connector state "
  1936. + connector.getClass().getSimpleName());
  1937. }
  1938. Profiler.enter("updateConnectorState create event");
  1939. boolean isNewConnector = remainingNewConnectors
  1940. .contains(connectorId);
  1941. if (isNewConnector) {
  1942. remainingNewConnectors.remove(connectorId);
  1943. }
  1944. StateChangeEvent event = new StateChangeEvent(
  1945. connector, stateJson, isNewConnector);
  1946. events.add(event);
  1947. Profiler.leave("updateConnectorState create event");
  1948. Profiler.leave("updateConnectorState inner loop");
  1949. }
  1950. } catch (final Throwable e) {
  1951. VConsole.error(e);
  1952. }
  1953. }
  1954. Profiler.enter("updateConnectorState newWithoutState");
  1955. // Fire events for properties using the default value for newly
  1956. // created connectors even if there were no state changes
  1957. JsArrayString dump = remainingNewConnectors.dump();
  1958. int length = dump.length();
  1959. for (int i = 0; i < length; i++) {
  1960. String connectorId = dump.get(i);
  1961. ServerConnector connector = connectorMap
  1962. .getConnector(connectorId);
  1963. StateChangeEvent event = new StateChangeEvent(connector,
  1964. Json.createObject(), true);
  1965. events.add(event);
  1966. }
  1967. Profiler.leave("updateConnectorState newWithoutState");
  1968. Profiler.leave("updateConnectorState");
  1969. return events;
  1970. }
  1971. /**
  1972. * Updates the connector hierarchy and returns a list of events that
  1973. * should be fired after update of the hierarchy and the state is
  1974. * done.
  1975. *
  1976. * @param json
  1977. * The JSON containing the hierarchy information
  1978. * @return A collection of events that should be fired when update
  1979. * of hierarchy and state is complete and a list of all
  1980. * connectors for which the parent has changed
  1981. */
  1982. private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
  1983. ValueMap json) {
  1984. ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
  1985. VConsole.log(" * Updating connector hierarchy");
  1986. if (!json.containsKey("hierarchy")) {
  1987. return result;
  1988. }
  1989. Profiler.enter("updateConnectorHierarchy");
  1990. FastStringSet maybeDetached = FastStringSet.create();
  1991. ValueMap hierarchies = json.getValueMap("hierarchy");
  1992. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  1993. for (int i = 0; i < hierarchyKeys.length(); i++) {
  1994. try {
  1995. Profiler.enter("updateConnectorHierarchy hierarchy entry");
  1996. String connectorId = hierarchyKeys.get(i);
  1997. ServerConnector parentConnector = connectorMap
  1998. .getConnector(connectorId);
  1999. JsArrayString childConnectorIds = hierarchies
  2000. .getJSStringArray(connectorId);
  2001. int childConnectorSize = childConnectorIds.length();
  2002. Profiler.enter("updateConnectorHierarchy find new connectors");
  2003. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  2004. List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
  2005. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  2006. String childConnectorId = childConnectorIds
  2007. .get(connectorIndex);
  2008. ServerConnector childConnector = connectorMap
  2009. .getConnector(childConnectorId);
  2010. if (childConnector == null) {
  2011. VConsole.error("Hierarchy claims that "
  2012. + childConnectorId
  2013. + " is a child for "
  2014. + connectorId
  2015. + " ("
  2016. + parentConnector.getClass().getName()
  2017. + ") but no connector with id "
  2018. + childConnectorId
  2019. + " has been registered. "
  2020. + "More information might be available in the server-side log if assertions are enabled");
  2021. continue;
  2022. }
  2023. newChildren.add(childConnector);
  2024. if (childConnector instanceof ComponentConnector) {
  2025. newComponents
  2026. .add((ComponentConnector) childConnector);
  2027. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  2028. throw new IllegalStateException(
  2029. Util.getConnectorString(childConnector)
  2030. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  2031. }
  2032. if (childConnector.getParent() != parentConnector) {
  2033. childConnector.setParent(parentConnector);
  2034. result.parentChangedIds.add(childConnectorId);
  2035. // Not detached even if previously removed from
  2036. // parent
  2037. maybeDetached.remove(childConnectorId);
  2038. }
  2039. }
  2040. Profiler.leave("updateConnectorHierarchy find new connectors");
  2041. // TODO This check should be done on the server side in
  2042. // the future so the hierarchy update is only sent when
  2043. // something actually has changed
  2044. List<ServerConnector> oldChildren = parentConnector
  2045. .getChildren();
  2046. boolean actuallyChanged = !Util.collectionsEquals(
  2047. oldChildren, newChildren);
  2048. if (!actuallyChanged) {
  2049. continue;
  2050. }
  2051. Profiler.enter("updateConnectorHierarchy handle HasComponentsConnector");
  2052. if (parentConnector instanceof HasComponentsConnector) {
  2053. HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
  2054. List<ComponentConnector> oldComponents = ccc
  2055. .getChildComponents();
  2056. if (!Util.collectionsEquals(oldComponents,
  2057. newComponents)) {
  2058. // Fire change event if the hierarchy has
  2059. // changed
  2060. ConnectorHierarchyChangeEvent event = GWT
  2061. .create(ConnectorHierarchyChangeEvent.class);
  2062. event.setOldChildren(oldComponents);
  2063. event.setConnector(parentConnector);
  2064. ccc.setChildComponents(newComponents);
  2065. result.events.add(event);
  2066. }
  2067. } else if (!newComponents.isEmpty()) {
  2068. VConsole.error("Hierachy claims "
  2069. + Util.getConnectorString(parentConnector)
  2070. + " has component children even though it isn't a HasComponentsConnector");
  2071. }
  2072. Profiler.leave("updateConnectorHierarchy handle HasComponentsConnector");
  2073. Profiler.enter("updateConnectorHierarchy setChildren");
  2074. parentConnector.setChildren(newChildren);
  2075. Profiler.leave("updateConnectorHierarchy setChildren");
  2076. Profiler.enter("updateConnectorHierarchy find removed children");
  2077. /*
  2078. * Find children removed from this parent and mark for
  2079. * removal unless they are already attached to some
  2080. * other parent.
  2081. */
  2082. for (ServerConnector oldChild : oldChildren) {
  2083. if (oldChild.getParent() != parentConnector) {
  2084. // Ignore if moved to some other connector
  2085. continue;
  2086. }
  2087. if (!newChildren.contains(oldChild)) {
  2088. /*
  2089. * Consider child detached for now, will be
  2090. * cleared if it is later on added to some other
  2091. * parent.
  2092. */
  2093. maybeDetached.add(oldChild.getConnectorId());
  2094. }
  2095. }
  2096. Profiler.leave("updateConnectorHierarchy find removed children");
  2097. } catch (final Throwable e) {
  2098. VConsole.error(e);
  2099. } finally {
  2100. Profiler.leave("updateConnectorHierarchy hierarchy entry");
  2101. }
  2102. }
  2103. Profiler.enter("updateConnectorHierarchy detach removed connectors");
  2104. /*
  2105. * Connector is in maybeDetached at this point if it has been
  2106. * removed from its parent but not added to any other parent
  2107. */
  2108. JsArrayString maybeDetachedArray = maybeDetached.dump();
  2109. for (int i = 0; i < maybeDetachedArray.length(); i++) {
  2110. ServerConnector removed = connectorMap
  2111. .getConnector(maybeDetachedArray.get(i));
  2112. recursivelyDetach(removed, result.events,
  2113. result.detachedConnectorIds);
  2114. }
  2115. Profiler.leave("updateConnectorHierarchy detach removed connectors");
  2116. if (result.events.size() != 0) {
  2117. onlyNoLayoutUpdates = false;
  2118. }
  2119. Profiler.leave("updateConnectorHierarchy");
  2120. return result;
  2121. }
  2122. private void recursivelyDetach(ServerConnector connector,
  2123. JsArrayObject<ConnectorHierarchyChangeEvent> events,
  2124. FastStringSet detachedConnectors) {
  2125. detachedConnectors.add(connector.getConnectorId());
  2126. /*
  2127. * Reset state in an attempt to keep it consistent with the
  2128. * hierarchy. No children and no parent is the initial situation
  2129. * for the hierarchy, so changing the state to its initial value
  2130. * is the closest we can get without data from the server.
  2131. * #10151
  2132. */
  2133. Profiler.enter("ApplicationConnection recursivelyDetach reset state");
  2134. try {
  2135. Profiler.enter("ApplicationConnection recursivelyDetach reset state - getStateType");
  2136. Type stateType = AbstractConnector.getStateType(connector);
  2137. Profiler.leave("ApplicationConnection recursivelyDetach reset state - getStateType");
  2138. // Empty state instance to get default property values from
  2139. Profiler.enter("ApplicationConnection recursivelyDetach reset state - createInstance");
  2140. Object defaultState = stateType.createInstance();
  2141. Profiler.leave("ApplicationConnection recursivelyDetach reset state - createInstance");
  2142. if (connector instanceof AbstractConnector) {
  2143. // optimization as the loop setting properties is very
  2144. // slow, especially on IE8
  2145. replaceState((AbstractConnector) connector,
  2146. defaultState);
  2147. } else {
  2148. SharedState state = connector.getState();
  2149. Profiler.enter("ApplicationConnection recursivelyDetach reset state - properties");
  2150. JsArrayObject<Property> properties = stateType
  2151. .getPropertiesAsArray();
  2152. int size = properties.size();
  2153. for (int i = 0; i < size; i++) {
  2154. Property property = properties.get(i);
  2155. property.setValue(state,
  2156. property.getValue(defaultState));
  2157. }
  2158. Profiler.leave("ApplicationConnection recursivelyDetach reset state - properties");
  2159. }
  2160. } catch (NoDataException e) {
  2161. throw new RuntimeException("Can't reset state for "
  2162. + Util.getConnectorString(connector), e);
  2163. } finally {
  2164. Profiler.leave("ApplicationConnection recursivelyDetach reset state");
  2165. }
  2166. Profiler.enter("ApplicationConnection recursivelyDetach perform detach");
  2167. /*
  2168. * Recursively detach children to make sure they get
  2169. * setParent(null) and hierarchy change events as needed.
  2170. */
  2171. for (ServerConnector child : connector.getChildren()) {
  2172. /*
  2173. * Server doesn't send updated child data for removed
  2174. * connectors -> ignore child that still seems to be a child
  2175. * of this connector although it has been moved to some part
  2176. * of the hierarchy that is not detached.
  2177. */
  2178. if (child.getParent() != connector) {
  2179. continue;
  2180. }
  2181. recursivelyDetach(child, events, detachedConnectors);
  2182. }
  2183. Profiler.leave("ApplicationConnection recursivelyDetach perform detach");
  2184. /*
  2185. * Clear child list and parent
  2186. */
  2187. Profiler.enter("ApplicationConnection recursivelyDetach clear children and parent");
  2188. connector
  2189. .setChildren(Collections.<ServerConnector> emptyList());
  2190. connector.setParent(null);
  2191. Profiler.leave("ApplicationConnection recursivelyDetach clear children and parent");
  2192. /*
  2193. * Create an artificial hierarchy event for containers to give
  2194. * it a chance to clean up after its children if it has any
  2195. */
  2196. Profiler.enter("ApplicationConnection recursivelyDetach create hierarchy event");
  2197. if (connector instanceof HasComponentsConnector) {
  2198. HasComponentsConnector ccc = (HasComponentsConnector) connector;
  2199. List<ComponentConnector> oldChildren = ccc
  2200. .getChildComponents();
  2201. if (!oldChildren.isEmpty()) {
  2202. /*
  2203. * HasComponentsConnector has a separate child component
  2204. * list that should also be cleared
  2205. */
  2206. ccc.setChildComponents(Collections
  2207. .<ComponentConnector> emptyList());
  2208. // Create event and add it to the list of pending events
  2209. ConnectorHierarchyChangeEvent event = GWT
  2210. .create(ConnectorHierarchyChangeEvent.class);
  2211. event.setConnector(connector);
  2212. event.setOldChildren(oldChildren);
  2213. events.add(event);
  2214. }
  2215. }
  2216. Profiler.leave("ApplicationConnection recursivelyDetach create hierarchy event");
  2217. }
  2218. private native void replaceState(AbstractConnector connector,
  2219. Object defaultState)
  2220. /*-{
  2221. connector.@com.vaadin.client.ui.AbstractConnector::state = defaultState;
  2222. }-*/;
  2223. private void handleRpcInvocations(ValueMap json) {
  2224. if (json.containsKey("rpc")) {
  2225. Profiler.enter("handleRpcInvocations");
  2226. VConsole.log(" * Performing server to client RPC calls");
  2227. JsonArray rpcCalls = Util.jso2json(json
  2228. .getJavaScriptObject("rpc"));
  2229. int rpcLength = rpcCalls.length();
  2230. for (int i = 0; i < rpcLength; i++) {
  2231. try {
  2232. JsonArray rpcCall = rpcCalls.getArray(i);
  2233. MethodInvocation invocation = rpcManager
  2234. .parseAndApplyInvocation(rpcCall,
  2235. ApplicationConnection.this);
  2236. if (onlyNoLayoutUpdates
  2237. && !RpcManager.getMethod(invocation)
  2238. .isNoLayout()) {
  2239. onlyNoLayoutUpdates = false;
  2240. }
  2241. } catch (final Throwable e) {
  2242. VConsole.error(e);
  2243. }
  2244. }
  2245. Profiler.leave("handleRpcInvocations");
  2246. }
  2247. }
  2248. };
  2249. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  2250. }
  2251. private void loadStyleDependencies(JsArrayString dependencies) {
  2252. // Assuming no reason to interpret in a defined order
  2253. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  2254. @Override
  2255. public void onLoad(ResourceLoadEvent event) {
  2256. ApplicationConfiguration.endDependencyLoading();
  2257. }
  2258. @Override
  2259. public void onError(ResourceLoadEvent event) {
  2260. VConsole.error(event.getResourceUrl()
  2261. + " could not be loaded, or the load detection failed because the stylesheet is empty.");
  2262. // The show must go on
  2263. onLoad(event);
  2264. }
  2265. };
  2266. ResourceLoader loader = ResourceLoader.get();
  2267. for (int i = 0; i < dependencies.length(); i++) {
  2268. String url = translateVaadinUri(dependencies.get(i));
  2269. ApplicationConfiguration.startDependencyLoading();
  2270. loader.loadStylesheet(url, resourceLoadListener);
  2271. }
  2272. }
  2273. private void loadScriptDependencies(final JsArrayString dependencies) {
  2274. if (dependencies.length() == 0) {
  2275. return;
  2276. }
  2277. // Listener that loads the next when one is completed
  2278. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  2279. @Override
  2280. public void onLoad(ResourceLoadEvent event) {
  2281. if (dependencies.length() != 0) {
  2282. String url = translateVaadinUri(dependencies.shift());
  2283. ApplicationConfiguration.startDependencyLoading();
  2284. // Load next in chain (hopefully already preloaded)
  2285. event.getResourceLoader().loadScript(url, this);
  2286. }
  2287. // Call start for next before calling end for current
  2288. ApplicationConfiguration.endDependencyLoading();
  2289. }
  2290. @Override
  2291. public void onError(ResourceLoadEvent event) {
  2292. VConsole.error(event.getResourceUrl() + " could not be loaded.");
  2293. // The show must go on
  2294. onLoad(event);
  2295. }
  2296. };
  2297. ResourceLoader loader = ResourceLoader.get();
  2298. // Start chain by loading first
  2299. String url = translateVaadinUri(dependencies.shift());
  2300. ApplicationConfiguration.startDependencyLoading();
  2301. loader.loadScript(url, resourceLoadListener);
  2302. if (ResourceLoader.supportsInOrderScriptExecution()) {
  2303. for (int i = 0; i < dependencies.length(); i++) {
  2304. String preloadUrl = translateVaadinUri(dependencies.get(i));
  2305. loader.loadScript(preloadUrl, null);
  2306. }
  2307. } else {
  2308. // Preload all remaining
  2309. for (int i = 0; i < dependencies.length(); i++) {
  2310. String preloadUrl = translateVaadinUri(dependencies.get(i));
  2311. loader.preloadResource(preloadUrl, null);
  2312. }
  2313. }
  2314. }
  2315. // Redirect browser, null reloads current page
  2316. private static native void redirect(String url)
  2317. /*-{
  2318. if (url) {
  2319. $wnd.location = url;
  2320. } else {
  2321. $wnd.location.reload(false);
  2322. }
  2323. }-*/;
  2324. private void addVariableToQueue(String connectorId, String variableName,
  2325. Object value, boolean immediate) {
  2326. boolean lastOnly = !immediate;
  2327. // note that type is now deduced from value
  2328. addMethodInvocationToQueue(new LegacyChangeVariablesInvocation(
  2329. connectorId, variableName, value), lastOnly, lastOnly);
  2330. }
  2331. /**
  2332. * Adds an explicit RPC method invocation to the send queue.
  2333. *
  2334. * @since 7.0
  2335. *
  2336. * @param invocation
  2337. * RPC method invocation
  2338. * @param delayed
  2339. * <code>false</code> to trigger sending within a short time
  2340. * window (possibly combining subsequent calls to a single
  2341. * request), <code>true</code> to let the framework delay sending
  2342. * of RPC calls and variable changes until the next non-delayed
  2343. * change
  2344. * @param lastOnly
  2345. * <code>true</code> to remove all previously delayed invocations
  2346. * of the same method that were also enqueued with lastonly set
  2347. * to <code>true</code>. <code>false</code> to add invocation to
  2348. * the end of the queue without touching previously enqueued
  2349. * invocations.
  2350. */
  2351. public void addMethodInvocationToQueue(MethodInvocation invocation,
  2352. boolean delayed, boolean lastOnly) {
  2353. if (!isApplicationRunning()) {
  2354. getLogger()
  2355. .warning(
  2356. "Trying to invoke method on not yet started or stopped application");
  2357. return;
  2358. }
  2359. String tag;
  2360. if (lastOnly) {
  2361. tag = invocation.getLastOnlyTag();
  2362. assert !tag.matches("\\d+") : "getLastOnlyTag value must have at least one non-digit character";
  2363. pendingInvocations.remove(tag);
  2364. } else {
  2365. tag = Integer.toString(lastInvocationTag++);
  2366. }
  2367. pendingInvocations.put(tag, invocation);
  2368. if (!delayed) {
  2369. sendPendingVariableChanges();
  2370. }
  2371. }
  2372. /**
  2373. * Removes any pending invocation of the given method from the queue
  2374. *
  2375. * @param invocation
  2376. * The invocation to remove
  2377. */
  2378. public void removePendingInvocations(MethodInvocation invocation) {
  2379. Iterator<MethodInvocation> iter = pendingInvocations.values()
  2380. .iterator();
  2381. while (iter.hasNext()) {
  2382. MethodInvocation mi = iter.next();
  2383. if (mi.equals(invocation)) {
  2384. iter.remove();
  2385. }
  2386. }
  2387. }
  2388. /**
  2389. * This method sends currently queued variable changes to server. It is
  2390. * called when immediate variable update must happen.
  2391. *
  2392. * To ensure correct order for variable changes (due servers multithreading
  2393. * or network), we always wait for active request to be handler before
  2394. * sending a new one. If there is an active request, we will put varible
  2395. * "burst" to queue that will be purged after current request is handled.
  2396. *
  2397. */
  2398. public void sendPendingVariableChanges() {
  2399. if (!deferredSendPending) {
  2400. deferredSendPending = true;
  2401. Scheduler.get().scheduleFinally(sendPendingCommand);
  2402. }
  2403. }
  2404. private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
  2405. @Override
  2406. public void execute() {
  2407. deferredSendPending = false;
  2408. doSendPendingVariableChanges();
  2409. }
  2410. };
  2411. private boolean deferredSendPending = false;
  2412. private void doSendPendingVariableChanges() {
  2413. if (isApplicationRunning()) {
  2414. if (hasActiveRequest() || (push != null && !push.isActive())) {
  2415. // skip empty queues if there are pending bursts to be sent
  2416. if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
  2417. pendingBursts.add(pendingInvocations);
  2418. pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
  2419. // Keep tag string short
  2420. lastInvocationTag = 0;
  2421. }
  2422. } else {
  2423. buildAndSendVariableBurst(pendingInvocations);
  2424. }
  2425. } else {
  2426. getLogger()
  2427. .warning(
  2428. "Trying to send variable changes from not yet started or stopped application");
  2429. return;
  2430. }
  2431. }
  2432. /**
  2433. * Build the variable burst and send it to server.
  2434. *
  2435. * When sync is forced, we also force sending of all pending variable-bursts
  2436. * at the same time. This is ok as we can assume that DOM will never be
  2437. * updated after this.
  2438. *
  2439. * @param pendingInvocations
  2440. * List of RPC method invocations to send
  2441. */
  2442. private void buildAndSendVariableBurst(
  2443. LinkedHashMap<String, MethodInvocation> pendingInvocations) {
  2444. boolean showLoadingIndicator = false;
  2445. JsonArray reqJson = Json.createArray();
  2446. if (!pendingInvocations.isEmpty()) {
  2447. if (ApplicationConfiguration.isDebugMode()) {
  2448. Util.logVariableBurst(this, pendingInvocations.values());
  2449. }
  2450. for (MethodInvocation invocation : pendingInvocations.values()) {
  2451. JsonArray invocationJson = Json.createArray();
  2452. invocationJson.set(0, invocation.getConnectorId());
  2453. invocationJson.set(1, invocation.getInterfaceName());
  2454. invocationJson.set(2, invocation.getMethodName());
  2455. JsonArray paramJson = Json.createArray();
  2456. Type[] parameterTypes = null;
  2457. if (!isLegacyVariableChange(invocation)
  2458. && !isJavascriptRpc(invocation)) {
  2459. try {
  2460. Type type = new Type(invocation.getInterfaceName(),
  2461. null);
  2462. Method method = type.getMethod(invocation
  2463. .getMethodName());
  2464. parameterTypes = method.getParameterTypes();
  2465. showLoadingIndicator |= !TypeDataStore
  2466. .isNoLoadingIndicator(method);
  2467. } catch (NoDataException e) {
  2468. throw new RuntimeException("No type data for "
  2469. + invocation.toString(), e);
  2470. }
  2471. } else {
  2472. // Always show loading indicator for legacy requests
  2473. showLoadingIndicator = true;
  2474. }
  2475. for (int i = 0; i < invocation.getParameters().length; ++i) {
  2476. // TODO non-static encoder?
  2477. Type type = null;
  2478. if (parameterTypes != null) {
  2479. type = parameterTypes[i];
  2480. }
  2481. Object value = invocation.getParameters()[i];
  2482. JsonValue jsonValue = JsonEncoder.encode(value, type, this);
  2483. paramJson.set(i, jsonValue);
  2484. }
  2485. invocationJson.set(3, paramJson);
  2486. reqJson.set(reqJson.length(), invocationJson);
  2487. }
  2488. pendingInvocations.clear();
  2489. // Keep tag string short
  2490. lastInvocationTag = 0;
  2491. }
  2492. String extraParams = "";
  2493. if (!getConfiguration().isWidgetsetVersionSent()) {
  2494. if (!extraParams.isEmpty()) {
  2495. extraParams += "&";
  2496. }
  2497. String widgetsetVersion = Version.getFullVersion();
  2498. extraParams += "v-wsver=" + widgetsetVersion;
  2499. getConfiguration().setWidgetsetVersionSent();
  2500. }
  2501. if (showLoadingIndicator) {
  2502. getLoadingIndicator().trigger();
  2503. }
  2504. makeUidlRequest(reqJson, extraParams);
  2505. }
  2506. private boolean isJavascriptRpc(MethodInvocation invocation) {
  2507. return invocation instanceof JavaScriptMethodInvocation;
  2508. }
  2509. private boolean isLegacyVariableChange(MethodInvocation invocation) {
  2510. return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
  2511. .getInterfaceName())
  2512. && ApplicationConstants.UPDATE_VARIABLE_METHOD
  2513. .equals(invocation.getMethodName());
  2514. }
  2515. /**
  2516. * Sends a new value for the given paintables given variable to the server.
  2517. * <p>
  2518. * The update is actually queued to be sent at a suitable time. If immediate
  2519. * is true, the update is sent as soon as possible. If immediate is false,
  2520. * the update will be sent along with the next immediate update.
  2521. * </p>
  2522. *
  2523. * @param paintableId
  2524. * the id of the paintable that owns the variable
  2525. * @param variableName
  2526. * the name of the variable
  2527. * @param newValue
  2528. * the new value to be sent
  2529. * @param immediate
  2530. * true if the update is to be sent as soon as possible
  2531. */
  2532. public void updateVariable(String paintableId, String variableName,
  2533. ServerConnector newValue, boolean immediate) {
  2534. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2535. }
  2536. /**
  2537. * Sends a new value for the given paintables given variable to the server.
  2538. * <p>
  2539. * The update is actually queued to be sent at a suitable time. If immediate
  2540. * is true, the update is sent as soon as possible. If immediate is false,
  2541. * the update will be sent along with the next immediate update.
  2542. * </p>
  2543. *
  2544. * @param paintableId
  2545. * the id of the paintable that owns the variable
  2546. * @param variableName
  2547. * the name of the variable
  2548. * @param newValue
  2549. * the new value to be sent
  2550. * @param immediate
  2551. * true if the update is to be sent as soon as possible
  2552. */
  2553. public void updateVariable(String paintableId, String variableName,
  2554. String newValue, boolean immediate) {
  2555. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2556. }
  2557. /**
  2558. * Sends a new value for the given paintables given variable to the server.
  2559. * <p>
  2560. * The update is actually queued to be sent at a suitable time. If immediate
  2561. * is true, the update is sent as soon as possible. If immediate is false,
  2562. * the update will be sent along with the next immediate update.
  2563. * </p>
  2564. *
  2565. * @param paintableId
  2566. * the id of the paintable that owns the variable
  2567. * @param variableName
  2568. * the name of the variable
  2569. * @param newValue
  2570. * the new value to be sent
  2571. * @param immediate
  2572. * true if the update is to be sent as soon as possible
  2573. */
  2574. public void updateVariable(String paintableId, String variableName,
  2575. int newValue, boolean immediate) {
  2576. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2577. }
  2578. /**
  2579. * Sends a new value for the given paintables given variable to the server.
  2580. * <p>
  2581. * The update is actually queued to be sent at a suitable time. If immediate
  2582. * is true, the update is sent as soon as possible. If immediate is false,
  2583. * the update will be sent along with the next immediate update.
  2584. * </p>
  2585. *
  2586. * @param paintableId
  2587. * the id of the paintable that owns the variable
  2588. * @param variableName
  2589. * the name of the variable
  2590. * @param newValue
  2591. * the new value to be sent
  2592. * @param immediate
  2593. * true if the update is to be sent as soon as possible
  2594. */
  2595. public void updateVariable(String paintableId, String variableName,
  2596. long newValue, boolean immediate) {
  2597. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2598. }
  2599. /**
  2600. * Sends a new value for the given paintables given variable to the server.
  2601. * <p>
  2602. * The update is actually queued to be sent at a suitable time. If immediate
  2603. * is true, the update is sent as soon as possible. If immediate is false,
  2604. * the update will be sent along with the next immediate update.
  2605. * </p>
  2606. *
  2607. * @param paintableId
  2608. * the id of the paintable that owns the variable
  2609. * @param variableName
  2610. * the name of the variable
  2611. * @param newValue
  2612. * the new value to be sent
  2613. * @param immediate
  2614. * true if the update is to be sent as soon as possible
  2615. */
  2616. public void updateVariable(String paintableId, String variableName,
  2617. float newValue, boolean immediate) {
  2618. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2619. }
  2620. /**
  2621. * Sends a new value for the given paintables given variable to the server.
  2622. * <p>
  2623. * The update is actually queued to be sent at a suitable time. If immediate
  2624. * is true, the update is sent as soon as possible. If immediate is false,
  2625. * the update will be sent along with the next immediate update.
  2626. * </p>
  2627. *
  2628. * @param paintableId
  2629. * the id of the paintable that owns the variable
  2630. * @param variableName
  2631. * the name of the variable
  2632. * @param newValue
  2633. * the new value to be sent
  2634. * @param immediate
  2635. * true if the update is to be sent as soon as possible
  2636. */
  2637. public void updateVariable(String paintableId, String variableName,
  2638. double newValue, boolean immediate) {
  2639. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2640. }
  2641. /**
  2642. * Sends a new value for the given paintables given variable to the server.
  2643. * <p>
  2644. * The update is actually queued to be sent at a suitable time. If immediate
  2645. * is true, the update is sent as soon as possible. If immediate is false,
  2646. * the update will be sent along with the next immediate update.
  2647. * </p>
  2648. *
  2649. * @param paintableId
  2650. * the id of the paintable that owns the variable
  2651. * @param variableName
  2652. * the name of the variable
  2653. * @param newValue
  2654. * the new value to be sent
  2655. * @param immediate
  2656. * true if the update is to be sent as soon as possible
  2657. */
  2658. public void updateVariable(String paintableId, String variableName,
  2659. boolean newValue, boolean immediate) {
  2660. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2661. }
  2662. /**
  2663. * Sends a new value for the given paintables given variable to the server.
  2664. * <p>
  2665. * The update is actually queued to be sent at a suitable time. If immediate
  2666. * is true, the update is sent as soon as possible. If immediate is false,
  2667. * the update will be sent along with the next immediate update.
  2668. * </p>
  2669. *
  2670. * @param paintableId
  2671. * the id of the paintable that owns the variable
  2672. * @param variableName
  2673. * the name of the variable
  2674. * @param map
  2675. * the new values to be sent
  2676. * @param immediate
  2677. * true if the update is to be sent as soon as possible
  2678. */
  2679. public void updateVariable(String paintableId, String variableName,
  2680. Map<String, Object> map, boolean immediate) {
  2681. addVariableToQueue(paintableId, variableName, map, immediate);
  2682. }
  2683. /**
  2684. * Sends a new value for the given paintables given variable to the server.
  2685. *
  2686. * The update is actually queued to be sent at a suitable time. If immediate
  2687. * is true, the update is sent as soon as possible. If immediate is false,
  2688. * the update will be sent along with the next immediate update.
  2689. *
  2690. * A null array is sent as an empty array.
  2691. *
  2692. * @param paintableId
  2693. * the id of the paintable that owns the variable
  2694. * @param variableName
  2695. * the name of the variable
  2696. * @param values
  2697. * the new value to be sent
  2698. * @param immediate
  2699. * true if the update is to be sent as soon as possible
  2700. */
  2701. public void updateVariable(String paintableId, String variableName,
  2702. String[] values, boolean immediate) {
  2703. addVariableToQueue(paintableId, variableName, values, immediate);
  2704. }
  2705. /**
  2706. * Sends a new value for the given paintables given variable to the server.
  2707. *
  2708. * The update is actually queued to be sent at a suitable time. If immediate
  2709. * is true, the update is sent as soon as possible. If immediate is false,
  2710. * the update will be sent along with the next immediate update. </p>
  2711. *
  2712. * A null array is sent as an empty array.
  2713. *
  2714. *
  2715. * @param paintableId
  2716. * the id of the paintable that owns the variable
  2717. * @param variableName
  2718. * the name of the variable
  2719. * @param values
  2720. * the new value to be sent
  2721. * @param immediate
  2722. * true if the update is to be sent as soon as possible
  2723. */
  2724. public void updateVariable(String paintableId, String variableName,
  2725. Object[] values, boolean immediate) {
  2726. addVariableToQueue(paintableId, variableName, values, immediate);
  2727. }
  2728. /**
  2729. * Does absolutely nothing. Replaced by {@link LayoutManager}.
  2730. *
  2731. * @param container
  2732. * @deprecated As of 7.0, serves no purpose
  2733. */
  2734. @Deprecated
  2735. public void runDescendentsLayout(HasWidgets container) {
  2736. }
  2737. /**
  2738. * This will cause re-layouting of all components. Mainly used for
  2739. * development. Published to JavaScript.
  2740. */
  2741. public void forceLayout() {
  2742. Duration duration = new Duration();
  2743. layoutManager.forceLayout();
  2744. VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
  2745. }
  2746. /**
  2747. * Returns false
  2748. *
  2749. * @param paintable
  2750. * @return false, always
  2751. * @deprecated As of 7.0, serves no purpose
  2752. */
  2753. @Deprecated
  2754. private boolean handleComponentRelativeSize(ComponentConnector paintable) {
  2755. return false;
  2756. }
  2757. /**
  2758. * Returns false
  2759. *
  2760. * @param paintable
  2761. * @return false, always
  2762. * @deprecated As of 7.0, serves no purpose
  2763. */
  2764. @Deprecated
  2765. public boolean handleComponentRelativeSize(Widget widget) {
  2766. return handleComponentRelativeSize(connectorMap.getConnector(widget));
  2767. }
  2768. @Deprecated
  2769. public ComponentConnector getPaintable(UIDL uidl) {
  2770. // Non-component connectors shouldn't be painted from legacy connectors
  2771. return (ComponentConnector) getConnector(uidl.getId(),
  2772. Integer.parseInt(uidl.getTag()));
  2773. }
  2774. /**
  2775. * Get either an existing ComponentConnector or create a new
  2776. * ComponentConnector with the given type and id.
  2777. *
  2778. * If a ComponentConnector with the given id already exists, returns it.
  2779. * Otherwise creates and registers a new ComponentConnector of the given
  2780. * type.
  2781. *
  2782. * @param connectorId
  2783. * Id of the paintable
  2784. * @param connectorType
  2785. * Type of the connector, as passed from the server side
  2786. *
  2787. * @return Either an existing ComponentConnector or a new ComponentConnector
  2788. * of the given type
  2789. */
  2790. public ServerConnector getConnector(String connectorId, int connectorType) {
  2791. if (!connectorMap.hasConnector(connectorId)) {
  2792. return createAndRegisterConnector(connectorId, connectorType);
  2793. }
  2794. return connectorMap.getConnector(connectorId);
  2795. }
  2796. /**
  2797. * Creates a new ServerConnector with the given type and id.
  2798. *
  2799. * Creates and registers a new ServerConnector of the given type. Should
  2800. * never be called with the connector id of an existing connector.
  2801. *
  2802. * @param connectorId
  2803. * Id of the new connector
  2804. * @param connectorType
  2805. * Type of the connector, as passed from the server side
  2806. *
  2807. * @return A new ServerConnector of the given type
  2808. */
  2809. private ServerConnector createAndRegisterConnector(String connectorId,
  2810. int connectorType) {
  2811. Profiler.enter("ApplicationConnection.createAndRegisterConnector");
  2812. // Create and register a new connector with the given type
  2813. ServerConnector p = widgetSet.createConnector(connectorType,
  2814. configuration);
  2815. connectorMap.registerConnector(connectorId, p);
  2816. p.doInit(connectorId, this);
  2817. Profiler.leave("ApplicationConnection.createAndRegisterConnector");
  2818. return p;
  2819. }
  2820. /**
  2821. * Gets a recource that has been pre-loaded via UIDL, such as custom
  2822. * layouts.
  2823. *
  2824. * @param name
  2825. * identifier of the resource to get
  2826. * @return the resource
  2827. */
  2828. public String getResource(String name) {
  2829. return resourcesMap.get(name);
  2830. }
  2831. /**
  2832. * Singleton method to get instance of app's context menu.
  2833. *
  2834. * @return VContextMenu object
  2835. */
  2836. public VContextMenu getContextMenu() {
  2837. if (contextMenu == null) {
  2838. contextMenu = new VContextMenu();
  2839. contextMenu.setOwner(uIConnector.getWidget());
  2840. DOM.setElementProperty(contextMenu.getElement(), "id",
  2841. "PID_VAADIN_CM");
  2842. }
  2843. return contextMenu;
  2844. }
  2845. /**
  2846. * Gets an {@link Icon} instance corresponding to a URI.
  2847. *
  2848. * @since 7.2
  2849. * @param uri
  2850. * @return Icon object
  2851. */
  2852. public Icon getIcon(String uri) {
  2853. Icon icon;
  2854. if (uri == null) {
  2855. return null;
  2856. } else if (FontIcon.isFontIconUri(uri)) {
  2857. icon = GWT.create(FontIcon.class);
  2858. } else {
  2859. icon = GWT.create(ImageIcon.class);
  2860. }
  2861. icon.setUri(translateVaadinUri(uri));
  2862. return icon;
  2863. }
  2864. /**
  2865. * Translates custom protocols in UIDL URI's to be recognizable by browser.
  2866. * All uri's from UIDL should be routed via this method before giving them
  2867. * to browser due URI's in UIDL may contain custom protocols like theme://.
  2868. *
  2869. * @param uidlUri
  2870. * Vaadin URI from uidl
  2871. * @return translated URI ready for browser
  2872. */
  2873. public String translateVaadinUri(String uidlUri) {
  2874. return uriResolver.resolveVaadinUri(uidlUri);
  2875. }
  2876. /**
  2877. * Gets the URI for the current theme. Can be used to reference theme
  2878. * resources.
  2879. *
  2880. * @return URI to the current theme
  2881. */
  2882. public String getThemeUri() {
  2883. return configuration.getVaadinDirUrl() + "themes/"
  2884. + getUIConnector().getActiveTheme();
  2885. }
  2886. /**
  2887. * Listens for Notification hide event, and redirects. Used for system
  2888. * messages, such as session expired.
  2889. *
  2890. */
  2891. private class NotificationRedirect implements VNotification.EventListener {
  2892. String url;
  2893. NotificationRedirect(String url) {
  2894. this.url = url;
  2895. }
  2896. @Override
  2897. public void notificationHidden(HideEvent event) {
  2898. redirect(url);
  2899. }
  2900. }
  2901. /* Extended title handling */
  2902. private final VTooltip tooltip;
  2903. private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
  2904. protected String getUidlSecurityKey() {
  2905. return getCsrfToken();
  2906. }
  2907. /**
  2908. * Gets the token (aka double submit cookie) that the server uses to protect
  2909. * against Cross Site Request Forgery attacks.
  2910. *
  2911. * @return the CSRF token string
  2912. */
  2913. public String getCsrfToken() {
  2914. return csrfToken;
  2915. }
  2916. /**
  2917. * Use to notify that the given component's caption has changed; layouts may
  2918. * have to be recalculated.
  2919. *
  2920. * @param component
  2921. * the Paintable whose caption has changed
  2922. * @deprecated As of 7.0.2, has not had any effect for a long time
  2923. */
  2924. @Deprecated
  2925. public void captionSizeUpdated(Widget widget) {
  2926. // This doesn't do anything, it's just kept here for compatibility
  2927. }
  2928. /**
  2929. * Gets the main view
  2930. *
  2931. * @return the main view
  2932. */
  2933. public UIConnector getUIConnector() {
  2934. return uIConnector;
  2935. }
  2936. /**
  2937. * Gets the {@link ApplicationConfiguration} for the current application.
  2938. *
  2939. * @see ApplicationConfiguration
  2940. * @return the configuration for this application
  2941. */
  2942. public ApplicationConfiguration getConfiguration() {
  2943. return configuration;
  2944. }
  2945. /**
  2946. * Checks if there is a registered server side listener for the event. The
  2947. * list of events which has server side listeners is updated automatically
  2948. * before the component is updated so the value is correct if called from
  2949. * updatedFromUIDL.
  2950. *
  2951. * @param paintable
  2952. * The connector to register event listeners for
  2953. * @param eventIdentifier
  2954. * The identifier for the event
  2955. * @return true if at least one listener has been registered on server side
  2956. * for the event identified by eventIdentifier.
  2957. * @deprecated As of 7.0. Use
  2958. * {@link AbstractComponentState#hasEventListener(String)}
  2959. * instead
  2960. */
  2961. @Deprecated
  2962. public boolean hasEventListeners(ComponentConnector paintable,
  2963. String eventIdentifier) {
  2964. return paintable.hasEventListener(eventIdentifier);
  2965. }
  2966. /**
  2967. * Adds the get parameters to the uri and returns the new uri that contains
  2968. * the parameters.
  2969. *
  2970. * @param uri
  2971. * The uri to which the parameters should be added.
  2972. * @param extraParams
  2973. * One or more parameters in the format "a=b" or "c=d&e=f". An
  2974. * empty string is allowed but will not modify the url.
  2975. * @return The modified URI with the get parameters in extraParams added.
  2976. * @deprecated Use {@link SharedUtil#addGetParameters(String,String)}
  2977. * instead
  2978. */
  2979. @Deprecated
  2980. public static String addGetParameters(String uri, String extraParams) {
  2981. return SharedUtil.addGetParameters(uri, extraParams);
  2982. }
  2983. ConnectorMap getConnectorMap() {
  2984. return connectorMap;
  2985. }
  2986. /**
  2987. * @deprecated As of 7.0. No longer serves any purpose.
  2988. */
  2989. @Deprecated
  2990. public void unregisterPaintable(ServerConnector p) {
  2991. VConsole.log("unregisterPaintable (unnecessarily) called for "
  2992. + Util.getConnectorString(p));
  2993. }
  2994. /**
  2995. * Get VTooltip instance related to application connection
  2996. *
  2997. * @return VTooltip instance
  2998. */
  2999. public VTooltip getVTooltip() {
  3000. return tooltip;
  3001. }
  3002. /**
  3003. * Method provided for backwards compatibility. Duties previously done by
  3004. * this method is now handled by the state change event handler in
  3005. * AbstractComponentConnector. The only function this method has is to
  3006. * return true if the UIDL is a "cached" update.
  3007. *
  3008. * @param component
  3009. * @param uidl
  3010. * @param manageCaption
  3011. * @deprecated As of 7.0, no longer serves any purpose
  3012. * @return
  3013. */
  3014. @Deprecated
  3015. public boolean updateComponent(Widget component, UIDL uidl,
  3016. boolean manageCaption) {
  3017. ComponentConnector connector = getConnectorMap()
  3018. .getConnector(component);
  3019. if (!AbstractComponentConnector.isRealUpdate(uidl)) {
  3020. return true;
  3021. }
  3022. if (!manageCaption) {
  3023. VConsole.error(Util.getConnectorString(connector)
  3024. + " called updateComponent with manageCaption=false. The parameter was ignored - override delegateCaption() to return false instead. It is however not recommended to use caption this way at all.");
  3025. }
  3026. return false;
  3027. }
  3028. /**
  3029. * @deprecated As of 7.0. Use
  3030. * {@link AbstractComponentConnector#hasEventListener(String)}
  3031. * instead
  3032. */
  3033. @Deprecated
  3034. public boolean hasEventListeners(Widget widget, String eventIdentifier) {
  3035. ComponentConnector connector = getConnectorMap().getConnector(widget);
  3036. if (connector == null) {
  3037. /*
  3038. * No connector will exist in cases where Vaadin widgets have been
  3039. * re-used without implementing server<->client communication.
  3040. */
  3041. return false;
  3042. }
  3043. return hasEventListeners(getConnectorMap().getConnector(widget),
  3044. eventIdentifier);
  3045. }
  3046. LayoutManager getLayoutManager() {
  3047. return layoutManager;
  3048. }
  3049. /**
  3050. * Schedules a heartbeat request to occur after the configured heartbeat
  3051. * interval elapses if the interval is a positive number. Otherwise, does
  3052. * nothing.
  3053. *
  3054. * @deprecated as of 7.2, use {@link Heartbeat#schedule()} instead
  3055. */
  3056. @Deprecated
  3057. protected void scheduleHeartbeat() {
  3058. heartbeat.schedule();
  3059. }
  3060. /**
  3061. * Sends a heartbeat request to the server.
  3062. * <p>
  3063. * Heartbeat requests are used to inform the server that the client-side is
  3064. * still alive. If the client page is closed or the connection lost, the
  3065. * server will eventually close the inactive UI.
  3066. *
  3067. * @deprecated as of 7.2, use {@link Heartbeat#send()} instead
  3068. */
  3069. @Deprecated
  3070. protected void sendHeartbeat() {
  3071. heartbeat.send();
  3072. }
  3073. /**
  3074. * Timer used to make sure that no misbehaving components can delay response
  3075. * handling forever.
  3076. */
  3077. Timer forceHandleMessage = new Timer() {
  3078. @Override
  3079. public void run() {
  3080. VConsole.log("WARNING: reponse handling was never resumed, forcibly removing locks...");
  3081. responseHandlingLocks.clear();
  3082. handlePendingMessages();
  3083. }
  3084. };
  3085. /**
  3086. * This method can be used to postpone rendering of a response for a short
  3087. * period of time (e.g. to avoid the rendering process during animation).
  3088. *
  3089. * @param lock
  3090. */
  3091. public void suspendReponseHandling(Object lock) {
  3092. responseHandlingLocks.add(lock);
  3093. }
  3094. /**
  3095. * Resumes the rendering process once all locks have been removed.
  3096. *
  3097. * @param lock
  3098. */
  3099. public void resumeResponseHandling(Object lock) {
  3100. responseHandlingLocks.remove(lock);
  3101. if (responseHandlingLocks.isEmpty()) {
  3102. // Cancel timer that breaks the lock
  3103. forceHandleMessage.cancel();
  3104. if (!pendingUIDLMessages.isEmpty()) {
  3105. VConsole.log("No more response handling locks, handling pending requests.");
  3106. handlePendingMessages();
  3107. }
  3108. }
  3109. }
  3110. /**
  3111. * Handles all pending UIDL messages queued while response handling was
  3112. * suspended.
  3113. */
  3114. private void handlePendingMessages() {
  3115. if (!pendingUIDLMessages.isEmpty()) {
  3116. /*
  3117. * Clear the list before processing enqueued messages to support
  3118. * reentrancy
  3119. */
  3120. List<PendingUIDLMessage> pendingMessages = pendingUIDLMessages;
  3121. pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
  3122. for (PendingUIDLMessage pending : pendingMessages) {
  3123. handleReceivedJSONMessage(pending.getStart(),
  3124. pending.getJsonText(), pending.getJson());
  3125. }
  3126. }
  3127. }
  3128. private boolean handleErrorInDelegate(String details, int statusCode) {
  3129. if (communicationErrorDelegate == null) {
  3130. return false;
  3131. }
  3132. return communicationErrorDelegate.onError(details, statusCode);
  3133. }
  3134. /**
  3135. * Sets the delegate that is called whenever a communication error occurrs.
  3136. *
  3137. * @param delegate
  3138. * the delegate.
  3139. */
  3140. public void setCommunicationErrorDelegate(CommunicationErrorHandler delegate) {
  3141. communicationErrorDelegate = delegate;
  3142. }
  3143. public void setApplicationRunning(boolean running) {
  3144. if (applicationRunning && !running) {
  3145. eventBus.fireEvent(new ApplicationStoppedEvent());
  3146. }
  3147. applicationRunning = running;
  3148. }
  3149. public boolean isApplicationRunning() {
  3150. return applicationRunning;
  3151. }
  3152. public <H extends EventHandler> HandlerRegistration addHandler(
  3153. GwtEvent.Type<H> type, H handler) {
  3154. return eventBus.addHandler(type, handler);
  3155. }
  3156. @Override
  3157. public void fireEvent(GwtEvent<?> event) {
  3158. eventBus.fireEvent(event);
  3159. }
  3160. /**
  3161. * Calls {@link ComponentConnector#flush()} on the active connector. Does
  3162. * nothing if there is no active (focused) connector.
  3163. */
  3164. public void flushActiveConnector() {
  3165. ComponentConnector activeConnector = getActiveConnector();
  3166. if (activeConnector == null) {
  3167. return;
  3168. }
  3169. activeConnector.flush();
  3170. }
  3171. /**
  3172. * Gets the active connector for focused element in browser.
  3173. *
  3174. * @return Connector for focused element or null.
  3175. */
  3176. private ComponentConnector getActiveConnector() {
  3177. Element focusedElement = WidgetUtil.getFocusedElement();
  3178. if (focusedElement == null) {
  3179. return null;
  3180. }
  3181. return Util.getConnectorForElement(this, getUIConnector().getWidget(),
  3182. focusedElement);
  3183. }
  3184. /**
  3185. * Sets the status for the push connection.
  3186. *
  3187. * @param enabled
  3188. * <code>true</code> to enable the push connection;
  3189. * <code>false</code> to disable the push connection.
  3190. */
  3191. public void setPushEnabled(boolean enabled) {
  3192. final PushConfigurationState pushState = uIConnector.getState().pushConfiguration;
  3193. if (enabled && push == null) {
  3194. push = GWT.create(PushConnection.class);
  3195. push.init(this, pushState, new CommunicationErrorHandler() {
  3196. @Override
  3197. public boolean onError(String details, int statusCode) {
  3198. showCommunicationError(details, statusCode);
  3199. return true;
  3200. }
  3201. });
  3202. } else if (!enabled && push != null && push.isActive()) {
  3203. push.disconnect(new Command() {
  3204. @Override
  3205. public void execute() {
  3206. push = null;
  3207. /*
  3208. * If push has been enabled again while we were waiting for
  3209. * the old connection to disconnect, now is the right time
  3210. * to open a new connection
  3211. */
  3212. if (pushState.mode.isEnabled()) {
  3213. setPushEnabled(true);
  3214. }
  3215. /*
  3216. * Send anything that was enqueued while we waited for the
  3217. * connection to close
  3218. */
  3219. if (pendingInvocations.size() > 0) {
  3220. sendPendingVariableChanges();
  3221. }
  3222. }
  3223. });
  3224. }
  3225. }
  3226. public void handlePushMessage(String message) {
  3227. handleJSONText(message, 200);
  3228. }
  3229. /**
  3230. * Returns a human readable string representation of the method used to
  3231. * communicate with the server.
  3232. *
  3233. * @since 7.1
  3234. * @return A string representation of the current transport type
  3235. */
  3236. public String getCommunicationMethodName() {
  3237. if (push != null) {
  3238. return "Push (" + push.getTransportType() + ")";
  3239. } else {
  3240. return "XHR";
  3241. }
  3242. }
  3243. private static Logger getLogger() {
  3244. return Logger.getLogger(ApplicationConnection.class.getName());
  3245. }
  3246. /**
  3247. * Returns the hearbeat instance.
  3248. */
  3249. public Heartbeat getHeartbeat() {
  3250. return heartbeat;
  3251. }
  3252. /**
  3253. * Checks whether state changes are currently being processed. Certain
  3254. * operations are not allowed when the internal state of the application
  3255. * might be in an inconsistent state because some state changes have been
  3256. * applied but others not. This includes running layotus.
  3257. *
  3258. * @since 7.4
  3259. * @return <code>true</code> if the internal state might be inconsistent
  3260. * because changes are being processed; <code>false</code> if the
  3261. * state should be consistent
  3262. */
  3263. public boolean isUpdatingState() {
  3264. return updatingState;
  3265. }
  3266. }