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

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