Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ApplicationConnection.java 140KB

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