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

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