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

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