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

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