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

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