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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599
  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.terminal.gwt.client;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import com.google.gwt.core.client.Duration;
  28. import com.google.gwt.core.client.GWT;
  29. import com.google.gwt.core.client.JavaScriptObject;
  30. import com.google.gwt.core.client.JsArray;
  31. import com.google.gwt.core.client.JsArrayString;
  32. import com.google.gwt.core.client.Scheduler;
  33. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  34. import com.google.gwt.http.client.Request;
  35. import com.google.gwt.http.client.RequestBuilder;
  36. import com.google.gwt.http.client.RequestCallback;
  37. import com.google.gwt.http.client.RequestException;
  38. import com.google.gwt.http.client.Response;
  39. import com.google.gwt.http.client.URL;
  40. import com.google.gwt.json.client.JSONArray;
  41. import com.google.gwt.json.client.JSONObject;
  42. import com.google.gwt.json.client.JSONString;
  43. import com.google.gwt.regexp.shared.MatchResult;
  44. import com.google.gwt.regexp.shared.RegExp;
  45. import com.google.gwt.user.client.Command;
  46. import com.google.gwt.user.client.DOM;
  47. import com.google.gwt.user.client.Element;
  48. import com.google.gwt.user.client.Timer;
  49. import com.google.gwt.user.client.ui.HasWidgets;
  50. import com.google.gwt.user.client.ui.Widget;
  51. import com.vaadin.shared.ApplicationConstants;
  52. import com.vaadin.shared.ComponentState;
  53. import com.vaadin.shared.Version;
  54. import com.vaadin.shared.communication.MethodInvocation;
  55. import com.vaadin.shared.communication.SharedState;
  56. import com.vaadin.shared.communication.UidlValue;
  57. import com.vaadin.terminal.gwt.client.ApplicationConfiguration.ErrorMessage;
  58. import com.vaadin.terminal.gwt.client.ResourceLoader.ResourceLoadEvent;
  59. import com.vaadin.terminal.gwt.client.ResourceLoader.ResourceLoadListener;
  60. import com.vaadin.terminal.gwt.client.communication.HasJavaScriptConnectorHelper;
  61. import com.vaadin.terminal.gwt.client.communication.JsonDecoder;
  62. import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
  63. import com.vaadin.terminal.gwt.client.communication.RpcManager;
  64. import com.vaadin.terminal.gwt.client.communication.SerializerMap;
  65. import com.vaadin.terminal.gwt.client.communication.StateChangeEvent;
  66. import com.vaadin.terminal.gwt.client.communication.Type;
  67. import com.vaadin.terminal.gwt.client.extensions.AbstractExtensionConnector;
  68. import com.vaadin.terminal.gwt.client.ui.AbstractComponentConnector;
  69. import com.vaadin.terminal.gwt.client.ui.VContextMenu;
  70. import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
  71. import com.vaadin.terminal.gwt.client.ui.notification.VNotification;
  72. import com.vaadin.terminal.gwt.client.ui.notification.VNotification.HideEvent;
  73. import com.vaadin.terminal.gwt.client.ui.root.RootConnector;
  74. import com.vaadin.terminal.gwt.client.ui.window.WindowConnector;
  75. /**
  76. * This is the client side communication "engine", managing client-server
  77. * communication with its server side counterpart
  78. * com.vaadin.terminal.gwt.server.AbstractCommunicationManager.
  79. *
  80. * Client-side connectors receive updates from the corresponding server-side
  81. * connector (typically component) as state updates or RPC calls. The connector
  82. * has the possibility to communicate back with its server side counter part
  83. * through RPC calls.
  84. *
  85. * TODO document better
  86. *
  87. * Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
  88. */
  89. public class ApplicationConnection {
  90. public static final String MODIFIED_CLASSNAME = "v-modified";
  91. public static final String DISABLED_CLASSNAME = "v-disabled";
  92. public static final String REQUIRED_CLASSNAME_EXT = "-required";
  93. public static final String ERROR_CLASSNAME_EXT = "-error";
  94. public static final char VAR_BURST_SEPARATOR = '\u001d';
  95. public static final char VAR_ESCAPE_CHARACTER = '\u001b';
  96. private static SerializerMap serializerMap;
  97. /**
  98. * A string that, if found in a non-JSON response to a UIDL request, will
  99. * cause the browser to refresh the page. If followed by a colon, optional
  100. * whitespace, and a URI, causes the browser to synchronously load the URI.
  101. *
  102. * <p>
  103. * This allows, for instance, a servlet filter to redirect the application
  104. * to a custom login page when the session expires. For example:
  105. * </p>
  106. *
  107. * <pre>
  108. * if (sessionExpired) {
  109. * response.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
  110. * response.getWriter().write(
  111. * myLoginPageHtml + &quot;&lt;!-- Vaadin-Refresh: &quot;
  112. * + request.getContextPath() + &quot; --&gt;&quot;);
  113. * }
  114. * </pre>
  115. */
  116. public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
  117. // will hold the UIDL security key (for XSS protection) once received
  118. private String uidlSecurityKey = "init";
  119. private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
  120. private ArrayList<MethodInvocation> pendingInvocations = new ArrayList<MethodInvocation>();
  121. private WidgetSet widgetSet;
  122. private VContextMenu contextMenu = null;
  123. private Timer loadTimer;
  124. private Timer loadTimer2;
  125. private Timer loadTimer3;
  126. private Element loadElement;
  127. private final RootConnector rootConnector;
  128. protected boolean applicationRunning = false;
  129. private boolean hasActiveRequest = false;
  130. protected boolean cssLoaded = false;
  131. /** Parameters for this application connection loaded from the web-page */
  132. private ApplicationConfiguration configuration;
  133. /** List of pending variable change bursts that must be submitted in order */
  134. private final ArrayList<ArrayList<MethodInvocation>> pendingBursts = new ArrayList<ArrayList<MethodInvocation>>();
  135. /** Timer for automatic refirect to SessionExpiredURL */
  136. private Timer redirectTimer;
  137. /** redirectTimer scheduling interval in seconds */
  138. private int sessionExpirationInterval;
  139. private ArrayList<Widget> componentCaptionSizeChanges = new ArrayList<Widget>();
  140. private Date requestStartTime;
  141. private boolean validatingLayouts = false;
  142. private Set<ComponentConnector> zeroWidthComponents = null;
  143. private Set<ComponentConnector> zeroHeightComponents = null;
  144. private final LayoutManager layoutManager;
  145. private final RpcManager rpcManager;
  146. public static class MultiStepDuration extends Duration {
  147. private int previousStep = elapsedMillis();
  148. public void logDuration(String message) {
  149. logDuration(message, 0);
  150. }
  151. public void logDuration(String message, int minDuration) {
  152. int currentTime = elapsedMillis();
  153. int stepDuration = currentTime - previousStep;
  154. if (stepDuration >= minDuration) {
  155. VConsole.log(message + ": " + stepDuration + " ms");
  156. }
  157. previousStep = currentTime;
  158. }
  159. }
  160. public ApplicationConnection() {
  161. rootConnector = GWT.create(RootConnector.class);
  162. rpcManager = GWT.create(RpcManager.class);
  163. layoutManager = GWT.create(LayoutManager.class);
  164. layoutManager.setConnection(this);
  165. serializerMap = GWT.create(SerializerMap.class);
  166. }
  167. public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
  168. VConsole.log("Starting application " + cnf.getRootPanelId());
  169. VConsole.log("Vaadin application servlet version: "
  170. + cnf.getServletVersion());
  171. VConsole.log("Application version: " + cnf.getApplicationVersion());
  172. if (!cnf.getServletVersion().equals(Version.getFullVersion())) {
  173. VConsole.error("Warning: your widget set seems to be built with a different "
  174. + "version than the one used on server. Unexpected "
  175. + "behavior may occur.");
  176. }
  177. this.widgetSet = widgetSet;
  178. configuration = cnf;
  179. ComponentLocator componentLocator = new ComponentLocator(this);
  180. String appRootPanelName = cnf.getRootPanelId();
  181. // remove the end (window name) of autogenerated rootpanel id
  182. appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
  183. initializeTestbenchHooks(componentLocator, appRootPanelName);
  184. initializeClientHooks();
  185. rootConnector.init(cnf.getRootPanelId(), this);
  186. showLoadingIndicator();
  187. scheduleHeartbeat();
  188. }
  189. /**
  190. * Starts this application. Don't call this method directly - it's called by
  191. * {@link ApplicationConfiguration#startNextApplication()}, which should be
  192. * called once this application has started (first response received) or
  193. * failed to start. This ensures that the applications are started in order,
  194. * to avoid session-id problems.
  195. *
  196. */
  197. public void start() {
  198. String jsonText = configuration.getUIDL();
  199. if (jsonText == null) {
  200. // inital UIDL not in DOM, request later
  201. repaintAll();
  202. } else {
  203. // Update counter so TestBench knows something is still going on
  204. hasActiveRequest = true;
  205. // initial UIDL provided in DOM, continue as if returned by request
  206. handleJSONText(jsonText, -1);
  207. }
  208. }
  209. private native void initializeTestbenchHooks(
  210. ComponentLocator componentLocator, String TTAppId)
  211. /*-{
  212. var ap = this;
  213. var client = {};
  214. client.isActive = $entry(function() {
  215. return ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::hasActiveRequest()()
  216. || ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::isExecutingDeferredCommands()();
  217. });
  218. var vi = ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::getVersionInfo()();
  219. if (vi) {
  220. client.getVersionInfo = function() {
  221. return vi;
  222. }
  223. }
  224. client.getProfilingData = $entry(function() {
  225. var pd = [
  226. ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::lastProcessingTime,
  227. ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::totalProcessingTime
  228. ];
  229. pd = pd.concat(ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::serverTimingInfo);
  230. return pd;
  231. });
  232. client.getElementByPath = $entry(function(id) {
  233. return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
  234. });
  235. client.getPathForElement = $entry(function(element) {
  236. return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
  237. });
  238. $wnd.vaadin.clients[TTAppId] = client;
  239. }-*/;
  240. /**
  241. * Helper for tt initialization
  242. */
  243. private JavaScriptObject getVersionInfo() {
  244. return configuration.getVersionInfoJSObject();
  245. }
  246. /**
  247. * Publishes a JavaScript API for mash-up applications.
  248. * <ul>
  249. * <li><code>vaadin.forceSync()</code> sends pending variable changes, in
  250. * effect synchronizing the server and client state. This is done for all
  251. * applications on host page.</li>
  252. * <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
  253. * called after each XHR made by vaadin application. Note, that it is
  254. * attaching js functions responsibility to create the variable like this:
  255. *
  256. * <code><pre>
  257. * if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
  258. * postRequestHooks.myHook = function(appId) {
  259. * if(appId == "MyAppOfInterest") {
  260. * // do the staff you need on xhr activity
  261. * }
  262. * }
  263. * </pre></code> First parameter passed to these functions is the identifier
  264. * of Vaadin application that made the request.
  265. * </ul>
  266. *
  267. * TODO make this multi-app aware
  268. */
  269. private native void initializeClientHooks()
  270. /*-{
  271. var app = this;
  272. var oldSync;
  273. if ($wnd.vaadin.forceSync) {
  274. oldSync = $wnd.vaadin.forceSync;
  275. }
  276. $wnd.vaadin.forceSync = $entry(function() {
  277. if (oldSync) {
  278. oldSync();
  279. }
  280. app.@com.vaadin.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
  281. });
  282. var oldForceLayout;
  283. if ($wnd.vaadin.forceLayout) {
  284. oldForceLayout = $wnd.vaadin.forceLayout;
  285. }
  286. $wnd.vaadin.forceLayout = $entry(function() {
  287. if (oldForceLayout) {
  288. oldForceLayout();
  289. }
  290. app.@com.vaadin.terminal.gwt.client.ApplicationConnection::forceLayout()();
  291. });
  292. }-*/;
  293. /**
  294. * Runs possibly registered client side post request hooks. This is expected
  295. * to be run after each uidl request made by Vaadin application.
  296. *
  297. * @param appId
  298. */
  299. private static native void runPostRequestHooks(String appId)
  300. /*-{
  301. if ($wnd.vaadin.postRequestHooks) {
  302. for ( var hook in $wnd.vaadin.postRequestHooks) {
  303. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  304. try {
  305. $wnd.vaadin.postRequestHooks[hook](appId);
  306. } catch (e) {
  307. }
  308. }
  309. }
  310. }
  311. }-*/;
  312. /**
  313. * If on Liferay and logged in, ask the client side session management
  314. * JavaScript to extend the session duration.
  315. *
  316. * Otherwise, Liferay client side JavaScript will explicitly expire the
  317. * session even though the server side considers the session to be active.
  318. * See ticket #8305 for more information.
  319. */
  320. protected native void extendLiferaySession()
  321. /*-{
  322. if ($wnd.Liferay && $wnd.Liferay.Session) {
  323. $wnd.Liferay.Session.extend();
  324. // if the extend banner is visible, hide it
  325. if ($wnd.Liferay.Session.banner) {
  326. $wnd.Liferay.Session.banner.remove();
  327. }
  328. }
  329. }-*/;
  330. /**
  331. * Get the active Console for writing debug messages. May return an actual
  332. * logging console, or the NullConsole if debugging is not turned on.
  333. *
  334. * @deprecated Developers should use {@link VConsole} since 6.4.5
  335. *
  336. * @return the active Console
  337. */
  338. @Deprecated
  339. public static Console getConsole() {
  340. return VConsole.getImplementation();
  341. }
  342. /**
  343. * Checks if client side is in debug mode. Practically this is invoked by
  344. * adding ?debug parameter to URI.
  345. *
  346. * @deprecated use ApplicationConfiguration isDebugMode instead.
  347. *
  348. * @return true if client side is currently been debugged
  349. */
  350. @Deprecated
  351. public static boolean isDebugMode() {
  352. return ApplicationConfiguration.isDebugMode();
  353. }
  354. /**
  355. * Gets the application base URI. Using this other than as the download
  356. * action URI can cause problems in Portlet 2.0 deployments.
  357. *
  358. * @return application base URI
  359. */
  360. public String getAppUri() {
  361. return configuration.getApplicationUri();
  362. };
  363. /**
  364. * Indicates whether or not there are currently active UIDL requests. Used
  365. * internally to sequence requests properly, seldom needed in Widgets.
  366. *
  367. * @return true if there are active requests
  368. */
  369. public boolean hasActiveRequest() {
  370. return hasActiveRequest;
  371. }
  372. private String getRepaintAllParameters() {
  373. // collect some client side data that will be sent to server on
  374. // initial uidl request
  375. String nativeBootstrapParameters = getNativeBrowserDetailsParameters(getConfiguration()
  376. .getRootPanelId());
  377. // TODO figure out how client and view size could be used better on
  378. // server. screen size can be accessed via Browser object, but other
  379. // values currently only via transaction listener.
  380. String parameters = "repaintAll=1&" + nativeBootstrapParameters;
  381. return parameters;
  382. }
  383. /**
  384. * Gets the browser detail parameters that are sent by the bootstrap
  385. * javascript for two-request initialization.
  386. *
  387. * @param parentElementId
  388. * @return
  389. */
  390. private static native String getNativeBrowserDetailsParameters(
  391. String parentElementId)
  392. /*-{
  393. return $wnd.vaadin.getBrowserDetailsParameters(parentElementId);
  394. }-*/;
  395. protected void repaintAll() {
  396. String repainAllParameters = getRepaintAllParameters();
  397. makeUidlRequest("", repainAllParameters, false);
  398. }
  399. /**
  400. * Requests an analyze of layouts, to find inconsistencies. Exclusively used
  401. * for debugging during development.
  402. */
  403. public void analyzeLayouts() {
  404. String params = getRepaintAllParameters() + "&analyzeLayouts=1";
  405. makeUidlRequest("", params, false);
  406. }
  407. /**
  408. * Sends a request to the server to print details to console that will help
  409. * developer to locate component in the source code.
  410. *
  411. * @param componentConnector
  412. */
  413. void highlightComponent(ComponentConnector componentConnector) {
  414. String params = getRepaintAllParameters() + "&highlightComponent="
  415. + componentConnector.getConnectorId();
  416. makeUidlRequest("", params, false);
  417. }
  418. /**
  419. * Makes an UIDL request to the server.
  420. *
  421. * @param requestData
  422. * Data that is passed to the server.
  423. * @param extraParams
  424. * Parameters that are added as GET parameters to the url.
  425. * Contains key=value pairs joined by & characters or is empty if
  426. * no parameters should be added. Should not start with any
  427. * special character.
  428. * @param forceSync
  429. * true if the request should be synchronous, false otherwise
  430. */
  431. protected void makeUidlRequest(final String requestData,
  432. final String extraParams, final boolean forceSync) {
  433. startRequest();
  434. // Security: double cookie submission pattern
  435. final String payload = uidlSecurityKey + VAR_BURST_SEPARATOR
  436. + requestData;
  437. VConsole.log("Making UIDL Request with params: " + payload);
  438. String uri = translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  439. + ApplicationConstants.UIDL_REQUEST_PATH);
  440. if (extraParams != null && extraParams.length() > 0) {
  441. uri = addGetParameters(uri, extraParams);
  442. }
  443. uri = addGetParameters(uri, ApplicationConstants.ROOT_ID_PARAMETER
  444. + "=" + configuration.getRootId());
  445. doUidlRequest(uri, payload, forceSync);
  446. }
  447. /**
  448. * Sends an asynchronous or synchronous UIDL request to the server using the
  449. * given URI.
  450. *
  451. * @param uri
  452. * The URI to use for the request. May includes GET parameters
  453. * @param payload
  454. * The contents of the request to send
  455. * @param synchronous
  456. * true if the request should be synchronous, false otherwise
  457. */
  458. protected void doUidlRequest(final String uri, final String payload,
  459. final boolean synchronous) {
  460. if (!synchronous) {
  461. RequestCallback requestCallback = new RequestCallback() {
  462. @Override
  463. public void onError(Request request, Throwable exception) {
  464. showCommunicationError(exception.getMessage(), -1);
  465. endRequest();
  466. }
  467. @Override
  468. public void onResponseReceived(Request request,
  469. Response response) {
  470. VConsole.log("Server visit took "
  471. + String.valueOf((new Date()).getTime()
  472. - requestStartTime.getTime()) + "ms");
  473. int statusCode = response.getStatusCode();
  474. switch (statusCode) {
  475. case 0:
  476. showCommunicationError(
  477. "Invalid status code 0 (server down?)",
  478. statusCode);
  479. endRequest();
  480. return;
  481. case 401:
  482. /*
  483. * Authorization has failed. Could be that the session
  484. * has timed out and the container is redirecting to a
  485. * login page.
  486. */
  487. showAuthenticationError("");
  488. endRequest();
  489. return;
  490. case 503:
  491. /*
  492. * We'll assume msec instead of the usual seconds. If
  493. * there's no Retry-After header, handle the error like
  494. * a 500, as per RFC 2616 section 10.5.4.
  495. */
  496. String delay = response.getHeader("Retry-After");
  497. if (delay != null) {
  498. VConsole.log("503, retrying in " + delay + "msec");
  499. (new Timer() {
  500. @Override
  501. public void run() {
  502. doUidlRequest(uri, payload, synchronous);
  503. }
  504. }).schedule(Integer.parseInt(delay));
  505. return;
  506. }
  507. }
  508. if ((statusCode / 100) == 4) {
  509. // Handle all 4xx errors the same way as (they are
  510. // all permanent errors)
  511. showCommunicationError(
  512. "UIDL could not be read from server. Check servlets mappings. Error code: "
  513. + statusCode, statusCode);
  514. endRequest();
  515. return;
  516. } else if ((statusCode / 100) == 5) {
  517. // Something's wrong on the server, there's nothing the
  518. // client can do except maybe try again.
  519. showCommunicationError("Server error. Error code: "
  520. + statusCode, statusCode);
  521. endRequest();
  522. return;
  523. }
  524. String contentType = response.getHeader("Content-Type");
  525. if (contentType == null
  526. || !contentType.startsWith("application/json")) {
  527. /*
  528. * A servlet filter or equivalent may have intercepted
  529. * the request and served non-UIDL content (for
  530. * instance, a login page if the session has expired.)
  531. * If the response contains a magic substring, do a
  532. * synchronous refresh. See #8241.
  533. */
  534. MatchResult refreshToken = RegExp.compile(
  535. UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)")
  536. .exec(response.getText());
  537. if (refreshToken != null) {
  538. redirect(refreshToken.getGroup(2));
  539. return;
  540. }
  541. }
  542. // for(;;);[realjson]
  543. final String jsonText = response.getText().substring(9,
  544. response.getText().length() - 1);
  545. handleJSONText(jsonText, statusCode);
  546. }
  547. };
  548. try {
  549. doAsyncUIDLRequest(uri, payload, requestCallback);
  550. } catch (RequestException e) {
  551. VConsole.error(e);
  552. endRequest();
  553. }
  554. } else {
  555. // Synchronized call, discarded response (leaving the page)
  556. SynchronousXHR syncXHR = (SynchronousXHR) SynchronousXHR.create();
  557. syncXHR.synchronousPost(uri + "&"
  558. + ApplicationConstants.PARAM_UNLOADBURST + "=1", payload);
  559. /*
  560. * Although we are in theory leaving the page, the page may still
  561. * stay open. End request properly here too. See #3289
  562. */
  563. endRequest();
  564. }
  565. }
  566. /**
  567. * Handles received UIDL JSON text, parsing it, and passing it on to the
  568. * appropriate handlers, while logging timiing information.
  569. *
  570. * @param jsonText
  571. * @param statusCode
  572. */
  573. private void handleJSONText(String jsonText, int statusCode) {
  574. final Date start = new Date();
  575. final ValueMap json;
  576. try {
  577. json = parseJSONResponse(jsonText);
  578. } catch (final Exception e) {
  579. endRequest();
  580. showCommunicationError(e.getMessage() + " - Original JSON-text:"
  581. + jsonText, statusCode);
  582. return;
  583. }
  584. VConsole.log("JSON parsing took "
  585. + (new Date().getTime() - start.getTime()) + "ms");
  586. if (applicationRunning) {
  587. handleReceivedJSONMessage(start, jsonText, json);
  588. } else {
  589. applicationRunning = true;
  590. handleWhenCSSLoaded(jsonText, json);
  591. }
  592. }
  593. /**
  594. * Sends an asynchronous UIDL request to the server using the given URI.
  595. *
  596. * @param uri
  597. * The URI to use for the request. May includes GET parameters
  598. * @param payload
  599. * The contents of the request to send
  600. * @param requestCallback
  601. * The handler for the response
  602. * @throws RequestException
  603. * if the request could not be sent
  604. */
  605. protected void doAsyncUIDLRequest(String uri, String payload,
  606. RequestCallback requestCallback) throws RequestException {
  607. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  608. // TODO enable timeout
  609. // rb.setTimeoutMillis(timeoutMillis);
  610. rb.setHeader("Content-Type", "text/plain;charset=utf-8");
  611. rb.setRequestData(payload);
  612. rb.setCallback(requestCallback);
  613. rb.send();
  614. }
  615. int cssWaits = 0;
  616. /**
  617. * Holds the time spent rendering the last request
  618. */
  619. protected int lastProcessingTime;
  620. /**
  621. * Holds the total time spent rendering requests during the lifetime of the
  622. * session.
  623. */
  624. protected int totalProcessingTime;
  625. /**
  626. * Holds the timing information from the server-side. How much time was
  627. * spent servicing the last request and how much time has been spent
  628. * servicing the session so far. These values are always one request behind,
  629. * since they cannot be measured before the request is finished.
  630. */
  631. private ValueMap serverTimingInfo;
  632. static final int MAX_CSS_WAITS = 100;
  633. protected void handleWhenCSSLoaded(final String jsonText,
  634. final ValueMap json) {
  635. if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
  636. (new Timer() {
  637. @Override
  638. public void run() {
  639. handleWhenCSSLoaded(jsonText, json);
  640. }
  641. }).schedule(50);
  642. VConsole.log("Assuming CSS loading is not complete, "
  643. + "postponing render phase. "
  644. + "(.v-loading-indicator height == 0)");
  645. cssWaits++;
  646. } else {
  647. cssLoaded = true;
  648. handleReceivedJSONMessage(new Date(), jsonText, json);
  649. if (cssWaits >= MAX_CSS_WAITS) {
  650. VConsole.error("CSS files may have not loaded properly.");
  651. }
  652. }
  653. }
  654. /**
  655. * Checks whether or not the CSS is loaded. By default checks the size of
  656. * the loading indicator element.
  657. *
  658. * @return
  659. */
  660. protected boolean isCSSLoaded() {
  661. return cssLoaded
  662. || DOM.getElementPropertyInt(loadElement, "offsetHeight") != 0;
  663. }
  664. /**
  665. * Shows the communication error notification.
  666. *
  667. * @param details
  668. * Optional details for debugging.
  669. * @param statusCode
  670. * The status code returned for the request
  671. *
  672. */
  673. protected void showCommunicationError(String details, int statusCode) {
  674. VConsole.error("Communication error: " + details);
  675. ErrorMessage communicationError = configuration.getCommunicationError();
  676. showError(details, communicationError.getCaption(),
  677. communicationError.getMessage(), communicationError.getUrl());
  678. }
  679. /**
  680. * Shows the authentication error notification.
  681. *
  682. * @param details
  683. * Optional details for debugging.
  684. */
  685. protected void showAuthenticationError(String details) {
  686. VConsole.error("Authentication error: " + details);
  687. ErrorMessage authorizationError = configuration.getAuthorizationError();
  688. showError(details, authorizationError.getCaption(),
  689. authorizationError.getMessage(), authorizationError.getUrl());
  690. }
  691. /**
  692. * Shows the error notification.
  693. *
  694. * @param details
  695. * Optional details for debugging.
  696. */
  697. private void showError(String details, String caption, String message,
  698. String url) {
  699. StringBuilder html = new StringBuilder();
  700. if (caption != null) {
  701. html.append("<h1>");
  702. html.append(caption);
  703. html.append("</h1>");
  704. }
  705. if (message != null) {
  706. html.append("<p>");
  707. html.append(message);
  708. html.append("</p>");
  709. }
  710. if (html.length() > 0) {
  711. // Add error description
  712. html.append("<br/><p><I style=\"font-size:0.7em\">");
  713. html.append(details);
  714. html.append("</I></p>");
  715. VNotification n = VNotification.createNotification(1000 * 60 * 45);
  716. n.addEventListener(new NotificationRedirect(url));
  717. n.show(html.toString(), VNotification.CENTERED_TOP,
  718. VNotification.STYLE_SYSTEM);
  719. } else {
  720. redirect(url);
  721. }
  722. }
  723. protected void startRequest() {
  724. if (hasActiveRequest) {
  725. VConsole.error("Trying to start a new request while another is active");
  726. }
  727. hasActiveRequest = true;
  728. requestStartTime = new Date();
  729. // show initial throbber
  730. if (loadTimer == null) {
  731. loadTimer = new Timer() {
  732. @Override
  733. public void run() {
  734. /*
  735. * IE7 does not properly cancel the event with
  736. * loadTimer.cancel() so we have to check that we really
  737. * should make it visible
  738. */
  739. if (loadTimer != null) {
  740. showLoadingIndicator();
  741. }
  742. }
  743. };
  744. // First one kicks in at 300ms
  745. }
  746. loadTimer.schedule(300);
  747. }
  748. protected void endRequest() {
  749. if (!hasActiveRequest) {
  750. VConsole.error("No active request");
  751. }
  752. // After checkForPendingVariableBursts() there may be a new active
  753. // request, so we must set hasActiveRequest to false before, not after,
  754. // the call. Active requests used to be tracked with an integer counter,
  755. // so setting it after used to work but not with the #8505 changes.
  756. hasActiveRequest = false;
  757. if (applicationRunning) {
  758. checkForPendingVariableBursts();
  759. runPostRequestHooks(configuration.getRootPanelId());
  760. }
  761. // deferring to avoid flickering
  762. Scheduler.get().scheduleDeferred(new Command() {
  763. @Override
  764. public void execute() {
  765. if (!hasActiveRequest()) {
  766. hideLoadingIndicator();
  767. // If on Liferay and session expiration management is in
  768. // use, extend session duration on each request.
  769. // Doing it here rather than before the request to improve
  770. // responsiveness.
  771. // Postponed until the end of the next request if other
  772. // requests still pending.
  773. extendLiferaySession();
  774. }
  775. }
  776. });
  777. }
  778. /**
  779. * This method is called after applying uidl change set to application.
  780. *
  781. * It will clean current and queued variable change sets. And send next
  782. * change set if it exists.
  783. */
  784. private void checkForPendingVariableBursts() {
  785. cleanVariableBurst(pendingInvocations);
  786. if (pendingBursts.size() > 0) {
  787. for (Iterator<ArrayList<MethodInvocation>> iterator = pendingBursts
  788. .iterator(); iterator.hasNext();) {
  789. cleanVariableBurst(iterator.next());
  790. }
  791. ArrayList<MethodInvocation> nextBurst = pendingBursts.get(0);
  792. pendingBursts.remove(0);
  793. buildAndSendVariableBurst(nextBurst, false);
  794. }
  795. }
  796. /**
  797. * Cleans given queue of variable changes of such changes that came from
  798. * components that do not exist anymore.
  799. *
  800. * @param variableBurst
  801. */
  802. private void cleanVariableBurst(ArrayList<MethodInvocation> variableBurst) {
  803. for (int i = 1; i < variableBurst.size(); i++) {
  804. String id = variableBurst.get(i).getConnectorId();
  805. if (!getConnectorMap().hasConnector(id)
  806. && !getConnectorMap().isDragAndDropPaintable(id)) {
  807. // variable owner does not exist anymore
  808. variableBurst.remove(i);
  809. VConsole.log("Removed variable from removed component: " + id);
  810. }
  811. }
  812. }
  813. private void showLoadingIndicator() {
  814. // show initial throbber
  815. if (loadElement == null) {
  816. loadElement = DOM.createDiv();
  817. DOM.setStyleAttribute(loadElement, "position", "absolute");
  818. DOM.appendChild(rootConnector.getWidget().getElement(), loadElement);
  819. VConsole.log("inserting load indicator");
  820. }
  821. DOM.setElementProperty(loadElement, "className", "v-loading-indicator");
  822. DOM.setStyleAttribute(loadElement, "display", "block");
  823. // Initialize other timers
  824. loadTimer2 = new Timer() {
  825. @Override
  826. public void run() {
  827. DOM.setElementProperty(loadElement, "className",
  828. "v-loading-indicator-delay");
  829. }
  830. };
  831. // Second one kicks in at 1500ms from request start
  832. loadTimer2.schedule(1200);
  833. loadTimer3 = new Timer() {
  834. @Override
  835. public void run() {
  836. DOM.setElementProperty(loadElement, "className",
  837. "v-loading-indicator-wait");
  838. }
  839. };
  840. // Third one kicks in at 5000ms from request start
  841. loadTimer3.schedule(4700);
  842. }
  843. private void hideLoadingIndicator() {
  844. if (loadTimer != null) {
  845. loadTimer.cancel();
  846. loadTimer = null;
  847. }
  848. if (loadTimer2 != null) {
  849. loadTimer2.cancel();
  850. loadTimer3.cancel();
  851. loadTimer2 = null;
  852. loadTimer3 = null;
  853. }
  854. if (loadElement != null) {
  855. DOM.setStyleAttribute(loadElement, "display", "none");
  856. }
  857. }
  858. /**
  859. * Checks if deferred commands are (potentially) still being executed as a
  860. * result of an update from the server. Returns true if a deferred command
  861. * might still be executing, false otherwise. This will not work correctly
  862. * if a deferred command is added in another deferred command.
  863. * <p>
  864. * Used by the native "client.isActive" function.
  865. * </p>
  866. *
  867. * @return true if deferred commands are (potentially) being executed, false
  868. * otherwise
  869. */
  870. private boolean isExecutingDeferredCommands() {
  871. Scheduler s = Scheduler.get();
  872. if (s instanceof VSchedulerImpl) {
  873. return ((VSchedulerImpl) s).hasWorkQueued();
  874. } else {
  875. return false;
  876. }
  877. }
  878. /**
  879. * Determines whether or not the loading indicator is showing.
  880. *
  881. * @return true if the loading indicator is visible
  882. */
  883. public boolean isLoadingIndicatorVisible() {
  884. if (loadElement == null) {
  885. return false;
  886. }
  887. if (loadElement.getStyle().getProperty("display").equals("none")) {
  888. return false;
  889. }
  890. return true;
  891. }
  892. private static native ValueMap parseJSONResponse(String jsonText)
  893. /*-{
  894. try {
  895. return JSON.parse(jsonText);
  896. } catch (ignored) {
  897. return eval('(' + jsonText + ')');
  898. }
  899. }-*/;
  900. private void handleReceivedJSONMessage(Date start, String jsonText,
  901. ValueMap json) {
  902. handleUIDLMessage(start, jsonText, json);
  903. }
  904. protected void handleUIDLMessage(final Date start, final String jsonText,
  905. final ValueMap json) {
  906. VConsole.log("Handling message from server");
  907. // Handle redirect
  908. if (json.containsKey("redirect")) {
  909. String url = json.getValueMap("redirect").getString("url");
  910. VConsole.log("redirecting to " + url);
  911. redirect(url);
  912. return;
  913. }
  914. final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
  915. // Get security key
  916. if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
  917. uidlSecurityKey = json
  918. .getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
  919. }
  920. VConsole.log(" * Handling resources from server");
  921. if (json.containsKey("resources")) {
  922. ValueMap resources = json.getValueMap("resources");
  923. JsArrayString keyArray = resources.getKeyArray();
  924. int l = keyArray.length();
  925. for (int i = 0; i < l; i++) {
  926. String key = keyArray.get(i);
  927. resourcesMap.put(key, resources.getAsString(key));
  928. }
  929. }
  930. handleUIDLDuration.logDuration(
  931. " * Handling resources from server completed", 10);
  932. VConsole.log(" * Handling type inheritance map from server");
  933. if (json.containsKey("typeInheritanceMap")) {
  934. configuration.addComponentInheritanceInfo(json
  935. .getValueMap("typeInheritanceMap"));
  936. }
  937. handleUIDLDuration.logDuration(
  938. " * Handling type inheritance map from server completed", 10);
  939. VConsole.log("Handling type mappings from server");
  940. if (json.containsKey("typeMappings")) {
  941. configuration.addComponentMappings(
  942. json.getValueMap("typeMappings"), widgetSet);
  943. }
  944. VConsole.log("Handling resource dependencies");
  945. if (json.containsKey("scriptDependencies")) {
  946. loadScriptDependencies(json.getJSStringArray("scriptDependencies"));
  947. }
  948. if (json.containsKey("styleDependencies")) {
  949. loadStyleDependencies(json.getJSStringArray("styleDependencies"));
  950. }
  951. handleUIDLDuration.logDuration(
  952. " * Handling type mappings from server completed", 10);
  953. /*
  954. * Hook for e.g. TestBench to get details about server peformance
  955. */
  956. if (json.containsKey("timings")) {
  957. serverTimingInfo = json.getValueMap("timings");
  958. }
  959. Command c = new Command() {
  960. @Override
  961. public void execute() {
  962. handleUIDLDuration.logDuration(" * Loading widgets completed",
  963. 10);
  964. MultiStepDuration updateDuration = new MultiStepDuration();
  965. if (json.containsKey("locales")) {
  966. VConsole.log(" * Handling locales");
  967. // Store locale data
  968. JsArray<ValueMap> valueMapArray = json
  969. .getJSValueMapArray("locales");
  970. LocaleService.addLocales(valueMapArray);
  971. }
  972. updateDuration.logDuration(" * Handling locales completed", 10);
  973. boolean repaintAll = false;
  974. ValueMap meta = null;
  975. if (json.containsKey("meta")) {
  976. VConsole.log(" * Handling meta information");
  977. meta = json.getValueMap("meta");
  978. if (meta.containsKey("repaintAll")) {
  979. repaintAll = true;
  980. rootConnector.getWidget().clear();
  981. getConnectorMap().clear();
  982. if (meta.containsKey("invalidLayouts")) {
  983. validatingLayouts = true;
  984. zeroWidthComponents = new HashSet<ComponentConnector>();
  985. zeroHeightComponents = new HashSet<ComponentConnector>();
  986. }
  987. }
  988. if (meta.containsKey("timedRedirect")) {
  989. final ValueMap timedRedirect = meta
  990. .getValueMap("timedRedirect");
  991. redirectTimer = new Timer() {
  992. @Override
  993. public void run() {
  994. redirect(timedRedirect.getString("url"));
  995. }
  996. };
  997. sessionExpirationInterval = timedRedirect
  998. .getInt("interval");
  999. }
  1000. }
  1001. updateDuration.logDuration(
  1002. " * Handling meta information completed", 10);
  1003. if (redirectTimer != null) {
  1004. redirectTimer.schedule(1000 * sessionExpirationInterval);
  1005. }
  1006. componentCaptionSizeChanges.clear();
  1007. int startProcessing = updateDuration.elapsedMillis();
  1008. // Ensure that all connectors that we are about to update exist
  1009. createConnectorsIfNeeded(json);
  1010. updateDuration.logDuration(" * Creating connectors completed",
  1011. 10);
  1012. // Update states, do not fire events
  1013. Collection<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(json);
  1014. updateDuration.logDuration(
  1015. " * Update of connector states completed", 10);
  1016. // Update hierarchy, do not fire events
  1017. Collection<ConnectorHierarchyChangeEvent> pendingHierarchyChangeEvents = updateConnectorHierarchy(json);
  1018. updateDuration.logDuration(
  1019. " * Update of connector hierarchy completed", 10);
  1020. // Fire hierarchy change events
  1021. sendHierarchyChangeEvents(pendingHierarchyChangeEvents);
  1022. updateDuration.logDuration(
  1023. " * Hierarchy state change event processing completed",
  1024. 10);
  1025. // Fire state change events.
  1026. sendStateChangeEvents(pendingStateChangeEvents);
  1027. updateDuration.logDuration(
  1028. " * State change event processing completed", 10);
  1029. // Update of legacy (UIDL) style connectors
  1030. updateVaadin6StyleConnectors(json);
  1031. updateDuration
  1032. .logDuration(
  1033. " * Vaadin 6 style connector updates (updateFromUidl) completed",
  1034. 10);
  1035. // Handle any RPC invocations done on the server side
  1036. handleRpcInvocations(json);
  1037. updateDuration.logDuration(
  1038. " * Processing of RPC invocations completed", 10);
  1039. if (json.containsKey("dd")) {
  1040. // response contains data for drag and drop service
  1041. VDragAndDropManager.get().handleServerResponse(
  1042. json.getValueMap("dd"));
  1043. }
  1044. updateDuration
  1045. .logDuration(
  1046. " * Processing of drag and drop server response completed",
  1047. 10);
  1048. unregisterRemovedConnectors();
  1049. updateDuration.logDuration(
  1050. " * Unregistering of removed components completed", 10);
  1051. VConsole.log("handleUIDLMessage: "
  1052. + (updateDuration.elapsedMillis() - startProcessing)
  1053. + " ms");
  1054. LayoutManager layoutManager = getLayoutManager();
  1055. layoutManager.setEverythingNeedsMeasure();
  1056. layoutManager.layoutNow();
  1057. updateDuration
  1058. .logDuration(" * Layout processing completed", 10);
  1059. if (ApplicationConfiguration.isDebugMode()) {
  1060. VConsole.log(" * Dumping state changes to the console");
  1061. VConsole.dirUIDL(json, ApplicationConnection.this);
  1062. updateDuration
  1063. .logDuration(
  1064. " * Dumping state changes to the console completed",
  1065. 10);
  1066. }
  1067. if (meta != null) {
  1068. if (meta.containsKey("appError")) {
  1069. ValueMap error = meta.getValueMap("appError");
  1070. String html = "";
  1071. if (error.containsKey("caption")
  1072. && error.getString("caption") != null) {
  1073. html += "<h1>" + error.getAsString("caption")
  1074. + "</h1>";
  1075. }
  1076. if (error.containsKey("message")
  1077. && error.getString("message") != null) {
  1078. html += "<p>" + error.getAsString("message")
  1079. + "</p>";
  1080. }
  1081. String url = null;
  1082. if (error.containsKey("url")) {
  1083. url = error.getString("url");
  1084. }
  1085. if (html.length() != 0) {
  1086. /* 45 min */
  1087. VNotification n = VNotification
  1088. .createNotification(1000 * 60 * 45);
  1089. n.addEventListener(new NotificationRedirect(url));
  1090. n.show(html, VNotification.CENTERED_TOP,
  1091. VNotification.STYLE_SYSTEM);
  1092. } else {
  1093. redirect(url);
  1094. }
  1095. applicationRunning = false;
  1096. }
  1097. if (validatingLayouts) {
  1098. VConsole.printLayoutProblems(meta,
  1099. ApplicationConnection.this,
  1100. zeroHeightComponents, zeroWidthComponents);
  1101. zeroHeightComponents = null;
  1102. zeroWidthComponents = null;
  1103. validatingLayouts = false;
  1104. }
  1105. }
  1106. updateDuration.logDuration(" * Error handling completed", 10);
  1107. // TODO build profiling for widget impl loading time
  1108. lastProcessingTime = (int) ((new Date().getTime()) - start
  1109. .getTime());
  1110. totalProcessingTime += lastProcessingTime;
  1111. VConsole.log(" Processing time was "
  1112. + String.valueOf(lastProcessingTime) + "ms for "
  1113. + jsonText.length() + " characters of JSON");
  1114. VConsole.log("Referenced paintables: " + connectorMap.size());
  1115. endRequest();
  1116. }
  1117. /**
  1118. * Sends the state change events created while updating the state
  1119. * information.
  1120. *
  1121. * This must be called after hierarchy change listeners have been
  1122. * called. At least caption updates for the parent are strange if
  1123. * fired from state change listeners and thus calls the parent
  1124. * BEFORE the parent is aware of the child (through a
  1125. * ConnectorHierarchyChangedEvent)
  1126. *
  1127. * @param pendingStateChangeEvents
  1128. * The events to send
  1129. */
  1130. private void sendStateChangeEvents(
  1131. Collection<StateChangeEvent> pendingStateChangeEvents) {
  1132. VConsole.log(" * Sending state change events");
  1133. for (StateChangeEvent sce : pendingStateChangeEvents) {
  1134. try {
  1135. sce.getConnector().fireEvent(sce);
  1136. } catch (final Throwable e) {
  1137. VConsole.error(e);
  1138. }
  1139. }
  1140. }
  1141. private void unregisterRemovedConnectors() {
  1142. int unregistered = 0;
  1143. List<ServerConnector> currentConnectors = new ArrayList<ServerConnector>(
  1144. connectorMap.getConnectors());
  1145. for (ServerConnector c : currentConnectors) {
  1146. if (c.getParent() != null) {
  1147. if (!c.getParent().getChildren().contains(c)) {
  1148. VConsole.error("ERROR: Connector is connected to a parent but the parent does not contain the connector");
  1149. }
  1150. } else if ((c instanceof RootConnector && c == getRootConnector())) {
  1151. // RootConnector for this connection, leave as-is
  1152. } else if (c instanceof WindowConnector
  1153. && getRootConnector().hasSubWindow(
  1154. (WindowConnector) c)) {
  1155. // Sub window attached to this RootConnector, leave
  1156. // as-is
  1157. } else {
  1158. // The connector has been detached from the
  1159. // hierarchy, unregister it and any possible
  1160. // children. The RootConnector should never be
  1161. // unregistered even though it has no parent.
  1162. connectorMap.unregisterConnector(c);
  1163. unregistered++;
  1164. }
  1165. }
  1166. VConsole.log("* Unregistered " + unregistered + " connectors");
  1167. }
  1168. private void createConnectorsIfNeeded(ValueMap json) {
  1169. VConsole.log(" * Creating connectors (if needed)");
  1170. if (!json.containsKey("types")) {
  1171. return;
  1172. }
  1173. ValueMap types = json.getValueMap("types");
  1174. JsArrayString keyArray = types.getKeyArray();
  1175. for (int i = 0; i < keyArray.length(); i++) {
  1176. try {
  1177. String connectorId = keyArray.get(i);
  1178. int connectorType = Integer.parseInt(types
  1179. .getString((connectorId)));
  1180. ServerConnector connector = connectorMap
  1181. .getConnector(connectorId);
  1182. if (connector != null) {
  1183. continue;
  1184. }
  1185. Class<? extends ServerConnector> connectorClass = configuration
  1186. .getConnectorClassByEncodedTag(connectorType);
  1187. // Connector does not exist so we must create it
  1188. if (connectorClass != RootConnector.class) {
  1189. // create, initialize and register the paintable
  1190. getConnector(connectorId, connectorType);
  1191. } else {
  1192. // First RootConnector update. Before this the
  1193. // RootConnector has been created but not
  1194. // initialized as the connector id has not been
  1195. // known
  1196. connectorMap.registerConnector(connectorId,
  1197. rootConnector);
  1198. rootConnector.doInit(connectorId,
  1199. ApplicationConnection.this);
  1200. }
  1201. } catch (final Throwable e) {
  1202. VConsole.error(e);
  1203. }
  1204. }
  1205. }
  1206. private void updateVaadin6StyleConnectors(ValueMap json) {
  1207. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  1208. int length = changes.length();
  1209. VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
  1210. // update paintables
  1211. for (int i = 0; i < length; i++) {
  1212. try {
  1213. final UIDL change = changes.get(i).cast();
  1214. final UIDL uidl = change.getChildUIDL(0);
  1215. String connectorId = uidl.getId();
  1216. final ComponentConnector legacyConnector = (ComponentConnector) connectorMap
  1217. .getConnector(connectorId);
  1218. if (legacyConnector instanceof Paintable) {
  1219. ((Paintable) legacyConnector).updateFromUIDL(uidl,
  1220. ApplicationConnection.this);
  1221. } else if (legacyConnector == null) {
  1222. VConsole.error("Received update for "
  1223. + uidl.getTag()
  1224. + ", but there is no such paintable ("
  1225. + connectorId + ") rendered.");
  1226. } else {
  1227. VConsole.error("Server sent Vaadin 6 style updates for "
  1228. + Util.getConnectorString(legacyConnector)
  1229. + " but this is not a Vaadin 6 Paintable");
  1230. }
  1231. } catch (final Throwable e) {
  1232. VConsole.error(e);
  1233. }
  1234. }
  1235. }
  1236. private void sendHierarchyChangeEvents(
  1237. Collection<ConnectorHierarchyChangeEvent> pendingHierarchyChangeEvents) {
  1238. if (pendingHierarchyChangeEvents.isEmpty()) {
  1239. return;
  1240. }
  1241. VConsole.log(" * Sending hierarchy change events");
  1242. for (ConnectorHierarchyChangeEvent event : pendingHierarchyChangeEvents) {
  1243. try {
  1244. event.getConnector().fireEvent(event);
  1245. } catch (final Throwable e) {
  1246. VConsole.error(e);
  1247. }
  1248. }
  1249. }
  1250. private Collection<StateChangeEvent> updateConnectorState(
  1251. ValueMap json) {
  1252. ArrayList<StateChangeEvent> events = new ArrayList<StateChangeEvent>();
  1253. VConsole.log(" * Updating connector states");
  1254. if (!json.containsKey("state")) {
  1255. return events;
  1256. }
  1257. // set states for all paintables mentioned in "state"
  1258. ValueMap states = json.getValueMap("state");
  1259. JsArrayString keyArray = states.getKeyArray();
  1260. for (int i = 0; i < keyArray.length(); i++) {
  1261. try {
  1262. String connectorId = keyArray.get(i);
  1263. ServerConnector connector = connectorMap
  1264. .getConnector(connectorId);
  1265. if (null != connector) {
  1266. JSONObject stateJson = new JSONObject(
  1267. states.getJavaScriptObject(connectorId));
  1268. if (connector instanceof HasJavaScriptConnectorHelper) {
  1269. ((HasJavaScriptConnectorHelper) connector)
  1270. .getJavascriptConnectorHelper()
  1271. .setNativeState(
  1272. stateJson.getJavaScriptObject());
  1273. }
  1274. SharedState state = connector.getState();
  1275. JsonDecoder.decodeValue(new Type(state.getClass()
  1276. .getName(), null), stateJson, state,
  1277. ApplicationConnection.this);
  1278. StateChangeEvent event = GWT
  1279. .create(StateChangeEvent.class);
  1280. event.setConnector(connector);
  1281. events.add(event);
  1282. }
  1283. } catch (final Throwable e) {
  1284. VConsole.error(e);
  1285. }
  1286. }
  1287. return events;
  1288. }
  1289. /**
  1290. * Updates the connector hierarchy and returns a list of events that
  1291. * should be fired after update of the hierarchy and the state is
  1292. * done.
  1293. *
  1294. * @param json
  1295. * The JSON containing the hierarchy information
  1296. * @return A collection of events that should be fired when update
  1297. * of hierarchy and state is complete
  1298. */
  1299. private Collection<ConnectorHierarchyChangeEvent> updateConnectorHierarchy(
  1300. ValueMap json) {
  1301. List<ConnectorHierarchyChangeEvent> events = new LinkedList<ConnectorHierarchyChangeEvent>();
  1302. VConsole.log(" * Updating connector hierarchy");
  1303. if (!json.containsKey("hierarchy")) {
  1304. return events;
  1305. }
  1306. ValueMap hierarchies = json.getValueMap("hierarchy");
  1307. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  1308. for (int i = 0; i < hierarchyKeys.length(); i++) {
  1309. try {
  1310. String connectorId = hierarchyKeys.get(i);
  1311. ServerConnector parentConnector = connectorMap
  1312. .getConnector(connectorId);
  1313. JsArrayString childConnectorIds = hierarchies
  1314. .getJSStringArray(connectorId);
  1315. int childConnectorSize = childConnectorIds.length();
  1316. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  1317. List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
  1318. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  1319. String childConnectorId = childConnectorIds
  1320. .get(connectorIndex);
  1321. ServerConnector childConnector = connectorMap
  1322. .getConnector(childConnectorId);
  1323. if (childConnector == null) {
  1324. VConsole.error("Hierarchy claims that "
  1325. + childConnectorId + " is a child for "
  1326. + connectorId + " ("
  1327. + parentConnector.getClass().getName()
  1328. + ") but no connector with id "
  1329. + childConnectorId
  1330. + " has been registered");
  1331. continue;
  1332. }
  1333. newChildren.add(childConnector);
  1334. if (childConnector instanceof ComponentConnector) {
  1335. newComponents
  1336. .add((ComponentConnector) childConnector);
  1337. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  1338. throw new IllegalStateException(
  1339. Util.getConnectorString(childConnector)
  1340. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  1341. }
  1342. if (childConnector.getParent() != parentConnector) {
  1343. // Avoid extra calls to setParent
  1344. childConnector.setParent(parentConnector);
  1345. }
  1346. }
  1347. // TODO This check should be done on the server side in
  1348. // the future so the hierarchy update is only sent when
  1349. // something actually has changed
  1350. List<ServerConnector> oldChildren = parentConnector
  1351. .getChildren();
  1352. boolean actuallyChanged = !Util.collectionsEquals(
  1353. oldChildren, newChildren);
  1354. if (!actuallyChanged) {
  1355. continue;
  1356. }
  1357. if (parentConnector instanceof ComponentContainerConnector) {
  1358. ComponentContainerConnector ccc = (ComponentContainerConnector) parentConnector;
  1359. List<ComponentConnector> oldComponents = ccc
  1360. .getChildComponents();
  1361. if (!Util.collectionsEquals(oldComponents,
  1362. newComponents)) {
  1363. // Fire change event if the hierarchy has
  1364. // changed
  1365. ConnectorHierarchyChangeEvent event = GWT
  1366. .create(ConnectorHierarchyChangeEvent.class);
  1367. event.setOldChildren(oldComponents);
  1368. event.setConnector(parentConnector);
  1369. ccc.setChildComponents(newComponents);
  1370. events.add(event);
  1371. }
  1372. } else if (!newComponents.isEmpty()) {
  1373. VConsole.error("Hierachy claims "
  1374. + Util.getConnectorString(parentConnector)
  1375. + " has component children even though it isn't a ComponentContainerConnector");
  1376. }
  1377. parentConnector.setChildren(newChildren);
  1378. // Remove parent for children that are no longer
  1379. // attached to this (avoid updating children if they
  1380. // have already been assigned to a new parent)
  1381. for (ServerConnector oldChild : oldChildren) {
  1382. if (oldChild.getParent() != parentConnector) {
  1383. continue;
  1384. }
  1385. // TODO This could probably be optimized
  1386. if (!newChildren.contains(oldChild)) {
  1387. oldChild.setParent(null);
  1388. }
  1389. }
  1390. } catch (final Throwable e) {
  1391. VConsole.error(e);
  1392. }
  1393. }
  1394. return events;
  1395. }
  1396. private void handleRpcInvocations(ValueMap json) {
  1397. if (json.containsKey("rpc")) {
  1398. VConsole.log(" * Performing server to client RPC calls");
  1399. JSONArray rpcCalls = new JSONArray(
  1400. json.getJavaScriptObject("rpc"));
  1401. int rpcLength = rpcCalls.size();
  1402. for (int i = 0; i < rpcLength; i++) {
  1403. try {
  1404. JSONArray rpcCall = (JSONArray) rpcCalls.get(i);
  1405. rpcManager.parseAndApplyInvocation(rpcCall,
  1406. ApplicationConnection.this);
  1407. } catch (final Throwable e) {
  1408. VConsole.error(e);
  1409. }
  1410. }
  1411. }
  1412. }
  1413. };
  1414. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  1415. }
  1416. private void loadStyleDependencies(JsArrayString dependencies) {
  1417. // Assuming no reason to interpret in a defined order
  1418. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  1419. @Override
  1420. public void onLoad(ResourceLoadEvent event) {
  1421. ApplicationConfiguration.endDependencyLoading();
  1422. }
  1423. @Override
  1424. public void onError(ResourceLoadEvent event) {
  1425. VConsole.error(event.getResourceUrl()
  1426. + " could not be loaded, or the load detection failed because the stylesheet is empty.");
  1427. // The show must go on
  1428. onLoad(event);
  1429. }
  1430. };
  1431. ResourceLoader loader = ResourceLoader.get();
  1432. for (int i = 0; i < dependencies.length(); i++) {
  1433. String url = translateVaadinUri(dependencies.get(i));
  1434. ApplicationConfiguration.startDependencyLoading();
  1435. loader.loadStylesheet(url, resourceLoadListener);
  1436. }
  1437. }
  1438. private void loadScriptDependencies(final JsArrayString dependencies) {
  1439. if (dependencies.length() == 0) {
  1440. return;
  1441. }
  1442. // Listener that loads the next when one is completed
  1443. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  1444. @Override
  1445. public void onLoad(ResourceLoadEvent event) {
  1446. if (dependencies.length() != 0) {
  1447. String url = translateVaadinUri(dependencies.shift());
  1448. ApplicationConfiguration.startDependencyLoading();
  1449. // Load next in chain (hopefully already preloaded)
  1450. event.getResourceLoader().loadScript(url, this);
  1451. }
  1452. // Call start for next before calling end for current
  1453. ApplicationConfiguration.endDependencyLoading();
  1454. }
  1455. @Override
  1456. public void onError(ResourceLoadEvent event) {
  1457. VConsole.error(event.getResourceUrl() + " could not be loaded.");
  1458. // The show must go on
  1459. onLoad(event);
  1460. }
  1461. };
  1462. ResourceLoader loader = ResourceLoader.get();
  1463. // Start chain by loading first
  1464. String url = translateVaadinUri(dependencies.shift());
  1465. ApplicationConfiguration.startDependencyLoading();
  1466. loader.loadScript(url, resourceLoadListener);
  1467. // Preload all remaining
  1468. for (int i = 0; i < dependencies.length(); i++) {
  1469. String preloadUrl = translateVaadinUri(dependencies.get(i));
  1470. loader.preloadResource(preloadUrl, null);
  1471. }
  1472. }
  1473. // Redirect browser, null reloads current page
  1474. private static native void redirect(String url)
  1475. /*-{
  1476. if (url) {
  1477. $wnd.location = url;
  1478. } else {
  1479. $wnd.location.reload(false);
  1480. }
  1481. }-*/;
  1482. private void addVariableToQueue(String connectorId, String variableName,
  1483. Object value, boolean immediate) {
  1484. // note that type is now deduced from value
  1485. // TODO could eliminate invocations of same shared variable setter
  1486. addMethodInvocationToQueue(new MethodInvocation(connectorId,
  1487. ApplicationConstants.UPDATE_VARIABLE_INTERFACE,
  1488. ApplicationConstants.UPDATE_VARIABLE_METHOD, new Object[] {
  1489. variableName, new UidlValue(value) }), immediate);
  1490. }
  1491. /**
  1492. * Adds an explicit RPC method invocation to the send queue.
  1493. *
  1494. * @since 7.0
  1495. *
  1496. * @param invocation
  1497. * RPC method invocation
  1498. * @param immediate
  1499. * true to trigger sending within a short time window (possibly
  1500. * combining subsequent calls to a single request), false to let
  1501. * the framework delay sending of RPC calls and variable changes
  1502. * until the next immediate change
  1503. */
  1504. public void addMethodInvocationToQueue(MethodInvocation invocation,
  1505. boolean immediate) {
  1506. pendingInvocations.add(invocation);
  1507. if (immediate) {
  1508. sendPendingVariableChanges();
  1509. }
  1510. }
  1511. /**
  1512. * This method sends currently queued variable changes to server. It is
  1513. * called when immediate variable update must happen.
  1514. *
  1515. * To ensure correct order for variable changes (due servers multithreading
  1516. * or network), we always wait for active request to be handler before
  1517. * sending a new one. If there is an active request, we will put varible
  1518. * "burst" to queue that will be purged after current request is handled.
  1519. *
  1520. */
  1521. public void sendPendingVariableChanges() {
  1522. if (!deferedSendPending) {
  1523. deferedSendPending = true;
  1524. Scheduler.get().scheduleDeferred(sendPendingCommand);
  1525. }
  1526. }
  1527. private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
  1528. @Override
  1529. public void execute() {
  1530. deferedSendPending = false;
  1531. doSendPendingVariableChanges();
  1532. }
  1533. };
  1534. private boolean deferedSendPending = false;
  1535. @SuppressWarnings("unchecked")
  1536. private void doSendPendingVariableChanges() {
  1537. if (applicationRunning) {
  1538. if (hasActiveRequest()) {
  1539. // skip empty queues if there are pending bursts to be sent
  1540. if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
  1541. pendingBursts.add(pendingInvocations);
  1542. pendingInvocations = new ArrayList<MethodInvocation>();
  1543. }
  1544. } else {
  1545. buildAndSendVariableBurst(pendingInvocations, false);
  1546. }
  1547. }
  1548. }
  1549. /**
  1550. * Build the variable burst and send it to server.
  1551. *
  1552. * When sync is forced, we also force sending of all pending variable-bursts
  1553. * at the same time. This is ok as we can assume that DOM will never be
  1554. * updated after this.
  1555. *
  1556. * @param pendingInvocations
  1557. * List of RPC method invocations to send
  1558. * @param forceSync
  1559. * Should we use synchronous request?
  1560. */
  1561. private void buildAndSendVariableBurst(
  1562. ArrayList<MethodInvocation> pendingInvocations, boolean forceSync) {
  1563. final StringBuffer req = new StringBuffer();
  1564. while (!pendingInvocations.isEmpty()) {
  1565. if (ApplicationConfiguration.isDebugMode()) {
  1566. Util.logVariableBurst(this, pendingInvocations);
  1567. }
  1568. JSONArray reqJson = new JSONArray();
  1569. for (MethodInvocation invocation : pendingInvocations) {
  1570. JSONArray invocationJson = new JSONArray();
  1571. invocationJson.set(0,
  1572. new JSONString(invocation.getConnectorId()));
  1573. invocationJson.set(1,
  1574. new JSONString(invocation.getInterfaceName()));
  1575. invocationJson.set(2,
  1576. new JSONString(invocation.getMethodName()));
  1577. JSONArray paramJson = new JSONArray();
  1578. boolean restrictToInternalTypes = isLegacyVariableChange(invocation);
  1579. for (int i = 0; i < invocation.getParameters().length; ++i) {
  1580. // TODO non-static encoder? type registration?
  1581. paramJson.set(i, JsonEncoder.encode(
  1582. invocation.getParameters()[i],
  1583. restrictToInternalTypes, this));
  1584. }
  1585. invocationJson.set(3, paramJson);
  1586. reqJson.set(reqJson.size(), invocationJson);
  1587. }
  1588. // escape burst separators (if any)
  1589. req.append(escapeBurstContents(reqJson.toString()));
  1590. pendingInvocations.clear();
  1591. // Append all the bursts to this synchronous request
  1592. if (forceSync && !pendingBursts.isEmpty()) {
  1593. pendingInvocations = pendingBursts.get(0);
  1594. pendingBursts.remove(0);
  1595. req.append(VAR_BURST_SEPARATOR);
  1596. }
  1597. }
  1598. // Include the browser detail parameters if they aren't already sent
  1599. String extraParams;
  1600. if (!getConfiguration().isBrowserDetailsSent()) {
  1601. extraParams = getNativeBrowserDetailsParameters(getConfiguration()
  1602. .getRootPanelId());
  1603. getConfiguration().setBrowserDetailsSent();
  1604. } else {
  1605. extraParams = "";
  1606. }
  1607. if (!getConfiguration().isWidgetsetVersionSent()) {
  1608. if (!extraParams.isEmpty()) {
  1609. extraParams += "&";
  1610. }
  1611. String widgetsetVersion = Version.getFullVersion();
  1612. extraParams += "wsver=" + widgetsetVersion;
  1613. getConfiguration().setWidgetsetVersionSent();
  1614. }
  1615. makeUidlRequest(req.toString(), extraParams, forceSync);
  1616. }
  1617. private boolean isLegacyVariableChange(MethodInvocation invocation) {
  1618. return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
  1619. .getInterfaceName())
  1620. && ApplicationConstants.UPDATE_VARIABLE_METHOD
  1621. .equals(invocation.getMethodName());
  1622. }
  1623. /**
  1624. * Sends a new value for the given paintables given variable to the server.
  1625. * <p>
  1626. * The update is actually queued to be sent at a suitable time. If immediate
  1627. * is true, the update is sent as soon as possible. If immediate is false,
  1628. * the update will be sent along with the next immediate update.
  1629. * </p>
  1630. *
  1631. * @param paintableId
  1632. * the id of the paintable that owns the variable
  1633. * @param variableName
  1634. * the name of the variable
  1635. * @param newValue
  1636. * the new value to be sent
  1637. * @param immediate
  1638. * true if the update is to be sent as soon as possible
  1639. */
  1640. public void updateVariable(String paintableId, String variableName,
  1641. ServerConnector newValue, boolean immediate) {
  1642. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1643. }
  1644. /**
  1645. * Sends a new value for the given paintables given variable to the server.
  1646. * <p>
  1647. * The update is actually queued to be sent at a suitable time. If immediate
  1648. * is true, the update is sent as soon as possible. If immediate is false,
  1649. * the update will be sent along with the next immediate update.
  1650. * </p>
  1651. *
  1652. * @param paintableId
  1653. * the id of the paintable that owns the variable
  1654. * @param variableName
  1655. * the name of the variable
  1656. * @param newValue
  1657. * the new value to be sent
  1658. * @param immediate
  1659. * true if the update is to be sent as soon as possible
  1660. */
  1661. public void updateVariable(String paintableId, String variableName,
  1662. String newValue, boolean immediate) {
  1663. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1664. }
  1665. /**
  1666. * Sends a new value for the given paintables given variable to the server.
  1667. * <p>
  1668. * The update is actually queued to be sent at a suitable time. If immediate
  1669. * is true, the update is sent as soon as possible. If immediate is false,
  1670. * the update will be sent along with the next immediate update.
  1671. * </p>
  1672. *
  1673. * @param paintableId
  1674. * the id of the paintable that owns the variable
  1675. * @param variableName
  1676. * the name of the variable
  1677. * @param newValue
  1678. * the new value to be sent
  1679. * @param immediate
  1680. * true if the update is to be sent as soon as possible
  1681. */
  1682. public void updateVariable(String paintableId, String variableName,
  1683. int newValue, boolean immediate) {
  1684. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1685. }
  1686. /**
  1687. * Sends a new value for the given paintables given variable to the server.
  1688. * <p>
  1689. * The update is actually queued to be sent at a suitable time. If immediate
  1690. * is true, the update is sent as soon as possible. If immediate is false,
  1691. * the update will be sent along with the next immediate update.
  1692. * </p>
  1693. *
  1694. * @param paintableId
  1695. * the id of the paintable that owns the variable
  1696. * @param variableName
  1697. * the name of the variable
  1698. * @param newValue
  1699. * the new value to be sent
  1700. * @param immediate
  1701. * true if the update is to be sent as soon as possible
  1702. */
  1703. public void updateVariable(String paintableId, String variableName,
  1704. long newValue, boolean immediate) {
  1705. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1706. }
  1707. /**
  1708. * Sends a new value for the given paintables given variable to the server.
  1709. * <p>
  1710. * The update is actually queued to be sent at a suitable time. If immediate
  1711. * is true, the update is sent as soon as possible. If immediate is false,
  1712. * the update will be sent along with the next immediate update.
  1713. * </p>
  1714. *
  1715. * @param paintableId
  1716. * the id of the paintable that owns the variable
  1717. * @param variableName
  1718. * the name of the variable
  1719. * @param newValue
  1720. * the new value to be sent
  1721. * @param immediate
  1722. * true if the update is to be sent as soon as possible
  1723. */
  1724. public void updateVariable(String paintableId, String variableName,
  1725. float newValue, boolean immediate) {
  1726. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1727. }
  1728. /**
  1729. * Sends a new value for the given paintables given variable to the server.
  1730. * <p>
  1731. * The update is actually queued to be sent at a suitable time. If immediate
  1732. * is true, the update is sent as soon as possible. If immediate is false,
  1733. * the update will be sent along with the next immediate update.
  1734. * </p>
  1735. *
  1736. * @param paintableId
  1737. * the id of the paintable that owns the variable
  1738. * @param variableName
  1739. * the name of the variable
  1740. * @param newValue
  1741. * the new value to be sent
  1742. * @param immediate
  1743. * true if the update is to be sent as soon as possible
  1744. */
  1745. public void updateVariable(String paintableId, String variableName,
  1746. double newValue, boolean immediate) {
  1747. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1748. }
  1749. /**
  1750. * Sends a new value for the given paintables given variable to the server.
  1751. * <p>
  1752. * The update is actually queued to be sent at a suitable time. If immediate
  1753. * is true, the update is sent as soon as possible. If immediate is false,
  1754. * the update will be sent along with the next immediate update.
  1755. * </p>
  1756. *
  1757. * @param paintableId
  1758. * the id of the paintable that owns the variable
  1759. * @param variableName
  1760. * the name of the variable
  1761. * @param newValue
  1762. * the new value to be sent
  1763. * @param immediate
  1764. * true if the update is to be sent as soon as possible
  1765. */
  1766. public void updateVariable(String paintableId, String variableName,
  1767. boolean newValue, boolean immediate) {
  1768. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1769. }
  1770. /**
  1771. * Sends a new value for the given paintables given variable to the server.
  1772. * <p>
  1773. * The update is actually queued to be sent at a suitable time. If immediate
  1774. * is true, the update is sent as soon as possible. If immediate is false,
  1775. * the update will be sent along with the next immediate update.
  1776. * </p>
  1777. *
  1778. * @param paintableId
  1779. * the id of the paintable that owns the variable
  1780. * @param variableName
  1781. * the name of the variable
  1782. * @param map
  1783. * the new values to be sent
  1784. * @param immediate
  1785. * true if the update is to be sent as soon as possible
  1786. */
  1787. public void updateVariable(String paintableId, String variableName,
  1788. Map<String, Object> map, boolean immediate) {
  1789. addVariableToQueue(paintableId, variableName, map, immediate);
  1790. }
  1791. /**
  1792. * Sends a new value for the given paintables given variable to the server.
  1793. *
  1794. * The update is actually queued to be sent at a suitable time. If immediate
  1795. * is true, the update is sent as soon as possible. If immediate is false,
  1796. * the update will be sent along with the next immediate update.
  1797. *
  1798. * A null array is sent as an empty array.
  1799. *
  1800. * @param paintableId
  1801. * the id of the paintable that owns the variable
  1802. * @param variableName
  1803. * the name of the variable
  1804. * @param values
  1805. * the new value to be sent
  1806. * @param immediate
  1807. * true if the update is to be sent as soon as possible
  1808. */
  1809. public void updateVariable(String paintableId, String variableName,
  1810. String[] values, boolean immediate) {
  1811. addVariableToQueue(paintableId, variableName, values, immediate);
  1812. }
  1813. /**
  1814. * Sends a new value for the given paintables given variable to the server.
  1815. *
  1816. * The update is actually queued to be sent at a suitable time. If immediate
  1817. * is true, the update is sent as soon as possible. If immediate is false,
  1818. * the update will be sent along with the next immediate update. </p>
  1819. *
  1820. * A null array is sent as an empty array.
  1821. *
  1822. *
  1823. * @param paintableId
  1824. * the id of the paintable that owns the variable
  1825. * @param variableName
  1826. * the name of the variable
  1827. * @param values
  1828. * the new value to be sent
  1829. * @param immediate
  1830. * true if the update is to be sent as soon as possible
  1831. */
  1832. public void updateVariable(String paintableId, String variableName,
  1833. Object[] values, boolean immediate) {
  1834. addVariableToQueue(paintableId, variableName, values, immediate);
  1835. }
  1836. /**
  1837. * Encode burst separator characters in a String for transport over the
  1838. * network. This protects from separator injection attacks.
  1839. *
  1840. * @param value
  1841. * to encode
  1842. * @return encoded value
  1843. */
  1844. protected String escapeBurstContents(String value) {
  1845. final StringBuilder result = new StringBuilder();
  1846. for (int i = 0; i < value.length(); ++i) {
  1847. char character = value.charAt(i);
  1848. switch (character) {
  1849. case VAR_ESCAPE_CHARACTER:
  1850. // fall-through - escape character is duplicated
  1851. case VAR_BURST_SEPARATOR:
  1852. result.append(VAR_ESCAPE_CHARACTER);
  1853. // encode as letters for easier reading
  1854. result.append(((char) (character + 0x30)));
  1855. break;
  1856. default:
  1857. // the char is not a special one - add it to the result as is
  1858. result.append(character);
  1859. break;
  1860. }
  1861. }
  1862. return result.toString();
  1863. }
  1864. private boolean runningLayout = false;
  1865. /**
  1866. * Causes a re-calculation/re-layout of all paintables in a container.
  1867. *
  1868. * @param container
  1869. */
  1870. public void runDescendentsLayout(HasWidgets container) {
  1871. if (runningLayout) {
  1872. return;
  1873. }
  1874. runningLayout = true;
  1875. internalRunDescendentsLayout(container);
  1876. runningLayout = false;
  1877. }
  1878. /**
  1879. * This will cause re-layouting of all components. Mainly used for
  1880. * development. Published to JavaScript.
  1881. */
  1882. public void forceLayout() {
  1883. Duration duration = new Duration();
  1884. layoutManager.forceLayout();
  1885. VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
  1886. }
  1887. private void internalRunDescendentsLayout(HasWidgets container) {
  1888. // getConsole().log(
  1889. // "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
  1890. final Iterator<Widget> childWidgets = container.iterator();
  1891. while (childWidgets.hasNext()) {
  1892. final Widget child = childWidgets.next();
  1893. if (getConnectorMap().isConnector(child)) {
  1894. if (handleComponentRelativeSize(child)) {
  1895. /*
  1896. * Only need to propagate event if "child" has a relative
  1897. * size
  1898. */
  1899. if (child instanceof ContainerResizedListener) {
  1900. ((ContainerResizedListener) child).iLayout();
  1901. }
  1902. if (child instanceof HasWidgets) {
  1903. final HasWidgets childContainer = (HasWidgets) child;
  1904. internalRunDescendentsLayout(childContainer);
  1905. }
  1906. }
  1907. } else if (child instanceof HasWidgets) {
  1908. // propagate over non Paintable HasWidgets
  1909. internalRunDescendentsLayout((HasWidgets) child);
  1910. }
  1911. }
  1912. }
  1913. /**
  1914. * Converts relative sizes into pixel sizes.
  1915. *
  1916. * @param child
  1917. * @return true if the child has a relative size
  1918. */
  1919. private boolean handleComponentRelativeSize(ComponentConnector paintable) {
  1920. return false;
  1921. }
  1922. /**
  1923. * Converts relative sizes into pixel sizes.
  1924. *
  1925. * @param child
  1926. * @return true if the child has a relative size
  1927. */
  1928. public boolean handleComponentRelativeSize(Widget widget) {
  1929. return handleComponentRelativeSize(connectorMap.getConnector(widget));
  1930. }
  1931. @Deprecated
  1932. public ComponentConnector getPaintable(UIDL uidl) {
  1933. // Non-component connectors shouldn't be painted from legacy connectors
  1934. return (ComponentConnector) getConnector(uidl.getId(),
  1935. Integer.parseInt(uidl.getTag()));
  1936. }
  1937. /**
  1938. * Get either an existing ComponentConnector or create a new
  1939. * ComponentConnector with the given type and id.
  1940. *
  1941. * If a ComponentConnector with the given id already exists, returns it.
  1942. * Otherwise creates and registers a new ComponentConnector of the given
  1943. * type.
  1944. *
  1945. * @param connectorId
  1946. * Id of the paintable
  1947. * @param connectorType
  1948. * Type of the connector, as passed from the server side
  1949. *
  1950. * @return Either an existing ComponentConnector or a new ComponentConnector
  1951. * of the given type
  1952. */
  1953. public ServerConnector getConnector(String connectorId, int connectorType) {
  1954. if (!connectorMap.hasConnector(connectorId)) {
  1955. return createAndRegisterConnector(connectorId, connectorType);
  1956. }
  1957. return connectorMap.getConnector(connectorId);
  1958. }
  1959. /**
  1960. * Creates a new ServerConnector with the given type and id.
  1961. *
  1962. * Creates and registers a new ServerConnector of the given type. Should
  1963. * never be called with the connector id of an existing connector.
  1964. *
  1965. * @param connectorId
  1966. * Id of the new connector
  1967. * @param connectorType
  1968. * Type of the connector, as passed from the server side
  1969. *
  1970. * @return A new ServerConnector of the given type
  1971. */
  1972. private ServerConnector createAndRegisterConnector(String connectorId,
  1973. int connectorType) {
  1974. // Create and register a new connector with the given type
  1975. ServerConnector p = widgetSet.createConnector(connectorType,
  1976. configuration);
  1977. connectorMap.registerConnector(connectorId, p);
  1978. p.doInit(connectorId, this);
  1979. return p;
  1980. }
  1981. /**
  1982. * Gets a recource that has been pre-loaded via UIDL, such as custom
  1983. * layouts.
  1984. *
  1985. * @param name
  1986. * identifier of the resource to get
  1987. * @return the resource
  1988. */
  1989. public String getResource(String name) {
  1990. return resourcesMap.get(name);
  1991. }
  1992. /**
  1993. * Singleton method to get instance of app's context menu.
  1994. *
  1995. * @return VContextMenu object
  1996. */
  1997. public VContextMenu getContextMenu() {
  1998. if (contextMenu == null) {
  1999. contextMenu = new VContextMenu();
  2000. DOM.setElementProperty(contextMenu.getElement(), "id",
  2001. "PID_VAADIN_CM");
  2002. }
  2003. return contextMenu;
  2004. }
  2005. /**
  2006. * Translates custom protocols in UIDL URI's to be recognizable by browser.
  2007. * All uri's from UIDL should be routed via this method before giving them
  2008. * to browser due URI's in UIDL may contain custom protocols like theme://.
  2009. *
  2010. * @param uidlUri
  2011. * Vaadin URI from uidl
  2012. * @return translated URI ready for browser
  2013. */
  2014. public String translateVaadinUri(String uidlUri) {
  2015. if (uidlUri == null) {
  2016. return null;
  2017. }
  2018. if (uidlUri.startsWith("theme://")) {
  2019. final String themeUri = configuration.getThemeUri();
  2020. if (themeUri == null) {
  2021. VConsole.error("Theme not set: ThemeResource will not be found. ("
  2022. + uidlUri + ")");
  2023. }
  2024. uidlUri = themeUri + uidlUri.substring(7);
  2025. }
  2026. if (uidlUri.startsWith(ApplicationConstants.CONNECTOR_PROTOCOL_PREFIX)) {
  2027. // getAppUri *should* always end with /
  2028. // substring *should* always start with / (connector:///foo.bar
  2029. // without connector://)
  2030. uidlUri = ApplicationConstants.APP_PROTOCOL_PREFIX
  2031. + ApplicationConstants.CONNECTOR_RESOURCE_PREFIX
  2032. + uidlUri
  2033. .substring(ApplicationConstants.CONNECTOR_PROTOCOL_PREFIX
  2034. .length());
  2035. // Let translation of app:// urls take care of the rest
  2036. }
  2037. if (uidlUri.startsWith(ApplicationConstants.APP_PROTOCOL_PREFIX)) {
  2038. String relativeUrl = uidlUri
  2039. .substring(ApplicationConstants.APP_PROTOCOL_PREFIX
  2040. .length());
  2041. if (getConfiguration().usePortletURLs()) {
  2042. // Should put path in v-resourcePath parameter and append query
  2043. // params to base portlet url
  2044. String[] parts = relativeUrl.split("\\?", 2);
  2045. String path = parts[0];
  2046. String url = getConfiguration().getPortletResourceUrl();
  2047. // If there's a "?" followed by something, append it as a query
  2048. // string to the base URL
  2049. if (parts.length > 1) {
  2050. String appUrlParams = parts[1];
  2051. url = addGetParameters(url, appUrlParams);
  2052. }
  2053. if (!path.startsWith("/")) {
  2054. path = '/' + path;
  2055. }
  2056. String pathParam = ApplicationConstants.V_RESOURCE_PATH + "="
  2057. + URL.encodeQueryString(path);
  2058. url = addGetParameters(url, pathParam);
  2059. uidlUri = url;
  2060. } else {
  2061. uidlUri = getAppUri() + relativeUrl;
  2062. }
  2063. }
  2064. return uidlUri;
  2065. }
  2066. /**
  2067. * Gets the URI for the current theme. Can be used to reference theme
  2068. * resources.
  2069. *
  2070. * @return URI to the current theme
  2071. */
  2072. public String getThemeUri() {
  2073. return configuration.getThemeUri();
  2074. }
  2075. /**
  2076. * Listens for Notification hide event, and redirects. Used for system
  2077. * messages, such as session expired.
  2078. *
  2079. */
  2080. private class NotificationRedirect implements VNotification.EventListener {
  2081. String url;
  2082. NotificationRedirect(String url) {
  2083. this.url = url;
  2084. }
  2085. @Override
  2086. public void notificationHidden(HideEvent event) {
  2087. redirect(url);
  2088. }
  2089. }
  2090. /* Extended title handling */
  2091. private final VTooltip tooltip = new VTooltip(this);
  2092. private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
  2093. protected String getUidlSecurityKey() {
  2094. return uidlSecurityKey;
  2095. }
  2096. /**
  2097. * Use to notify that the given component's caption has changed; layouts may
  2098. * have to be recalculated.
  2099. *
  2100. * @param component
  2101. * the Paintable whose caption has changed
  2102. */
  2103. public void captionSizeUpdated(Widget widget) {
  2104. componentCaptionSizeChanges.add(widget);
  2105. }
  2106. /**
  2107. * Gets the main view
  2108. *
  2109. * @return the main view
  2110. */
  2111. public RootConnector getRootConnector() {
  2112. return rootConnector;
  2113. }
  2114. /**
  2115. * Gets the {@link ApplicationConfiguration} for the current application.
  2116. *
  2117. * @see ApplicationConfiguration
  2118. * @return the configuration for this application
  2119. */
  2120. public ApplicationConfiguration getConfiguration() {
  2121. return configuration;
  2122. }
  2123. /**
  2124. * Checks if there is a registered server side listener for the event. The
  2125. * list of events which has server side listeners is updated automatically
  2126. * before the component is updated so the value is correct if called from
  2127. * updatedFromUIDL.
  2128. *
  2129. * @param paintable
  2130. * The connector to register event listeners for
  2131. * @param eventIdentifier
  2132. * The identifier for the event
  2133. * @return true if at least one listener has been registered on server side
  2134. * for the event identified by eventIdentifier.
  2135. * @deprecated Use {@link ComponentState#hasEventListener(String)} instead
  2136. */
  2137. @Deprecated
  2138. public boolean hasEventListeners(ComponentConnector paintable,
  2139. String eventIdentifier) {
  2140. return paintable.hasEventListener(eventIdentifier);
  2141. }
  2142. /**
  2143. * Adds the get parameters to the uri and returns the new uri that contains
  2144. * the parameters.
  2145. *
  2146. * @param uri
  2147. * The uri to which the parameters should be added.
  2148. * @param extraParams
  2149. * One or more parameters in the format "a=b" or "c=d&e=f". An
  2150. * empty string is allowed but will not modify the url.
  2151. * @return The modified URI with the get parameters in extraParams added.
  2152. */
  2153. public static String addGetParameters(String uri, String extraParams) {
  2154. if (extraParams == null || extraParams.length() == 0) {
  2155. return uri;
  2156. }
  2157. // RFC 3986: The query component is indicated by the first question
  2158. // mark ("?") character and terminated by a number sign ("#") character
  2159. // or by the end of the URI.
  2160. String fragment = null;
  2161. int hashPosition = uri.indexOf('#');
  2162. if (hashPosition != -1) {
  2163. // Fragment including "#"
  2164. fragment = uri.substring(hashPosition);
  2165. // The full uri before the fragment
  2166. uri = uri.substring(0, hashPosition);
  2167. }
  2168. if (uri.contains("?")) {
  2169. uri += "&";
  2170. } else {
  2171. uri += "?";
  2172. }
  2173. uri += extraParams;
  2174. if (fragment != null) {
  2175. uri += fragment;
  2176. }
  2177. return uri;
  2178. }
  2179. ConnectorMap getConnectorMap() {
  2180. return connectorMap;
  2181. }
  2182. @Deprecated
  2183. public void unregisterPaintable(ServerConnector p) {
  2184. System.out.println("unregisterPaintable (unnecessarily) called for "
  2185. + Util.getConnectorString(p));
  2186. // connectorMap.unregisterConnector(p);
  2187. }
  2188. /**
  2189. * Get VTooltip instance related to application connection
  2190. *
  2191. * @return VTooltip instance
  2192. */
  2193. public VTooltip getVTooltip() {
  2194. return tooltip;
  2195. }
  2196. /**
  2197. * Method provided for backwards compatibility. Duties previously done by
  2198. * this method is now handled by the state change event handler in
  2199. * AbstractComponentConnector. The only function this method has is to
  2200. * return true if the UIDL is a "cached" update.
  2201. *
  2202. * @param component
  2203. * @param uidl
  2204. * @param manageCaption
  2205. * @return
  2206. */
  2207. @Deprecated
  2208. public boolean updateComponent(Widget component, UIDL uidl,
  2209. boolean manageCaption) {
  2210. ComponentConnector connector = getConnectorMap()
  2211. .getConnector(component);
  2212. if (!AbstractComponentConnector.isRealUpdate(uidl)) {
  2213. return true;
  2214. }
  2215. if (!manageCaption) {
  2216. VConsole.error(Util.getConnectorString(connector)
  2217. + " 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.");
  2218. }
  2219. return false;
  2220. }
  2221. @Deprecated
  2222. public boolean hasEventListeners(Widget widget, String eventIdentifier) {
  2223. return hasEventListeners(getConnectorMap().getConnector(widget),
  2224. eventIdentifier);
  2225. }
  2226. LayoutManager getLayoutManager() {
  2227. return layoutManager;
  2228. }
  2229. public SerializerMap getSerializerMap() {
  2230. return serializerMap;
  2231. }
  2232. /**
  2233. * Schedules a heartbeat request to occur after the configured heartbeat
  2234. * interval elapses if the interval is a positive number. Otherwise, does
  2235. * nothing.
  2236. *
  2237. * @see #sendHeartbeat()
  2238. * @see ApplicationConfiguration#getHeartbeatInterval()
  2239. */
  2240. protected void scheduleHeartbeat() {
  2241. final int interval = getConfiguration().getHeartbeatInterval();
  2242. if (interval > 0) {
  2243. VConsole.log("Scheduling heartbeat in " + interval + " seconds");
  2244. new Timer() {
  2245. @Override
  2246. public void run() {
  2247. sendHeartbeat();
  2248. }
  2249. }.schedule(interval * 1000);
  2250. }
  2251. }
  2252. /**
  2253. * Sends a heartbeat request to the server.
  2254. * <p>
  2255. * Heartbeat requests are used to inform the server that the client-side is
  2256. * still alive. If the client page is closed or the connection lost, the
  2257. * server will eventually close the inactive Root.
  2258. * <p>
  2259. * <b>TODO</b>: Improved error handling, like in doUidlRequest().
  2260. *
  2261. * @see #scheduleHeartbeat()
  2262. * @see com.vaadin.ui.Root#heartbeat()
  2263. */
  2264. protected void sendHeartbeat() {
  2265. final String uri = addGetParameters(
  2266. translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  2267. + ApplicationConstants.HEARTBEAT_REQUEST_PATH),
  2268. ApplicationConstants.ROOT_ID_PARAMETER + "="
  2269. + getConfiguration().getRootId());
  2270. final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  2271. final RequestCallback callback = new RequestCallback() {
  2272. @Override
  2273. public void onResponseReceived(Request request, Response response) {
  2274. int status = response.getStatusCode();
  2275. if (status == Response.SC_OK) {
  2276. // TODO Permit retry in some error situations
  2277. VConsole.log("Heartbeat response OK");
  2278. scheduleHeartbeat();
  2279. } else {
  2280. VConsole.error("Heartbeat request failed with status code "
  2281. + status);
  2282. }
  2283. }
  2284. @Override
  2285. public void onError(Request request, Throwable exception) {
  2286. VConsole.error("Heartbeat request resulted in exception");
  2287. VConsole.error(exception);
  2288. }
  2289. };
  2290. rb.setCallback(callback);
  2291. try {
  2292. VConsole.log("Sending heartbeat request...");
  2293. rb.send();
  2294. } catch (RequestException re) {
  2295. callback.onError(null, re);
  2296. }
  2297. }
  2298. }