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

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