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 140KB

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