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

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