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

ApplicationConnection.java 139KB

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