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

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