You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ApplicationConnection.java 97KB

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