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

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