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

ApplicationConnection.java 135KB

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