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

ApplicationConnection.java 92KB

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