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

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