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

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