Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

ApplicationConnection.java 138KB

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