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

ApplicationConnection.java 139KB

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