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

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