Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ApplicationConnection.java 99KB

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