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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695
  1. /*
  2. * Copyright 2000-2014 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.Collections;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.logging.Logger;
  28. import com.google.gwt.aria.client.LiveValue;
  29. import com.google.gwt.aria.client.RelevantValue;
  30. import com.google.gwt.aria.client.Roles;
  31. import com.google.gwt.core.client.Duration;
  32. import com.google.gwt.core.client.GWT;
  33. import com.google.gwt.core.client.JavaScriptObject;
  34. import com.google.gwt.core.client.JsArray;
  35. import com.google.gwt.core.client.JsArrayString;
  36. import com.google.gwt.core.client.Scheduler;
  37. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  38. import com.google.gwt.dom.client.Element;
  39. import com.google.gwt.event.shared.EventBus;
  40. import com.google.gwt.event.shared.EventHandler;
  41. import com.google.gwt.event.shared.GwtEvent;
  42. import com.google.gwt.event.shared.HandlerRegistration;
  43. import com.google.gwt.event.shared.HasHandlers;
  44. import com.google.gwt.event.shared.SimpleEventBus;
  45. import com.google.gwt.http.client.Request;
  46. import com.google.gwt.http.client.RequestBuilder;
  47. import com.google.gwt.http.client.RequestCallback;
  48. import com.google.gwt.http.client.RequestException;
  49. import com.google.gwt.http.client.Response;
  50. import com.google.gwt.http.client.URL;
  51. import com.google.gwt.json.client.JSONArray;
  52. import com.google.gwt.json.client.JSONNumber;
  53. import com.google.gwt.json.client.JSONObject;
  54. import com.google.gwt.json.client.JSONString;
  55. import com.google.gwt.regexp.shared.MatchResult;
  56. import com.google.gwt.regexp.shared.RegExp;
  57. import com.google.gwt.user.client.Command;
  58. import com.google.gwt.user.client.DOM;
  59. import com.google.gwt.user.client.Timer;
  60. import com.google.gwt.user.client.Window;
  61. import com.google.gwt.user.client.Window.ClosingEvent;
  62. import com.google.gwt.user.client.Window.ClosingHandler;
  63. import com.google.gwt.user.client.ui.HasWidgets;
  64. import com.google.gwt.user.client.ui.Widget;
  65. import com.vaadin.client.ApplicationConfiguration.ErrorMessage;
  66. import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
  67. import com.vaadin.client.ResourceLoader.ResourceLoadListener;
  68. import com.vaadin.client.communication.HasJavaScriptConnectorHelper;
  69. import com.vaadin.client.communication.Heartbeat;
  70. import com.vaadin.client.communication.JavaScriptMethodInvocation;
  71. import com.vaadin.client.communication.JsonDecoder;
  72. import com.vaadin.client.communication.JsonEncoder;
  73. import com.vaadin.client.communication.PushConnection;
  74. import com.vaadin.client.communication.RpcManager;
  75. import com.vaadin.client.communication.StateChangeEvent;
  76. import com.vaadin.client.componentlocator.ComponentLocator;
  77. import com.vaadin.client.extensions.AbstractExtensionConnector;
  78. import com.vaadin.client.metadata.ConnectorBundleLoader;
  79. import com.vaadin.client.metadata.Method;
  80. import com.vaadin.client.metadata.NoDataException;
  81. import com.vaadin.client.metadata.Property;
  82. import com.vaadin.client.metadata.Type;
  83. import com.vaadin.client.metadata.TypeData;
  84. import com.vaadin.client.ui.AbstractComponentConnector;
  85. import com.vaadin.client.ui.AbstractConnector;
  86. import com.vaadin.client.ui.FontIcon;
  87. import com.vaadin.client.ui.Icon;
  88. import com.vaadin.client.ui.ImageIcon;
  89. import com.vaadin.client.ui.VContextMenu;
  90. import com.vaadin.client.ui.VNotification;
  91. import com.vaadin.client.ui.VNotification.HideEvent;
  92. import com.vaadin.client.ui.VOverlay;
  93. import com.vaadin.client.ui.dd.VDragAndDropManager;
  94. import com.vaadin.client.ui.ui.UIConnector;
  95. import com.vaadin.client.ui.window.WindowConnector;
  96. import com.vaadin.shared.AbstractComponentState;
  97. import com.vaadin.shared.ApplicationConstants;
  98. import com.vaadin.shared.JsonConstants;
  99. import com.vaadin.shared.Version;
  100. import com.vaadin.shared.communication.LegacyChangeVariablesInvocation;
  101. import com.vaadin.shared.communication.MethodInvocation;
  102. import com.vaadin.shared.communication.SharedState;
  103. import com.vaadin.shared.ui.ui.UIConstants;
  104. import com.vaadin.shared.ui.ui.UIState.PushConfigurationState;
  105. /**
  106. * This is the client side communication "engine", managing client-server
  107. * communication with its server side counterpart
  108. * com.vaadin.server.VaadinService.
  109. *
  110. * Client-side connectors receive updates from the corresponding server-side
  111. * connector (typically component) as state updates or RPC calls. The connector
  112. * has the possibility to communicate back with its server side counter part
  113. * through RPC calls.
  114. *
  115. * TODO document better
  116. *
  117. * Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
  118. */
  119. public class ApplicationConnection implements HasHandlers {
  120. /**
  121. * Helper used to return two values when updating the connector hierarchy.
  122. */
  123. private static class ConnectorHierarchyUpdateResult {
  124. /**
  125. * Needed at a later point when the created events are fired
  126. */
  127. private JsArrayObject<ConnectorHierarchyChangeEvent> events = JavaScriptObject
  128. .createArray().cast();
  129. /**
  130. * Needed to know where captions might need to get updated
  131. */
  132. private FastStringSet parentChangedIds = FastStringSet.create();
  133. /**
  134. * Connectors for which the parent has been set to null
  135. */
  136. private FastStringSet detachedConnectorIds = FastStringSet.create();
  137. }
  138. public static final String MODIFIED_CLASSNAME = "v-modified";
  139. public static final String DISABLED_CLASSNAME = "v-disabled";
  140. public static final String REQUIRED_CLASSNAME = "v-required";
  141. public static final String REQUIRED_CLASSNAME_EXT = "-required";
  142. public static final String ERROR_CLASSNAME_EXT = "-error";
  143. /**
  144. * A string that, if found in a non-JSON response to a UIDL request, will
  145. * cause the browser to refresh the page. If followed by a colon, optional
  146. * whitespace, and a URI, causes the browser to synchronously load the URI.
  147. *
  148. * <p>
  149. * This allows, for instance, a servlet filter to redirect the application
  150. * to a custom login page when the session expires. For example:
  151. * </p>
  152. *
  153. * <pre>
  154. * if (sessionExpired) {
  155. * response.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
  156. * response.getWriter().write(
  157. * myLoginPageHtml + &quot;&lt;!-- Vaadin-Refresh: &quot;
  158. * + request.getContextPath() + &quot; --&gt;&quot;);
  159. * }
  160. * </pre>
  161. */
  162. public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
  163. // will hold the CSRF token once received
  164. private String csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE;
  165. private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
  166. /**
  167. * The pending method invocations that will be send to the server by
  168. * {@link #sendPendingCommand}. The key is defined differently based on
  169. * whether the method invocation is enqueued with lastonly. With lastonly
  170. * enabled, the method signature ( {@link MethodInvocation#getLastOnlyTag()}
  171. * ) is used as the key to make enable removing a previously enqueued
  172. * invocation. Without lastonly, an incremental id based on
  173. * {@link #lastInvocationTag} is used to get unique values.
  174. */
  175. private LinkedHashMap<String, MethodInvocation> pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
  176. private int lastInvocationTag = 0;
  177. private WidgetSet widgetSet;
  178. private VContextMenu contextMenu = null;
  179. private final UIConnector uIConnector;
  180. protected boolean applicationRunning = false;
  181. private boolean hasActiveRequest = false;
  182. /**
  183. * Webkit will ignore outgoing requests while waiting for a response to a
  184. * navigation event (indicated by a beforeunload event). When this happens,
  185. * we should keep trying to send the request every now and then until there
  186. * is a response or until it throws an exception saying that it is already
  187. * being sent.
  188. */
  189. private boolean webkitMaybeIgnoringRequests = false;
  190. protected boolean cssLoaded = false;
  191. /** Parameters for this application connection loaded from the web-page */
  192. private ApplicationConfiguration configuration;
  193. /** List of pending variable change bursts that must be submitted in order */
  194. private final ArrayList<LinkedHashMap<String, MethodInvocation>> pendingBursts = new ArrayList<LinkedHashMap<String, MethodInvocation>>();
  195. /** Timer for automatic refirect to SessionExpiredURL */
  196. private Timer redirectTimer;
  197. /** redirectTimer scheduling interval in seconds */
  198. private int sessionExpirationInterval;
  199. private Date requestStartTime;
  200. private final LayoutManager layoutManager;
  201. private final RpcManager rpcManager;
  202. private PushConnection push;
  203. /**
  204. * If responseHandlingLocks contains any objects, response handling is
  205. * suspended until the collection is empty or a timeout has occurred.
  206. */
  207. private Set<Object> responseHandlingLocks = new HashSet<Object>();
  208. /**
  209. * Data structure holding information about pending UIDL messages.
  210. */
  211. private class PendingUIDLMessage {
  212. private Date start;
  213. private String jsonText;
  214. private ValueMap json;
  215. public PendingUIDLMessage(Date start, String jsonText, ValueMap json) {
  216. this.start = start;
  217. this.jsonText = jsonText;
  218. this.json = json;
  219. }
  220. public Date getStart() {
  221. return start;
  222. }
  223. public String getJsonText() {
  224. return jsonText;
  225. }
  226. public ValueMap getJson() {
  227. return json;
  228. }
  229. }
  230. /** Contains all UIDL messages received while response handling is suspended */
  231. private List<PendingUIDLMessage> pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
  232. /** The max timeout that response handling may be suspended */
  233. private static final int MAX_SUSPENDED_TIMEOUT = 5000;
  234. /** Event bus for communication events */
  235. private EventBus eventBus = GWT.create(SimpleEventBus.class);
  236. /**
  237. * The communication handler methods are called at certain points during
  238. * communication with the server. This allows for making add-ons that keep
  239. * track of different aspects of the communication.
  240. */
  241. public interface CommunicationHandler extends EventHandler {
  242. void onRequestStarting(RequestStartingEvent e);
  243. void onResponseHandlingStarted(ResponseHandlingStartedEvent e);
  244. void onResponseHandlingEnded(ResponseHandlingEndedEvent e);
  245. }
  246. public static class RequestStartingEvent extends ApplicationConnectionEvent {
  247. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  248. public RequestStartingEvent(ApplicationConnection connection) {
  249. super(connection);
  250. }
  251. @Override
  252. public Type<CommunicationHandler> getAssociatedType() {
  253. return TYPE;
  254. }
  255. @Override
  256. protected void dispatch(CommunicationHandler handler) {
  257. handler.onRequestStarting(this);
  258. }
  259. }
  260. public static class ResponseHandlingEndedEvent extends
  261. ApplicationConnectionEvent {
  262. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  263. public ResponseHandlingEndedEvent(ApplicationConnection connection) {
  264. super(connection);
  265. }
  266. @Override
  267. public Type<CommunicationHandler> getAssociatedType() {
  268. return TYPE;
  269. }
  270. @Override
  271. protected void dispatch(CommunicationHandler handler) {
  272. handler.onResponseHandlingEnded(this);
  273. }
  274. }
  275. public static abstract class ApplicationConnectionEvent extends
  276. GwtEvent<CommunicationHandler> {
  277. private ApplicationConnection connection;
  278. protected ApplicationConnectionEvent(ApplicationConnection connection) {
  279. this.connection = connection;
  280. }
  281. public ApplicationConnection getConnection() {
  282. return connection;
  283. }
  284. }
  285. /**
  286. * Event triggered when a XHR request has finished with the status code of
  287. * the response.
  288. *
  289. * Useful for handlers observing network failures like online/off-line
  290. * monitors.
  291. */
  292. public static class ConnectionStatusEvent extends
  293. GwtEvent<ConnectionStatusEvent.ConnectionStatusHandler> {
  294. private int status;
  295. public static interface ConnectionStatusHandler extends EventHandler {
  296. public void onConnectionStatusChange(ConnectionStatusEvent event);
  297. }
  298. public ConnectionStatusEvent(int status) {
  299. this.status = status;
  300. }
  301. public int getStatus() {
  302. return status;
  303. }
  304. public final static Type<ConnectionStatusHandler> TYPE = new Type<ConnectionStatusHandler>();
  305. @Override
  306. public Type<ConnectionStatusHandler> getAssociatedType() {
  307. return TYPE;
  308. }
  309. @Override
  310. protected void dispatch(ConnectionStatusHandler handler) {
  311. handler.onConnectionStatusChange(this);
  312. }
  313. }
  314. public static class ResponseHandlingStartedEvent extends
  315. ApplicationConnectionEvent {
  316. public ResponseHandlingStartedEvent(ApplicationConnection connection) {
  317. super(connection);
  318. }
  319. public static Type<CommunicationHandler> TYPE = new Type<CommunicationHandler>();
  320. @Override
  321. public Type<CommunicationHandler> getAssociatedType() {
  322. return TYPE;
  323. }
  324. @Override
  325. protected void dispatch(CommunicationHandler handler) {
  326. handler.onResponseHandlingStarted(this);
  327. }
  328. }
  329. /**
  330. * Event triggered when a application is stopped by calling
  331. * {@link ApplicationConnection#setApplicationRunning(false)}.
  332. *
  333. * To listen for the event add a {@link ApplicationStoppedHandler} by
  334. * invoking
  335. * {@link ApplicationConnection#addHandler(ApplicationConnection.ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
  336. * to the {@link ApplicationConnection}
  337. *
  338. * @since 7.1.8
  339. * @author Vaadin Ltd
  340. */
  341. public static class ApplicationStoppedEvent extends
  342. GwtEvent<ApplicationStoppedHandler> {
  343. public static Type<ApplicationStoppedHandler> TYPE = new Type<ApplicationStoppedHandler>();
  344. @Override
  345. public Type<ApplicationStoppedHandler> getAssociatedType() {
  346. return TYPE;
  347. }
  348. @Override
  349. protected void dispatch(ApplicationStoppedHandler listener) {
  350. listener.onApplicationStopped(this);
  351. }
  352. }
  353. /**
  354. * Allows custom handling of communication errors.
  355. */
  356. public interface CommunicationErrorHandler {
  357. /**
  358. * Called when a communication error has occurred. Returning
  359. * <code>true</code> from this method suppresses error handling.
  360. *
  361. * @param details
  362. * A string describing the error.
  363. * @param statusCode
  364. * The HTTP status code (e.g. 404, etc).
  365. * @return true if the error reporting should be suppressed, false to
  366. * perform normal error reporting.
  367. */
  368. public boolean onError(String details, int statusCode);
  369. }
  370. /**
  371. * A listener for listening to application stopped events. The listener can
  372. * be added to a {@link ApplicationConnection} by invoking
  373. * {@link ApplicationConnection#addHandler(ApplicationStoppedEvent.Type, ApplicationStoppedHandler)}
  374. *
  375. * @since 7.1.8
  376. * @author Vaadin Ltd
  377. */
  378. public interface ApplicationStoppedHandler extends EventHandler {
  379. /**
  380. * Triggered when the {@link ApplicationConnection} marks a previously
  381. * running application as stopped by invoking
  382. * {@link ApplicationConnection#setApplicationRunning(false)}
  383. *
  384. * @param event
  385. * the event triggered by the {@link ApplicationConnection}
  386. */
  387. void onApplicationStopped(ApplicationStoppedEvent event);
  388. }
  389. private CommunicationErrorHandler communicationErrorDelegate = null;
  390. private VLoadingIndicator loadingIndicator;
  391. private Heartbeat heartbeat = GWT.create(Heartbeat.class);
  392. private boolean tooltipInitialized = false;
  393. public static class MultiStepDuration extends Duration {
  394. private int previousStep = elapsedMillis();
  395. public void logDuration(String message) {
  396. logDuration(message, 0);
  397. }
  398. public void logDuration(String message, int minDuration) {
  399. int currentTime = elapsedMillis();
  400. int stepDuration = currentTime - previousStep;
  401. if (stepDuration >= minDuration) {
  402. VConsole.log(message + ": " + stepDuration + " ms");
  403. }
  404. previousStep = currentTime;
  405. }
  406. }
  407. public ApplicationConnection() {
  408. // Assuming UI data is eagerly loaded
  409. ConnectorBundleLoader.get().loadBundle(
  410. ConnectorBundleLoader.EAGER_BUNDLE_NAME, null);
  411. uIConnector = GWT.create(UIConnector.class);
  412. rpcManager = GWT.create(RpcManager.class);
  413. layoutManager = GWT.create(LayoutManager.class);
  414. layoutManager.setConnection(this);
  415. tooltip = GWT.create(VTooltip.class);
  416. loadingIndicator = GWT.create(VLoadingIndicator.class);
  417. loadingIndicator.setConnection(this);
  418. }
  419. public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
  420. VConsole.log("Starting application " + cnf.getRootPanelId());
  421. VConsole.log("Using theme: " + cnf.getThemeName());
  422. VConsole.log("Vaadin application servlet version: "
  423. + cnf.getServletVersion());
  424. if (!cnf.getServletVersion().equals(Version.getFullVersion())) {
  425. VConsole.error("Warning: your widget set seems to be built with a different "
  426. + "version than the one used on server. Unexpected "
  427. + "behavior may occur.");
  428. }
  429. this.widgetSet = widgetSet;
  430. configuration = cnf;
  431. ComponentLocator componentLocator = new ComponentLocator(this);
  432. String appRootPanelName = cnf.getRootPanelId();
  433. // remove the end (window name) of autogenerated rootpanel id
  434. appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
  435. initializeTestbenchHooks(componentLocator, appRootPanelName);
  436. initializeClientHooks();
  437. uIConnector.init(cnf.getRootPanelId(), this);
  438. tooltip.setOwner(uIConnector.getWidget());
  439. getLoadingIndicator().show();
  440. heartbeat.init(this);
  441. Window.addWindowClosingHandler(new ClosingHandler() {
  442. @Override
  443. public void onWindowClosing(ClosingEvent event) {
  444. webkitMaybeIgnoringRequests = true;
  445. }
  446. });
  447. // Ensure the overlay container is added to the dom and set as a live
  448. // area for assistive devices
  449. Element overlayContainer = VOverlay.getOverlayContainer(this);
  450. Roles.getAlertRole().setAriaLiveProperty(overlayContainer,
  451. LiveValue.ASSERTIVE);
  452. VOverlay.setOverlayContainerLabel(this,
  453. getUIConnector().getState().overlayContainerLabel);
  454. Roles.getAlertRole().setAriaRelevantProperty(overlayContainer,
  455. RelevantValue.ADDITIONS);
  456. }
  457. /**
  458. * Starts this application. Don't call this method directly - it's called by
  459. * {@link ApplicationConfiguration#startNextApplication()}, which should be
  460. * called once this application has started (first response received) or
  461. * failed to start. This ensures that the applications are started in order,
  462. * to avoid session-id problems.
  463. *
  464. */
  465. public void start() {
  466. String jsonText = configuration.getUIDL();
  467. if (jsonText == null) {
  468. // inital UIDL not in DOM, request later
  469. repaintAll();
  470. } else {
  471. // Update counter so TestBench knows something is still going on
  472. hasActiveRequest = true;
  473. // initial UIDL provided in DOM, continue as if returned by request
  474. handleJSONText(jsonText, -1);
  475. }
  476. // Tooltip can't be created earlier because the
  477. // necessary fields are not setup to add it in the
  478. // correct place in the DOM
  479. if (!tooltipInitialized) {
  480. tooltipInitialized = true;
  481. ApplicationConfiguration.runWhenDependenciesLoaded(new Command() {
  482. @Override
  483. public void execute() {
  484. getVTooltip().initializeAssistiveTooltips();
  485. }
  486. });
  487. }
  488. }
  489. /**
  490. * Checks if there is some work to be done on the client side
  491. *
  492. * @return true if the client has some work to be done, false otherwise
  493. */
  494. private boolean isActive() {
  495. return isWorkPending() || hasActiveRequest()
  496. || isExecutingDeferredCommands();
  497. }
  498. private native void initializeTestbenchHooks(
  499. ComponentLocator componentLocator, String TTAppId)
  500. /*-{
  501. var ap = this;
  502. var client = {};
  503. client.isActive = $entry(function() {
  504. return ap.@com.vaadin.client.ApplicationConnection::isActive()();
  505. });
  506. var vi = ap.@com.vaadin.client.ApplicationConnection::getVersionInfo()();
  507. if (vi) {
  508. client.getVersionInfo = function() {
  509. return vi;
  510. }
  511. }
  512. client.getProfilingData = $entry(function() {
  513. var pd = [
  514. ap.@com.vaadin.client.ApplicationConnection::lastProcessingTime,
  515. ap.@com.vaadin.client.ApplicationConnection::totalProcessingTime
  516. ];
  517. pd = pd.concat(ap.@com.vaadin.client.ApplicationConnection::serverTimingInfo);
  518. pd[pd.length] = ap.@com.vaadin.client.ApplicationConnection::bootstrapTime;
  519. return pd;
  520. });
  521. client.getElementByPath = $entry(function(id) {
  522. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
  523. });
  524. client.getElementByPathStartingAt = $entry(function(id, element) {
  525. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementByPathStartingAt(Ljava/lang/String;Lcom/google/gwt/dom/client/Element;)(id, element);
  526. });
  527. client.getElementsByPath = $entry(function(id) {
  528. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementsByPath(Ljava/lang/String;)(id);
  529. });
  530. client.getElementsByPathStartingAt = $entry(function(id, element) {
  531. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getElementsByPathStartingAt(Ljava/lang/String;Lcom/google/gwt/dom/client/Element;)(id, element);
  532. });
  533. client.getPathForElement = $entry(function(element) {
  534. return componentLocator.@com.vaadin.client.componentlocator.ComponentLocator::getPathForElement(Lcom/google/gwt/dom/client/Element;)(element);
  535. });
  536. client.initializing = false;
  537. $wnd.vaadin.clients[TTAppId] = client;
  538. }-*/;
  539. private static native final int calculateBootstrapTime()
  540. /*-{
  541. if ($wnd.performance && $wnd.performance.timing) {
  542. return (new Date).getTime() - $wnd.performance.timing.responseStart;
  543. } else {
  544. // performance.timing not supported
  545. return -1;
  546. }
  547. }-*/;
  548. /**
  549. * Helper for tt initialization
  550. */
  551. private JavaScriptObject getVersionInfo() {
  552. return configuration.getVersionInfoJSObject();
  553. }
  554. /**
  555. * Publishes a JavaScript API for mash-up applications.
  556. * <ul>
  557. * <li><code>vaadin.forceSync()</code> sends pending variable changes, in
  558. * effect synchronizing the server and client state. This is done for all
  559. * applications on host page.</li>
  560. * <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
  561. * called after each XHR made by vaadin application. Note, that it is
  562. * attaching js functions responsibility to create the variable like this:
  563. *
  564. * <code><pre>
  565. * if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
  566. * postRequestHooks.myHook = function(appId) {
  567. * if(appId == "MyAppOfInterest") {
  568. * // do the staff you need on xhr activity
  569. * }
  570. * }
  571. * </pre></code> First parameter passed to these functions is the identifier
  572. * of Vaadin application that made the request.
  573. * </ul>
  574. *
  575. * TODO make this multi-app aware
  576. */
  577. private native void initializeClientHooks()
  578. /*-{
  579. var app = this;
  580. var oldSync;
  581. if ($wnd.vaadin.forceSync) {
  582. oldSync = $wnd.vaadin.forceSync;
  583. }
  584. $wnd.vaadin.forceSync = $entry(function() {
  585. if (oldSync) {
  586. oldSync();
  587. }
  588. app.@com.vaadin.client.ApplicationConnection::sendPendingVariableChanges()();
  589. });
  590. var oldForceLayout;
  591. if ($wnd.vaadin.forceLayout) {
  592. oldForceLayout = $wnd.vaadin.forceLayout;
  593. }
  594. $wnd.vaadin.forceLayout = $entry(function() {
  595. if (oldForceLayout) {
  596. oldForceLayout();
  597. }
  598. app.@com.vaadin.client.ApplicationConnection::forceLayout()();
  599. });
  600. }-*/;
  601. /**
  602. * Runs possibly registered client side post request hooks. This is expected
  603. * to be run after each uidl request made by Vaadin application.
  604. *
  605. * @param appId
  606. */
  607. private static native void runPostRequestHooks(String appId)
  608. /*-{
  609. if ($wnd.vaadin.postRequestHooks) {
  610. for ( var hook in $wnd.vaadin.postRequestHooks) {
  611. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  612. try {
  613. $wnd.vaadin.postRequestHooks[hook](appId);
  614. } catch (e) {
  615. }
  616. }
  617. }
  618. }
  619. }-*/;
  620. /**
  621. * If on Liferay and logged in, ask the client side session management
  622. * JavaScript to extend the session duration.
  623. *
  624. * Otherwise, Liferay client side JavaScript will explicitly expire the
  625. * session even though the server side considers the session to be active.
  626. * See ticket #8305 for more information.
  627. */
  628. protected native void extendLiferaySession()
  629. /*-{
  630. if ($wnd.Liferay && $wnd.Liferay.Session) {
  631. $wnd.Liferay.Session.extend();
  632. // if the extend banner is visible, hide it
  633. if ($wnd.Liferay.Session.banner) {
  634. $wnd.Liferay.Session.banner.remove();
  635. }
  636. }
  637. }-*/;
  638. /**
  639. * Indicates whether or not there are currently active UIDL requests. Used
  640. * internally to sequence requests properly, seldom needed in Widgets.
  641. *
  642. * @return true if there are active requests
  643. */
  644. public boolean hasActiveRequest() {
  645. return hasActiveRequest;
  646. }
  647. private String getRepaintAllParameters() {
  648. String parameters = ApplicationConstants.URL_PARAMETER_REPAINT_ALL
  649. + "=1";
  650. return parameters;
  651. }
  652. protected void repaintAll() {
  653. makeUidlRequest(new JSONArray(), getRepaintAllParameters());
  654. }
  655. /**
  656. * Requests an analyze of layouts, to find inconsistencies. Exclusively used
  657. * for debugging during development.
  658. *
  659. * @deprecated as of 7.1. Replaced by {@link UIConnector#analyzeLayouts()}
  660. */
  661. @Deprecated
  662. public void analyzeLayouts() {
  663. getUIConnector().analyzeLayouts();
  664. }
  665. /**
  666. * Sends a request to the server to print details to console that will help
  667. * the developer to locate the corresponding server-side connector in the
  668. * source code.
  669. *
  670. * @param serverConnector
  671. * @deprecated as of 7.1. Replaced by
  672. * {@link UIConnector#showServerDebugInfo(ServerConnector)}
  673. */
  674. @Deprecated
  675. void highlightConnector(ServerConnector serverConnector) {
  676. getUIConnector().showServerDebugInfo(serverConnector);
  677. }
  678. /**
  679. * Makes an UIDL request to the server.
  680. *
  681. * @param reqInvocations
  682. * Data containing RPC invocations and all related information.
  683. * @param extraParams
  684. * Parameters that are added as GET parameters to the url.
  685. * Contains key=value pairs joined by & characters or is empty if
  686. * no parameters should be added. Should not start with any
  687. * special character.
  688. */
  689. protected void makeUidlRequest(final JSONArray reqInvocations,
  690. final String extraParams) {
  691. startRequest();
  692. JSONObject payload = new JSONObject();
  693. if (!getCsrfToken().equals(
  694. ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE)) {
  695. payload.put(ApplicationConstants.CSRF_TOKEN, new JSONString(
  696. getCsrfToken()));
  697. }
  698. payload.put(ApplicationConstants.RPC_INVOCATIONS, reqInvocations);
  699. payload.put(ApplicationConstants.SERVER_SYNC_ID, new JSONNumber(
  700. lastSeenServerSyncId));
  701. VConsole.log("Making UIDL Request with params: " + payload);
  702. String uri = translateVaadinUri(ApplicationConstants.APP_PROTOCOL_PREFIX
  703. + ApplicationConstants.UIDL_PATH + '/');
  704. if (extraParams != null && extraParams.length() > 0) {
  705. uri = addGetParameters(uri, extraParams);
  706. }
  707. uri = addGetParameters(uri, UIConstants.UI_ID_PARAMETER + "="
  708. + configuration.getUIId());
  709. doUidlRequest(uri, payload);
  710. }
  711. /**
  712. * Sends an asynchronous or synchronous UIDL request to the server using the
  713. * given URI.
  714. *
  715. * @param uri
  716. * The URI to use for the request. May includes GET parameters
  717. * @param payload
  718. * The contents of the request to send
  719. */
  720. protected void doUidlRequest(final String uri, final JSONObject payload) {
  721. doUidlRequest(uri, payload, true);
  722. }
  723. /**
  724. * Sends an asynchronous or synchronous UIDL request to the server using the
  725. * given URI.
  726. *
  727. * @param uri
  728. * The URI to use for the request. May includes GET parameters
  729. * @param payload
  730. * The contents of the request to send
  731. * @param retry
  732. * true when a status code 0 should be retried
  733. * @since 7.3.7
  734. */
  735. protected void doUidlRequest(final String uri, final JSONObject payload,
  736. final boolean retry) {
  737. RequestCallback requestCallback = new RequestCallback() {
  738. @Override
  739. public void onError(Request request, Throwable exception) {
  740. handleCommunicationError(exception.getMessage(), -1);
  741. }
  742. private void handleCommunicationError(String details, int statusCode) {
  743. if (!handleErrorInDelegate(details, statusCode)) {
  744. showCommunicationError(details, statusCode);
  745. }
  746. endRequest();
  747. // Consider application not running any more and prevent all
  748. // future requests
  749. setApplicationRunning(false);
  750. }
  751. @Override
  752. public void onResponseReceived(Request request, Response response) {
  753. VConsole.log("Server visit took "
  754. + String.valueOf((new Date()).getTime()
  755. - requestStartTime.getTime()) + "ms");
  756. int statusCode = response.getStatusCode();
  757. // Notify network observers about response status
  758. fireEvent(new ConnectionStatusEvent(statusCode));
  759. switch (statusCode) {
  760. case 0:
  761. if (retry) {
  762. /*
  763. * There are 2 situations where the error can pop up:
  764. *
  765. * 1) Request was most likely canceled because the
  766. * browser is maybe navigating away from the page. Just
  767. * send the request again without displaying any error
  768. * in case the navigation isn't carried through.
  769. *
  770. * 2) The browser failed to establish a network
  771. * connection. This was observed with keep-alive
  772. * requests, and under wi-fi roaming conditions.
  773. *
  774. * Status code 0 does indicate that there was no server
  775. * side processing, so we can retry the request.
  776. */
  777. VConsole.log("Status code 0, retrying");
  778. (new Timer() {
  779. @Override
  780. public void run() {
  781. doUidlRequest(uri, payload, false);
  782. }
  783. }).schedule(100);
  784. } else {
  785. handleCommunicationError(
  786. "Invalid status code 0 (server down?)",
  787. statusCode);
  788. }
  789. return;
  790. case 401:
  791. /*
  792. * Authorization has failed. Could be that the session has
  793. * timed out and the container is redirecting to a login
  794. * page.
  795. */
  796. showAuthenticationError("");
  797. endRequest();
  798. return;
  799. case 503:
  800. /*
  801. * We'll assume msec instead of the usual seconds. If
  802. * there's no Retry-After header, handle the error like a
  803. * 500, as per RFC 2616 section 10.5.4.
  804. */
  805. String delay = response.getHeader("Retry-After");
  806. if (delay != null) {
  807. VConsole.log("503, retrying in " + delay + "msec");
  808. (new Timer() {
  809. @Override
  810. public void run() {
  811. doUidlRequest(uri, payload);
  812. }
  813. }).schedule(Integer.parseInt(delay));
  814. return;
  815. }
  816. }
  817. if ((statusCode / 100) == 4) {
  818. // Handle all 4xx errors the same way as (they are
  819. // all permanent errors)
  820. showCommunicationError(
  821. "UIDL could not be read from server. Check servlets mappings. Error code: "
  822. + statusCode, statusCode);
  823. endRequest();
  824. return;
  825. } else if ((statusCode / 100) == 5) {
  826. // Something's wrong on the server, there's nothing the
  827. // client can do except maybe try again.
  828. handleCommunicationError("Server error. Error code: "
  829. + statusCode, statusCode);
  830. return;
  831. }
  832. String contentType = response.getHeader("Content-Type");
  833. if (contentType == null
  834. || !contentType.startsWith("application/json")) {
  835. /*
  836. * A servlet filter or equivalent may have intercepted the
  837. * request and served non-UIDL content (for instance, a
  838. * login page if the session has expired.) If the response
  839. * contains a magic substring, do a synchronous refresh. See
  840. * #8241.
  841. */
  842. MatchResult refreshToken = RegExp.compile(
  843. UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)").exec(
  844. response.getText());
  845. if (refreshToken != null) {
  846. redirect(refreshToken.getGroup(2));
  847. return;
  848. }
  849. }
  850. // for(;;);[realjson]
  851. final String jsonText = response.getText().substring(9,
  852. response.getText().length() - 1);
  853. handleJSONText(jsonText, statusCode);
  854. }
  855. };
  856. if (push != null) {
  857. push.push(payload);
  858. } else {
  859. try {
  860. doAjaxRequest(uri, payload, requestCallback);
  861. } catch (RequestException e) {
  862. VConsole.error(e);
  863. endRequest();
  864. fireEvent(new ConnectionStatusEvent(0));
  865. }
  866. }
  867. }
  868. /**
  869. * Handles received UIDL JSON text, parsing it, and passing it on to the
  870. * appropriate handlers, while logging timing information.
  871. *
  872. * @param jsonText
  873. * @param statusCode
  874. */
  875. private void handleJSONText(String jsonText, int statusCode) {
  876. final Date start = new Date();
  877. final ValueMap json;
  878. try {
  879. json = parseJSONResponse(jsonText);
  880. } catch (final Exception e) {
  881. endRequest();
  882. showCommunicationError(e.getMessage() + " - Original JSON-text:"
  883. + jsonText, statusCode);
  884. return;
  885. }
  886. VConsole.log("JSON parsing took "
  887. + (new Date().getTime() - start.getTime()) + "ms");
  888. if (isApplicationRunning()) {
  889. handleReceivedJSONMessage(start, jsonText, json);
  890. } else {
  891. setApplicationRunning(true);
  892. handleWhenCSSLoaded(jsonText, json);
  893. }
  894. }
  895. /**
  896. * Sends an asynchronous UIDL request to the server using the given URI.
  897. *
  898. * @param uri
  899. * The URI to use for the request. May includes GET parameters
  900. * @param payload
  901. * The contents of the request to send
  902. * @param requestCallback
  903. * The handler for the response
  904. * @throws RequestException
  905. * if the request could not be sent
  906. */
  907. protected void doAjaxRequest(String uri, JSONObject payload,
  908. RequestCallback requestCallback) throws RequestException {
  909. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  910. // TODO enable timeout
  911. // rb.setTimeoutMillis(timeoutMillis);
  912. // TODO this should be configurable
  913. rb.setHeader("Content-Type", JsonConstants.JSON_CONTENT_TYPE);
  914. rb.setRequestData(payload.toString());
  915. rb.setCallback(requestCallback);
  916. final Request request = rb.send();
  917. if (webkitMaybeIgnoringRequests && BrowserInfo.get().isWebkit()) {
  918. final int retryTimeout = 250;
  919. new Timer() {
  920. @Override
  921. public void run() {
  922. // Use native js to access private field in Request
  923. if (resendRequest(request) && webkitMaybeIgnoringRequests) {
  924. // Schedule retry if still needed
  925. schedule(retryTimeout);
  926. }
  927. }
  928. }.schedule(retryTimeout);
  929. }
  930. }
  931. private static native boolean resendRequest(Request request)
  932. /*-{
  933. var xhr = request.@com.google.gwt.http.client.Request::xmlHttpRequest
  934. if (xhr.readyState != 1) {
  935. // Progressed to some other readyState -> no longer blocked
  936. return false;
  937. }
  938. try {
  939. xhr.send();
  940. return true;
  941. } catch (e) {
  942. // send throws exception if it is running for real
  943. return false;
  944. }
  945. }-*/;
  946. int cssWaits = 0;
  947. /**
  948. * Holds the time spent rendering the last request
  949. */
  950. protected int lastProcessingTime;
  951. /**
  952. * Holds the total time spent rendering requests during the lifetime of the
  953. * session.
  954. */
  955. protected int totalProcessingTime;
  956. /**
  957. * Holds the time it took to load the page and render the first view. 0
  958. * means that this value has not yet been calculated because the first view
  959. * has not yet been rendered (or that your browser is very fast). -1 means
  960. * that the browser does not support the performance.timing feature used to
  961. * get this measurement.
  962. */
  963. private int bootstrapTime;
  964. /**
  965. * Holds the timing information from the server-side. How much time was
  966. * spent servicing the last request and how much time has been spent
  967. * servicing the session so far. These values are always one request behind,
  968. * since they cannot be measured before the request is finished.
  969. */
  970. private ValueMap serverTimingInfo;
  971. /**
  972. * Holds the last seen response id given by the server.
  973. * <p>
  974. * The server generates a strictly increasing id for each response to each
  975. * request from the client. This ID is then replayed back to the server on
  976. * each request. This helps the server in knowing in what state the client
  977. * is, and compare it to its own state. In short, it helps with concurrent
  978. * changes between the client and server.
  979. * <p>
  980. * Initial value, i.e. no responses received from the server, is
  981. * {@link #UNDEFINED_SYNC_ID} ({@value #UNDEFINED_SYNC_ID}). This happens
  982. * between the bootstrap HTML being loaded and the first UI being rendered;
  983. */
  984. private int lastSeenServerSyncId = UNDEFINED_SYNC_ID;
  985. /**
  986. * The value of an undefined sync id.
  987. * <p>
  988. * This must be <code>-1</code>, because of the contract in
  989. * {@link #getLastResponseId()}
  990. */
  991. private static final int UNDEFINED_SYNC_ID = -1;
  992. static final int MAX_CSS_WAITS = 100;
  993. protected void handleWhenCSSLoaded(final String jsonText,
  994. final ValueMap json) {
  995. if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
  996. (new Timer() {
  997. @Override
  998. public void run() {
  999. handleWhenCSSLoaded(jsonText, json);
  1000. }
  1001. }).schedule(50);
  1002. // Show this message just once
  1003. if (cssWaits++ == 0) {
  1004. VConsole.log("Assuming CSS loading is not complete, "
  1005. + "postponing render phase. "
  1006. + "(.v-loading-indicator height == 0)");
  1007. }
  1008. } else {
  1009. cssLoaded = true;
  1010. if (cssWaits >= MAX_CSS_WAITS) {
  1011. getLogger().severe("CSS files may have not loaded properly.");
  1012. }
  1013. handleReceivedJSONMessage(new Date(), jsonText, json);
  1014. }
  1015. }
  1016. /**
  1017. * Checks whether or not the CSS is loaded. By default checks the size of
  1018. * the loading indicator element.
  1019. *
  1020. * @return
  1021. */
  1022. protected boolean isCSSLoaded() {
  1023. return cssLoaded
  1024. || getLoadingIndicator().getElement().getOffsetHeight() != 0;
  1025. }
  1026. /**
  1027. * Shows the communication error notification.
  1028. *
  1029. * @param details
  1030. * Optional details for debugging.
  1031. * @param statusCode
  1032. * The status code returned for the request
  1033. *
  1034. */
  1035. protected void showCommunicationError(String details, int statusCode) {
  1036. VConsole.error("Communication error: " + details);
  1037. showError(details, configuration.getCommunicationError());
  1038. }
  1039. /**
  1040. * Shows the authentication error notification.
  1041. *
  1042. * @param details
  1043. * Optional details for debugging.
  1044. */
  1045. protected void showAuthenticationError(String details) {
  1046. VConsole.error("Authentication error: " + details);
  1047. showError(details, configuration.getAuthorizationError());
  1048. }
  1049. /**
  1050. * Shows the session expiration notification.
  1051. *
  1052. * @param details
  1053. * Optional details for debugging.
  1054. */
  1055. public void showSessionExpiredError(String details) {
  1056. VConsole.error("Session expired: " + details);
  1057. showError(details, configuration.getSessionExpiredError());
  1058. }
  1059. /**
  1060. * Shows an error notification.
  1061. *
  1062. * @param details
  1063. * Optional details for debugging.
  1064. * @param message
  1065. * An ErrorMessage describing the error.
  1066. */
  1067. protected void showError(String details, ErrorMessage message) {
  1068. showError(details, message.getCaption(), message.getMessage(),
  1069. message.getUrl());
  1070. }
  1071. /**
  1072. * Shows the error notification.
  1073. *
  1074. * @param details
  1075. * Optional details for debugging.
  1076. */
  1077. private void showError(String details, String caption, String message,
  1078. String url) {
  1079. StringBuilder html = new StringBuilder();
  1080. if (caption != null) {
  1081. html.append("<h1>");
  1082. html.append(caption);
  1083. html.append("</h1>");
  1084. }
  1085. if (message != null) {
  1086. html.append("<p>");
  1087. html.append(message);
  1088. html.append("</p>");
  1089. }
  1090. if (html.length() > 0) {
  1091. // Add error description
  1092. if (details != null) {
  1093. html.append("<p><i style=\"font-size:0.7em\">");
  1094. html.append(details);
  1095. html.append("</i></p>");
  1096. }
  1097. VNotification n = VNotification.createNotification(1000 * 60 * 45,
  1098. uIConnector.getWidget());
  1099. n.addEventListener(new NotificationRedirect(url));
  1100. n.show(html.toString(), VNotification.CENTERED_TOP,
  1101. VNotification.STYLE_SYSTEM);
  1102. } else {
  1103. redirect(url);
  1104. }
  1105. }
  1106. protected void startRequest() {
  1107. if (hasActiveRequest) {
  1108. VConsole.error("Trying to start a new request while another is active");
  1109. }
  1110. hasActiveRequest = true;
  1111. requestStartTime = new Date();
  1112. loadingIndicator.trigger();
  1113. eventBus.fireEvent(new RequestStartingEvent(this));
  1114. }
  1115. protected void endRequest() {
  1116. if (!hasActiveRequest) {
  1117. VConsole.error("No active request");
  1118. }
  1119. // After checkForPendingVariableBursts() there may be a new active
  1120. // request, so we must set hasActiveRequest to false before, not after,
  1121. // the call. Active requests used to be tracked with an integer counter,
  1122. // so setting it after used to work but not with the #8505 changes.
  1123. hasActiveRequest = false;
  1124. webkitMaybeIgnoringRequests = false;
  1125. if (isApplicationRunning()) {
  1126. checkForPendingVariableBursts();
  1127. runPostRequestHooks(configuration.getRootPanelId());
  1128. }
  1129. // deferring to avoid flickering
  1130. Scheduler.get().scheduleDeferred(new Command() {
  1131. @Override
  1132. public void execute() {
  1133. if (!hasActiveRequest()) {
  1134. getLoadingIndicator().hide();
  1135. // If on Liferay and session expiration management is in
  1136. // use, extend session duration on each request.
  1137. // Doing it here rather than before the request to improve
  1138. // responsiveness.
  1139. // Postponed until the end of the next request if other
  1140. // requests still pending.
  1141. extendLiferaySession();
  1142. }
  1143. }
  1144. });
  1145. eventBus.fireEvent(new ResponseHandlingEndedEvent(this));
  1146. }
  1147. /**
  1148. * This method is called after applying uidl change set to application.
  1149. *
  1150. * It will clean current and queued variable change sets. And send next
  1151. * change set if it exists.
  1152. */
  1153. private void checkForPendingVariableBursts() {
  1154. cleanVariableBurst(pendingInvocations);
  1155. if (pendingBursts.size() > 0) {
  1156. for (LinkedHashMap<String, MethodInvocation> pendingBurst : pendingBursts) {
  1157. cleanVariableBurst(pendingBurst);
  1158. }
  1159. LinkedHashMap<String, MethodInvocation> nextBurst = pendingBursts
  1160. .remove(0);
  1161. buildAndSendVariableBurst(nextBurst);
  1162. }
  1163. }
  1164. /**
  1165. * Cleans given queue of variable changes of such changes that came from
  1166. * components that do not exist anymore.
  1167. *
  1168. * @param variableBurst
  1169. */
  1170. private void cleanVariableBurst(
  1171. LinkedHashMap<String, MethodInvocation> variableBurst) {
  1172. Iterator<MethodInvocation> iterator = variableBurst.values().iterator();
  1173. while (iterator.hasNext()) {
  1174. String id = iterator.next().getConnectorId();
  1175. if (!getConnectorMap().hasConnector(id)
  1176. && !getConnectorMap().isDragAndDropPaintable(id)) {
  1177. // variable owner does not exist anymore
  1178. iterator.remove();
  1179. VConsole.log("Removed variable from removed component: " + id);
  1180. }
  1181. }
  1182. }
  1183. /**
  1184. * Checks if the client has running or scheduled commands
  1185. */
  1186. private boolean isWorkPending() {
  1187. ConnectorMap connectorMap = getConnectorMap();
  1188. JsArrayObject<ServerConnector> connectors = connectorMap
  1189. .getConnectorsAsJsArray();
  1190. int size = connectors.size();
  1191. for (int i = 0; i < size; i++) {
  1192. ServerConnector conn = connectors.get(i);
  1193. ComponentConnector compConn = null;
  1194. if (conn instanceof ComponentConnector) {
  1195. compConn = (ComponentConnector) conn;
  1196. Widget wgt = compConn.getWidget();
  1197. if (wgt instanceof DeferredWorker) {
  1198. if (((DeferredWorker) wgt).isWorkPending()) {
  1199. return true;
  1200. }
  1201. }
  1202. }
  1203. }
  1204. return false;
  1205. }
  1206. /**
  1207. * Checks if deferred commands are (potentially) still being executed as a
  1208. * result of an update from the server. Returns true if a deferred command
  1209. * might still be executing, false otherwise. This will not work correctly
  1210. * if a deferred command is added in another deferred command.
  1211. * <p>
  1212. * Used by the native "client.isActive" function.
  1213. * </p>
  1214. *
  1215. * @return true if deferred commands are (potentially) being executed, false
  1216. * otherwise
  1217. */
  1218. private boolean isExecutingDeferredCommands() {
  1219. Scheduler s = Scheduler.get();
  1220. if (s instanceof VSchedulerImpl) {
  1221. return ((VSchedulerImpl) s).hasWorkQueued();
  1222. } else {
  1223. return false;
  1224. }
  1225. }
  1226. /**
  1227. * Returns the loading indicator used by this ApplicationConnection
  1228. *
  1229. * @return The loading indicator for this ApplicationConnection
  1230. */
  1231. public VLoadingIndicator getLoadingIndicator() {
  1232. return loadingIndicator;
  1233. }
  1234. /**
  1235. * Determines whether or not the loading indicator is showing.
  1236. *
  1237. * @return true if the loading indicator is visible
  1238. * @deprecated As of 7.1. Use {@link #getLoadingIndicator()} and
  1239. * {@link VLoadingIndicator#isVisible()}.isVisible() instead.
  1240. */
  1241. @Deprecated
  1242. public boolean isLoadingIndicatorVisible() {
  1243. return getLoadingIndicator().isVisible();
  1244. }
  1245. private static native ValueMap parseJSONResponse(String jsonText)
  1246. /*-{
  1247. try {
  1248. return JSON.parse(jsonText);
  1249. } catch (ignored) {
  1250. return eval('(' + jsonText + ')');
  1251. }
  1252. }-*/;
  1253. private void handleReceivedJSONMessage(Date start, String jsonText,
  1254. ValueMap json) {
  1255. handleUIDLMessage(start, jsonText, json);
  1256. }
  1257. /**
  1258. * Gets the id of the last received response. This id can be used by
  1259. * connectors to determine whether new data has been received from the
  1260. * server to avoid doing the same calculations multiple times.
  1261. * <p>
  1262. * No guarantees are made for the structure of the id other than that there
  1263. * will be a new unique value every time a new response with data from the
  1264. * server is received.
  1265. * <p>
  1266. * The initial id when no request has yet been processed is -1.
  1267. *
  1268. * @return and id identifying the response
  1269. */
  1270. public int getLastResponseId() {
  1271. /*
  1272. * The discrepancy between field name and getter name is simply historic
  1273. * - API can't be changed, but the field was repurposed in a more
  1274. * general, yet compatible, use. "Response id" was deemed unsuitable a
  1275. * name, so it was called "server sync id" instead.
  1276. */
  1277. return lastSeenServerSyncId;
  1278. }
  1279. protected void handleUIDLMessage(final Date start, final String jsonText,
  1280. final ValueMap json) {
  1281. if (!responseHandlingLocks.isEmpty()) {
  1282. // Some component is doing something that can't be interrupted
  1283. // (e.g. animation that should be smooth). Enqueue the UIDL
  1284. // message for later processing.
  1285. VConsole.log("Postponing UIDL handling due to lock...");
  1286. pendingUIDLMessages.add(new PendingUIDLMessage(start, jsonText,
  1287. json));
  1288. forceHandleMessage.schedule(MAX_SUSPENDED_TIMEOUT);
  1289. return;
  1290. }
  1291. /*
  1292. * Lock response handling to avoid a situation where something pushed
  1293. * from the server gets processed while waiting for e.g. lazily loaded
  1294. * connectors that are needed for processing the current message.
  1295. */
  1296. final Object lock = new Object();
  1297. suspendReponseHandling(lock);
  1298. VConsole.log("Handling message from server");
  1299. eventBus.fireEvent(new ResponseHandlingStartedEvent(this));
  1300. final int syncId;
  1301. if (json.containsKey(ApplicationConstants.SERVER_SYNC_ID)) {
  1302. syncId = json.getInt(ApplicationConstants.SERVER_SYNC_ID);
  1303. /*
  1304. * Use sync id unless explicitly set as undefined, as is done by
  1305. * e.g. critical server-side notifications
  1306. */
  1307. if (syncId != -1) {
  1308. assert (lastSeenServerSyncId == UNDEFINED_SYNC_ID || syncId == lastSeenServerSyncId + 1) : "Newly retrieved server sync id was not exactly one larger than the previous one (new: "
  1309. + syncId + ", last seen: " + lastSeenServerSyncId + ")";
  1310. lastSeenServerSyncId = syncId;
  1311. }
  1312. } else {
  1313. syncId = -1;
  1314. VConsole.error("Server response didn't contain a sync id. "
  1315. + "Please verify that the server is up-to-date and that the response data has not been modified in transmission.");
  1316. }
  1317. // Handle redirect
  1318. if (json.containsKey("redirect")) {
  1319. String url = json.getValueMap("redirect").getString("url");
  1320. VConsole.log("redirecting to " + url);
  1321. redirect(url);
  1322. return;
  1323. }
  1324. final MultiStepDuration handleUIDLDuration = new MultiStepDuration();
  1325. // Get security key
  1326. if (json.containsKey(ApplicationConstants.UIDL_SECURITY_TOKEN_ID)) {
  1327. csrfToken = json
  1328. .getString(ApplicationConstants.UIDL_SECURITY_TOKEN_ID);
  1329. }
  1330. VConsole.log(" * Handling resources from server");
  1331. if (json.containsKey("resources")) {
  1332. ValueMap resources = json.getValueMap("resources");
  1333. JsArrayString keyArray = resources.getKeyArray();
  1334. int l = keyArray.length();
  1335. for (int i = 0; i < l; i++) {
  1336. String key = keyArray.get(i);
  1337. resourcesMap.put(key, resources.getAsString(key));
  1338. }
  1339. }
  1340. handleUIDLDuration.logDuration(
  1341. " * Handling resources from server completed", 10);
  1342. VConsole.log(" * Handling type inheritance map from server");
  1343. if (json.containsKey("typeInheritanceMap")) {
  1344. configuration.addComponentInheritanceInfo(json
  1345. .getValueMap("typeInheritanceMap"));
  1346. }
  1347. handleUIDLDuration.logDuration(
  1348. " * Handling type inheritance map from server completed", 10);
  1349. VConsole.log("Handling type mappings from server");
  1350. if (json.containsKey("typeMappings")) {
  1351. configuration.addComponentMappings(
  1352. json.getValueMap("typeMappings"), widgetSet);
  1353. }
  1354. VConsole.log("Handling resource dependencies");
  1355. if (json.containsKey("scriptDependencies")) {
  1356. loadScriptDependencies(json.getJSStringArray("scriptDependencies"));
  1357. }
  1358. if (json.containsKey("styleDependencies")) {
  1359. loadStyleDependencies(json.getJSStringArray("styleDependencies"));
  1360. }
  1361. handleUIDLDuration.logDuration(
  1362. " * Handling type mappings from server completed", 10);
  1363. /*
  1364. * Hook for e.g. TestBench to get details about server peformance
  1365. */
  1366. if (json.containsKey("timings")) {
  1367. serverTimingInfo = json.getValueMap("timings");
  1368. }
  1369. Command c = new Command() {
  1370. @Override
  1371. public void execute() {
  1372. assert syncId == -1 || syncId == lastSeenServerSyncId;
  1373. handleUIDLDuration.logDuration(" * Loading widgets completed",
  1374. 10);
  1375. Profiler.enter("Handling meta information");
  1376. ValueMap meta = null;
  1377. if (json.containsKey("meta")) {
  1378. VConsole.log(" * Handling meta information");
  1379. meta = json.getValueMap("meta");
  1380. if (meta.containsKey("repaintAll")) {
  1381. prepareRepaintAll();
  1382. }
  1383. if (meta.containsKey("timedRedirect")) {
  1384. final ValueMap timedRedirect = meta
  1385. .getValueMap("timedRedirect");
  1386. if (redirectTimer != null) {
  1387. redirectTimer.cancel();
  1388. }
  1389. redirectTimer = new Timer() {
  1390. @Override
  1391. public void run() {
  1392. redirect(timedRedirect.getString("url"));
  1393. }
  1394. };
  1395. sessionExpirationInterval = timedRedirect
  1396. .getInt("interval");
  1397. }
  1398. }
  1399. Profiler.leave("Handling meta information");
  1400. if (redirectTimer != null) {
  1401. redirectTimer.schedule(1000 * sessionExpirationInterval);
  1402. }
  1403. double processUidlStart = Duration.currentTimeMillis();
  1404. // Ensure that all connectors that we are about to update exist
  1405. JsArrayString createdConnectorIds = createConnectorsIfNeeded(json);
  1406. // Update states, do not fire events
  1407. JsArrayObject<StateChangeEvent> pendingStateChangeEvents = updateConnectorState(
  1408. json, createdConnectorIds);
  1409. /*
  1410. * Doing this here so that locales are available also to the
  1411. * connectors which get a state change event before the UI.
  1412. */
  1413. Profiler.enter("Handling locales");
  1414. VConsole.log(" * Handling locales");
  1415. // Store locale data
  1416. LocaleService
  1417. .addLocales(getUIConnector().getState().localeServiceState.localeData);
  1418. Profiler.leave("Handling locales");
  1419. // Update hierarchy, do not fire events
  1420. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(json);
  1421. // Fire hierarchy change events
  1422. sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
  1423. updateCaptions(pendingStateChangeEvents,
  1424. connectorHierarchyUpdateResult.parentChangedIds);
  1425. delegateToWidget(pendingStateChangeEvents);
  1426. // Fire state change events.
  1427. sendStateChangeEvents(pendingStateChangeEvents);
  1428. // Update of legacy (UIDL) style connectors
  1429. updateVaadin6StyleConnectors(json);
  1430. // Handle any RPC invocations done on the server side
  1431. handleRpcInvocations(json);
  1432. if (json.containsKey("dd")) {
  1433. // response contains data for drag and drop service
  1434. VDragAndDropManager.get().handleServerResponse(
  1435. json.getValueMap("dd"));
  1436. }
  1437. unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  1438. VConsole.log("handleUIDLMessage: "
  1439. + (Duration.currentTimeMillis() - processUidlStart)
  1440. + " ms");
  1441. Profiler.enter("Layout processing");
  1442. try {
  1443. LayoutManager layoutManager = getLayoutManager();
  1444. layoutManager.setEverythingNeedsMeasure();
  1445. layoutManager.layoutNow();
  1446. } catch (final Throwable e) {
  1447. VConsole.error(e);
  1448. }
  1449. Profiler.leave("Layout processing");
  1450. if (ApplicationConfiguration.isDebugMode()) {
  1451. Profiler.enter("Dumping state changes to the console");
  1452. VConsole.log(" * Dumping state changes to the console");
  1453. VConsole.dirUIDL(json, ApplicationConnection.this);
  1454. Profiler.leave("Dumping state changes to the console");
  1455. }
  1456. if (meta != null) {
  1457. Profiler.enter("Error handling");
  1458. if (meta.containsKey("appError")) {
  1459. ValueMap error = meta.getValueMap("appError");
  1460. showError(null, error.getString("caption"),
  1461. error.getString("message"),
  1462. error.getString("url"));
  1463. setApplicationRunning(false);
  1464. }
  1465. Profiler.leave("Error handling");
  1466. }
  1467. // TODO build profiling for widget impl loading time
  1468. lastProcessingTime = (int) ((new Date().getTime()) - start
  1469. .getTime());
  1470. totalProcessingTime += lastProcessingTime;
  1471. if (bootstrapTime == 0) {
  1472. bootstrapTime = calculateBootstrapTime();
  1473. if (Profiler.isEnabled() && bootstrapTime != -1) {
  1474. Profiler.logBootstrapTimings();
  1475. }
  1476. }
  1477. VConsole.log(" Processing time was "
  1478. + String.valueOf(lastProcessingTime) + "ms for "
  1479. + jsonText.length() + " characters of JSON");
  1480. VConsole.log("Referenced paintables: " + connectorMap.size());
  1481. if (meta == null || !meta.containsKey("async")) {
  1482. // End the request if the received message was a response,
  1483. // not sent asynchronously
  1484. endRequest();
  1485. }
  1486. resumeResponseHandling(lock);
  1487. if (Profiler.isEnabled()) {
  1488. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1489. @Override
  1490. public void execute() {
  1491. Profiler.logTimings();
  1492. Profiler.reset();
  1493. }
  1494. });
  1495. }
  1496. }
  1497. /**
  1498. * Properly clean up any old stuff to ensure everything is properly
  1499. * reinitialized.
  1500. */
  1501. private void prepareRepaintAll() {
  1502. String uiConnectorId = uIConnector.getConnectorId();
  1503. if (uiConnectorId == null) {
  1504. // Nothing to clear yet
  1505. return;
  1506. }
  1507. // Create fake server response that says that the uiConnector
  1508. // has no children
  1509. JSONObject fakeHierarchy = new JSONObject();
  1510. fakeHierarchy.put(uiConnectorId, new JSONArray());
  1511. JSONObject fakeJson = new JSONObject();
  1512. fakeJson.put("hierarchy", fakeHierarchy);
  1513. ValueMap fakeValueMap = fakeJson.getJavaScriptObject().cast();
  1514. // Update hierarchy based on the fake response
  1515. ConnectorHierarchyUpdateResult connectorHierarchyUpdateResult = updateConnectorHierarchy(fakeValueMap);
  1516. // Send hierarchy events based on the fake update
  1517. sendHierarchyChangeEvents(connectorHierarchyUpdateResult.events);
  1518. // Unregister all the old connectors that have now been removed
  1519. unregisterRemovedConnectors(connectorHierarchyUpdateResult.detachedConnectorIds);
  1520. getLayoutManager().cleanMeasuredSizes();
  1521. }
  1522. private void updateCaptions(
  1523. JsArrayObject<StateChangeEvent> pendingStateChangeEvents,
  1524. FastStringSet parentChangedIds) {
  1525. Profiler.enter("updateCaptions");
  1526. /*
  1527. * Find all components that might need a caption update based on
  1528. * pending state and hierarchy changes
  1529. */
  1530. FastStringSet needsCaptionUpdate = FastStringSet.create();
  1531. needsCaptionUpdate.addAll(parentChangedIds);
  1532. // Find components with potentially changed caption state
  1533. int size = pendingStateChangeEvents.size();
  1534. for (int i = 0; i < size; i++) {
  1535. StateChangeEvent event = pendingStateChangeEvents.get(i);
  1536. if (VCaption.mightChange(event)) {
  1537. ServerConnector connector = event.getConnector();
  1538. needsCaptionUpdate.add(connector.getConnectorId());
  1539. }
  1540. }
  1541. ConnectorMap connectorMap = getConnectorMap();
  1542. // Update captions for all suitable candidates
  1543. JsArrayString dump = needsCaptionUpdate.dump();
  1544. int needsUpdateLength = dump.length();
  1545. for (int i = 0; i < needsUpdateLength; i++) {
  1546. String childId = dump.get(i);
  1547. ServerConnector child = connectorMap.getConnector(childId);
  1548. if (child instanceof ComponentConnector
  1549. && ((ComponentConnector) child)
  1550. .delegateCaptionHandling()) {
  1551. ServerConnector parent = child.getParent();
  1552. if (parent instanceof HasComponentsConnector) {
  1553. Profiler.enter("HasComponentsConnector.updateCaption");
  1554. ((HasComponentsConnector) parent)
  1555. .updateCaption((ComponentConnector) child);
  1556. Profiler.leave("HasComponentsConnector.updateCaption");
  1557. }
  1558. }
  1559. }
  1560. Profiler.leave("updateCaptions");
  1561. }
  1562. private void delegateToWidget(
  1563. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  1564. Profiler.enter("@DelegateToWidget");
  1565. VConsole.log(" * Running @DelegateToWidget");
  1566. // Keep track of types that have no @DelegateToWidget in their
  1567. // state to optimize performance
  1568. FastStringSet noOpTypes = FastStringSet.create();
  1569. int size = pendingStateChangeEvents.size();
  1570. for (int eventIndex = 0; eventIndex < size; eventIndex++) {
  1571. StateChangeEvent sce = pendingStateChangeEvents
  1572. .get(eventIndex);
  1573. ServerConnector connector = sce.getConnector();
  1574. if (connector instanceof ComponentConnector) {
  1575. String className = connector.getClass().getName();
  1576. if (noOpTypes.contains(className)) {
  1577. continue;
  1578. }
  1579. ComponentConnector component = (ComponentConnector) connector;
  1580. Type stateType = AbstractConnector
  1581. .getStateType(component);
  1582. JsArrayString delegateToWidgetProperties = stateType
  1583. .getDelegateToWidgetProperties();
  1584. if (delegateToWidgetProperties == null) {
  1585. noOpTypes.add(className);
  1586. continue;
  1587. }
  1588. int length = delegateToWidgetProperties.length();
  1589. for (int i = 0; i < length; i++) {
  1590. String propertyName = delegateToWidgetProperties
  1591. .get(i);
  1592. if (sce.hasPropertyChanged(propertyName)) {
  1593. Property property = stateType
  1594. .getProperty(propertyName);
  1595. String method = property
  1596. .getDelegateToWidgetMethodName();
  1597. Profiler.enter("doDelegateToWidget");
  1598. doDelegateToWidget(component, property, method);
  1599. Profiler.leave("doDelegateToWidget");
  1600. }
  1601. }
  1602. }
  1603. }
  1604. Profiler.leave("@DelegateToWidget");
  1605. }
  1606. private void doDelegateToWidget(ComponentConnector component,
  1607. Property property, String methodName) {
  1608. Type type = TypeData.getType(component.getClass());
  1609. try {
  1610. Type widgetType = type.getMethod("getWidget")
  1611. .getReturnType();
  1612. Widget widget = component.getWidget();
  1613. Object propertyValue = property.getValue(component
  1614. .getState());
  1615. widgetType.getMethod(methodName).invoke(widget,
  1616. propertyValue);
  1617. } catch (NoDataException e) {
  1618. throw new RuntimeException(
  1619. "Missing data needed to invoke @DelegateToWidget for "
  1620. + Util.getSimpleName(component), e);
  1621. }
  1622. }
  1623. /**
  1624. * Sends the state change events created while updating the state
  1625. * information.
  1626. *
  1627. * This must be called after hierarchy change listeners have been
  1628. * called. At least caption updates for the parent are strange if
  1629. * fired from state change listeners and thus calls the parent
  1630. * BEFORE the parent is aware of the child (through a
  1631. * ConnectorHierarchyChangedEvent)
  1632. *
  1633. * @param pendingStateChangeEvents
  1634. * The events to send
  1635. */
  1636. private void sendStateChangeEvents(
  1637. JsArrayObject<StateChangeEvent> pendingStateChangeEvents) {
  1638. Profiler.enter("sendStateChangeEvents");
  1639. VConsole.log(" * Sending state change events");
  1640. int size = pendingStateChangeEvents.size();
  1641. for (int i = 0; i < size; i++) {
  1642. StateChangeEvent sce = pendingStateChangeEvents.get(i);
  1643. try {
  1644. sce.getConnector().fireEvent(sce);
  1645. } catch (final Throwable e) {
  1646. VConsole.error(e);
  1647. }
  1648. }
  1649. Profiler.leave("sendStateChangeEvents");
  1650. }
  1651. private void verifyConnectorHierarchy() {
  1652. Profiler.enter("verifyConnectorHierarchy - this is only performed in debug mode");
  1653. JsArrayObject<ServerConnector> currentConnectors = connectorMap
  1654. .getConnectorsAsJsArray();
  1655. int size = currentConnectors.size();
  1656. for (int i = 0; i < size; i++) {
  1657. ServerConnector c = currentConnectors.get(i);
  1658. if (c.getParent() != null) {
  1659. if (!c.getParent().getChildren().contains(c)) {
  1660. VConsole.error("ERROR: Connector "
  1661. + c.getConnectorId()
  1662. + " is connected to a parent but the parent ("
  1663. + c.getParent().getConnectorId()
  1664. + ") does not contain the connector");
  1665. }
  1666. } else if (c == getUIConnector()) {
  1667. // UIConnector for this connection, ignore
  1668. } else if (c instanceof WindowConnector
  1669. && getUIConnector().hasSubWindow(
  1670. (WindowConnector) c)) {
  1671. // Sub window attached to this UIConnector, ignore
  1672. } else {
  1673. // The connector has been detached from the
  1674. // hierarchy but was not unregistered.
  1675. VConsole.error("ERROR: Connector "
  1676. + c.getConnectorId()
  1677. + " is not attached to a parent but has not been unregistered");
  1678. }
  1679. }
  1680. Profiler.leave("verifyConnectorHierarchy - this is only performed in debug mode");
  1681. }
  1682. private void unregisterRemovedConnectors(
  1683. FastStringSet detachedConnectors) {
  1684. Profiler.enter("unregisterRemovedConnectors");
  1685. JsArrayString detachedArray = detachedConnectors.dump();
  1686. for (int i = 0; i < detachedArray.length(); i++) {
  1687. ServerConnector connector = connectorMap
  1688. .getConnector(detachedArray.get(i));
  1689. Profiler.enter("unregisterRemovedConnectors unregisterConnector");
  1690. connectorMap.unregisterConnector(connector);
  1691. Profiler.leave("unregisterRemovedConnectors unregisterConnector");
  1692. }
  1693. if (ApplicationConfiguration.isDebugMode()) {
  1694. // Do some extra checking if we're in debug mode (i.e. debug
  1695. // window is open)
  1696. verifyConnectorHierarchy();
  1697. }
  1698. VConsole.log("* Unregistered " + detachedArray.length()
  1699. + " connectors");
  1700. Profiler.leave("unregisterRemovedConnectors");
  1701. }
  1702. private JsArrayString createConnectorsIfNeeded(ValueMap json) {
  1703. VConsole.log(" * Creating connectors (if needed)");
  1704. JsArrayString createdConnectors = JavaScriptObject
  1705. .createArray().cast();
  1706. if (!json.containsKey("types")) {
  1707. return createdConnectors;
  1708. }
  1709. Profiler.enter("Creating connectors");
  1710. ValueMap types = json.getValueMap("types");
  1711. JsArrayString keyArray = types.getKeyArray();
  1712. for (int i = 0; i < keyArray.length(); i++) {
  1713. try {
  1714. String connectorId = keyArray.get(i);
  1715. ServerConnector connector = connectorMap
  1716. .getConnector(connectorId);
  1717. if (connector != null) {
  1718. continue;
  1719. }
  1720. int connectorType = Integer.parseInt(types
  1721. .getString(connectorId));
  1722. Class<? extends ServerConnector> connectorClass = configuration
  1723. .getConnectorClassByEncodedTag(connectorType);
  1724. // Connector does not exist so we must create it
  1725. if (connectorClass != uIConnector.getClass()) {
  1726. // create, initialize and register the paintable
  1727. Profiler.enter("ApplicationConnection.getConnector");
  1728. connector = getConnector(connectorId, connectorType);
  1729. Profiler.leave("ApplicationConnection.getConnector");
  1730. createdConnectors.push(connectorId);
  1731. } else {
  1732. // First UIConnector update. Before this the
  1733. // UIConnector has been created but not
  1734. // initialized as the connector id has not been
  1735. // known
  1736. connectorMap.registerConnector(connectorId,
  1737. uIConnector);
  1738. uIConnector.doInit(connectorId,
  1739. ApplicationConnection.this);
  1740. createdConnectors.push(connectorId);
  1741. }
  1742. } catch (final Throwable e) {
  1743. VConsole.error(e);
  1744. }
  1745. }
  1746. Profiler.leave("Creating connectors");
  1747. return createdConnectors;
  1748. }
  1749. private void updateVaadin6StyleConnectors(ValueMap json) {
  1750. Profiler.enter("updateVaadin6StyleConnectors");
  1751. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  1752. int length = changes.length();
  1753. VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
  1754. // update paintables
  1755. for (int i = 0; i < length; i++) {
  1756. try {
  1757. final UIDL change = changes.get(i).cast();
  1758. final UIDL uidl = change.getChildUIDL(0);
  1759. String connectorId = uidl.getId();
  1760. final ComponentConnector legacyConnector = (ComponentConnector) connectorMap
  1761. .getConnector(connectorId);
  1762. if (legacyConnector instanceof Paintable) {
  1763. String key = null;
  1764. if (Profiler.isEnabled()) {
  1765. key = "updateFromUIDL for "
  1766. + Util.getSimpleName(legacyConnector);
  1767. Profiler.enter(key);
  1768. }
  1769. ((Paintable) legacyConnector).updateFromUIDL(uidl,
  1770. ApplicationConnection.this);
  1771. if (Profiler.isEnabled()) {
  1772. Profiler.leave(key);
  1773. }
  1774. } else if (legacyConnector == null) {
  1775. VConsole.error("Received update for "
  1776. + uidl.getTag()
  1777. + ", but there is no such paintable ("
  1778. + connectorId + ") rendered.");
  1779. } else {
  1780. VConsole.error("Server sent Vaadin 6 style updates for "
  1781. + Util.getConnectorString(legacyConnector)
  1782. + " but this is not a Vaadin 6 Paintable");
  1783. }
  1784. } catch (final Throwable e) {
  1785. VConsole.error(e);
  1786. }
  1787. }
  1788. Profiler.leave("updateVaadin6StyleConnectors");
  1789. }
  1790. private void sendHierarchyChangeEvents(
  1791. JsArrayObject<ConnectorHierarchyChangeEvent> events) {
  1792. int eventCount = events.size();
  1793. if (eventCount == 0) {
  1794. return;
  1795. }
  1796. Profiler.enter("sendHierarchyChangeEvents");
  1797. VConsole.log(" * Sending hierarchy change events");
  1798. for (int i = 0; i < eventCount; i++) {
  1799. ConnectorHierarchyChangeEvent event = events.get(i);
  1800. try {
  1801. logHierarchyChange(event);
  1802. event.getConnector().fireEvent(event);
  1803. } catch (final Throwable e) {
  1804. VConsole.error(e);
  1805. }
  1806. }
  1807. Profiler.leave("sendHierarchyChangeEvents");
  1808. }
  1809. private void logHierarchyChange(ConnectorHierarchyChangeEvent event) {
  1810. if (true) {
  1811. // Always disabled for now. Can be enabled manually
  1812. return;
  1813. }
  1814. VConsole.log("Hierarchy changed for "
  1815. + Util.getConnectorString(event.getConnector()));
  1816. String oldChildren = "* Old children: ";
  1817. for (ComponentConnector child : event.getOldChildren()) {
  1818. oldChildren += Util.getConnectorString(child) + " ";
  1819. }
  1820. VConsole.log(oldChildren);
  1821. String newChildren = "* New children: ";
  1822. HasComponentsConnector parent = (HasComponentsConnector) event
  1823. .getConnector();
  1824. for (ComponentConnector child : parent.getChildComponents()) {
  1825. newChildren += Util.getConnectorString(child) + " ";
  1826. }
  1827. VConsole.log(newChildren);
  1828. }
  1829. private JsArrayObject<StateChangeEvent> updateConnectorState(
  1830. ValueMap json, JsArrayString createdConnectorIds) {
  1831. JsArrayObject<StateChangeEvent> events = JavaScriptObject
  1832. .createArray().cast();
  1833. VConsole.log(" * Updating connector states");
  1834. if (!json.containsKey("state")) {
  1835. return events;
  1836. }
  1837. Profiler.enter("updateConnectorState");
  1838. FastStringSet remainingNewConnectors = FastStringSet.create();
  1839. remainingNewConnectors.addAll(createdConnectorIds);
  1840. // set states for all paintables mentioned in "state"
  1841. ValueMap states = json.getValueMap("state");
  1842. JsArrayString keyArray = states.getKeyArray();
  1843. for (int i = 0; i < keyArray.length(); i++) {
  1844. try {
  1845. String connectorId = keyArray.get(i);
  1846. ServerConnector connector = connectorMap
  1847. .getConnector(connectorId);
  1848. if (null != connector) {
  1849. Profiler.enter("updateConnectorState inner loop");
  1850. if (Profiler.isEnabled()) {
  1851. Profiler.enter("Decode connector state "
  1852. + Util.getSimpleName(connector));
  1853. }
  1854. JSONObject stateJson = new JSONObject(
  1855. states.getJavaScriptObject(connectorId));
  1856. if (connector instanceof HasJavaScriptConnectorHelper) {
  1857. ((HasJavaScriptConnectorHelper) connector)
  1858. .getJavascriptConnectorHelper()
  1859. .setNativeState(
  1860. stateJson.getJavaScriptObject());
  1861. }
  1862. SharedState state = connector.getState();
  1863. Profiler.enter("updateConnectorState decodeValue");
  1864. JsonDecoder.decodeValue(new Type(state.getClass()
  1865. .getName(), null), stateJson, state,
  1866. ApplicationConnection.this);
  1867. Profiler.leave("updateConnectorState decodeValue");
  1868. if (Profiler.isEnabled()) {
  1869. Profiler.leave("Decode connector state "
  1870. + Util.getSimpleName(connector));
  1871. }
  1872. Profiler.enter("updateConnectorState create event");
  1873. boolean isNewConnector = remainingNewConnectors
  1874. .contains(connectorId);
  1875. if (isNewConnector) {
  1876. remainingNewConnectors.remove(connectorId);
  1877. }
  1878. StateChangeEvent event = new StateChangeEvent(
  1879. connector, stateJson, isNewConnector);
  1880. events.add(event);
  1881. Profiler.leave("updateConnectorState create event");
  1882. Profiler.leave("updateConnectorState inner loop");
  1883. }
  1884. } catch (final Throwable e) {
  1885. VConsole.error(e);
  1886. }
  1887. }
  1888. Profiler.enter("updateConnectorState newWithoutState");
  1889. // Fire events for properties using the default value for newly
  1890. // created connectors even if there were no state changes
  1891. JsArrayString dump = remainingNewConnectors.dump();
  1892. int length = dump.length();
  1893. for (int i = 0; i < length; i++) {
  1894. String connectorId = dump.get(i);
  1895. ServerConnector connector = connectorMap
  1896. .getConnector(connectorId);
  1897. StateChangeEvent event = new StateChangeEvent(connector,
  1898. new JSONObject(), true);
  1899. events.add(event);
  1900. }
  1901. Profiler.leave("updateConnectorState newWithoutState");
  1902. Profiler.leave("updateConnectorState");
  1903. return events;
  1904. }
  1905. /**
  1906. * Updates the connector hierarchy and returns a list of events that
  1907. * should be fired after update of the hierarchy and the state is
  1908. * done.
  1909. *
  1910. * @param json
  1911. * The JSON containing the hierarchy information
  1912. * @return A collection of events that should be fired when update
  1913. * of hierarchy and state is complete and a list of all
  1914. * connectors for which the parent has changed
  1915. */
  1916. private ConnectorHierarchyUpdateResult updateConnectorHierarchy(
  1917. ValueMap json) {
  1918. ConnectorHierarchyUpdateResult result = new ConnectorHierarchyUpdateResult();
  1919. VConsole.log(" * Updating connector hierarchy");
  1920. if (!json.containsKey("hierarchy")) {
  1921. return result;
  1922. }
  1923. Profiler.enter("updateConnectorHierarchy");
  1924. FastStringSet maybeDetached = FastStringSet.create();
  1925. ValueMap hierarchies = json.getValueMap("hierarchy");
  1926. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  1927. for (int i = 0; i < hierarchyKeys.length(); i++) {
  1928. try {
  1929. Profiler.enter("updateConnectorHierarchy hierarchy entry");
  1930. String connectorId = hierarchyKeys.get(i);
  1931. ServerConnector parentConnector = connectorMap
  1932. .getConnector(connectorId);
  1933. JsArrayString childConnectorIds = hierarchies
  1934. .getJSStringArray(connectorId);
  1935. int childConnectorSize = childConnectorIds.length();
  1936. Profiler.enter("updateConnectorHierarchy find new connectors");
  1937. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  1938. List<ComponentConnector> newComponents = new ArrayList<ComponentConnector>();
  1939. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  1940. String childConnectorId = childConnectorIds
  1941. .get(connectorIndex);
  1942. ServerConnector childConnector = connectorMap
  1943. .getConnector(childConnectorId);
  1944. if (childConnector == null) {
  1945. VConsole.error("Hierarchy claims that "
  1946. + childConnectorId
  1947. + " is a child for "
  1948. + connectorId
  1949. + " ("
  1950. + parentConnector.getClass().getName()
  1951. + ") but no connector with id "
  1952. + childConnectorId
  1953. + " has been registered. "
  1954. + "More information might be available in the server-side log if assertions are enabled");
  1955. continue;
  1956. }
  1957. newChildren.add(childConnector);
  1958. if (childConnector instanceof ComponentConnector) {
  1959. newComponents
  1960. .add((ComponentConnector) childConnector);
  1961. } else if (!(childConnector instanceof AbstractExtensionConnector)) {
  1962. throw new IllegalStateException(
  1963. Util.getConnectorString(childConnector)
  1964. + " is not a ComponentConnector nor an AbstractExtensionConnector");
  1965. }
  1966. if (childConnector.getParent() != parentConnector) {
  1967. childConnector.setParent(parentConnector);
  1968. result.parentChangedIds.add(childConnectorId);
  1969. // Not detached even if previously removed from
  1970. // parent
  1971. maybeDetached.remove(childConnectorId);
  1972. }
  1973. }
  1974. Profiler.leave("updateConnectorHierarchy find new connectors");
  1975. // TODO This check should be done on the server side in
  1976. // the future so the hierarchy update is only sent when
  1977. // something actually has changed
  1978. List<ServerConnector> oldChildren = parentConnector
  1979. .getChildren();
  1980. boolean actuallyChanged = !Util.collectionsEquals(
  1981. oldChildren, newChildren);
  1982. if (!actuallyChanged) {
  1983. continue;
  1984. }
  1985. Profiler.enter("updateConnectorHierarchy handle HasComponentsConnector");
  1986. if (parentConnector instanceof HasComponentsConnector) {
  1987. HasComponentsConnector ccc = (HasComponentsConnector) parentConnector;
  1988. List<ComponentConnector> oldComponents = ccc
  1989. .getChildComponents();
  1990. if (!Util.collectionsEquals(oldComponents,
  1991. newComponents)) {
  1992. // Fire change event if the hierarchy has
  1993. // changed
  1994. ConnectorHierarchyChangeEvent event = GWT
  1995. .create(ConnectorHierarchyChangeEvent.class);
  1996. event.setOldChildren(oldComponents);
  1997. event.setConnector(parentConnector);
  1998. ccc.setChildComponents(newComponents);
  1999. result.events.add(event);
  2000. }
  2001. } else if (!newComponents.isEmpty()) {
  2002. VConsole.error("Hierachy claims "
  2003. + Util.getConnectorString(parentConnector)
  2004. + " has component children even though it isn't a HasComponentsConnector");
  2005. }
  2006. Profiler.leave("updateConnectorHierarchy handle HasComponentsConnector");
  2007. Profiler.enter("updateConnectorHierarchy setChildren");
  2008. parentConnector.setChildren(newChildren);
  2009. Profiler.leave("updateConnectorHierarchy setChildren");
  2010. Profiler.enter("updateConnectorHierarchy find removed children");
  2011. /*
  2012. * Find children removed from this parent and mark for
  2013. * removal unless they are already attached to some
  2014. * other parent.
  2015. */
  2016. for (ServerConnector oldChild : oldChildren) {
  2017. if (oldChild.getParent() != parentConnector) {
  2018. // Ignore if moved to some other connector
  2019. continue;
  2020. }
  2021. if (!newChildren.contains(oldChild)) {
  2022. /*
  2023. * Consider child detached for now, will be
  2024. * cleared if it is later on added to some other
  2025. * parent.
  2026. */
  2027. maybeDetached.add(oldChild.getConnectorId());
  2028. }
  2029. }
  2030. Profiler.leave("updateConnectorHierarchy find removed children");
  2031. } catch (final Throwable e) {
  2032. VConsole.error(e);
  2033. } finally {
  2034. Profiler.leave("updateConnectorHierarchy hierarchy entry");
  2035. }
  2036. }
  2037. Profiler.enter("updateConnectorHierarchy detach removed connectors");
  2038. /*
  2039. * Connector is in maybeDetached at this point if it has been
  2040. * removed from its parent but not added to any other parent
  2041. */
  2042. JsArrayString maybeDetachedArray = maybeDetached.dump();
  2043. for (int i = 0; i < maybeDetachedArray.length(); i++) {
  2044. ServerConnector removed = connectorMap
  2045. .getConnector(maybeDetachedArray.get(i));
  2046. recursivelyDetach(removed, result.events,
  2047. result.detachedConnectorIds);
  2048. }
  2049. Profiler.leave("updateConnectorHierarchy detach removed connectors");
  2050. Profiler.leave("updateConnectorHierarchy");
  2051. return result;
  2052. }
  2053. private void recursivelyDetach(ServerConnector connector,
  2054. JsArrayObject<ConnectorHierarchyChangeEvent> events,
  2055. FastStringSet detachedConnectors) {
  2056. detachedConnectors.add(connector.getConnectorId());
  2057. /*
  2058. * Reset state in an attempt to keep it consistent with the
  2059. * hierarchy. No children and no parent is the initial situation
  2060. * for the hierarchy, so changing the state to its initial value
  2061. * is the closest we can get without data from the server.
  2062. * #10151
  2063. */
  2064. Profiler.enter("ApplicationConnection recursivelyDetach reset state");
  2065. try {
  2066. Profiler.enter("ApplicationConnection recursivelyDetach reset state - getStateType");
  2067. Type stateType = AbstractConnector.getStateType(connector);
  2068. Profiler.leave("ApplicationConnection recursivelyDetach reset state - getStateType");
  2069. // Empty state instance to get default property values from
  2070. Profiler.enter("ApplicationConnection recursivelyDetach reset state - createInstance");
  2071. Object defaultState = stateType.createInstance();
  2072. Profiler.leave("ApplicationConnection recursivelyDetach reset state - createInstance");
  2073. if (connector instanceof AbstractConnector) {
  2074. // optimization as the loop setting properties is very
  2075. // slow, especially on IE8
  2076. replaceState((AbstractConnector) connector,
  2077. defaultState);
  2078. } else {
  2079. SharedState state = connector.getState();
  2080. Profiler.enter("ApplicationConnection recursivelyDetach reset state - properties");
  2081. JsArrayObject<Property> properties = stateType
  2082. .getPropertiesAsArray();
  2083. int size = properties.size();
  2084. for (int i = 0; i < size; i++) {
  2085. Property property = properties.get(i);
  2086. property.setValue(state,
  2087. property.getValue(defaultState));
  2088. }
  2089. Profiler.leave("ApplicationConnection recursivelyDetach reset state - properties");
  2090. }
  2091. } catch (NoDataException e) {
  2092. throw new RuntimeException("Can't reset state for "
  2093. + Util.getConnectorString(connector), e);
  2094. } finally {
  2095. Profiler.leave("ApplicationConnection recursivelyDetach reset state");
  2096. }
  2097. Profiler.enter("ApplicationConnection recursivelyDetach perform detach");
  2098. /*
  2099. * Recursively detach children to make sure they get
  2100. * setParent(null) and hierarchy change events as needed.
  2101. */
  2102. for (ServerConnector child : connector.getChildren()) {
  2103. /*
  2104. * Server doesn't send updated child data for removed
  2105. * connectors -> ignore child that still seems to be a child
  2106. * of this connector although it has been moved to some part
  2107. * of the hierarchy that is not detached.
  2108. */
  2109. if (child.getParent() != connector) {
  2110. continue;
  2111. }
  2112. recursivelyDetach(child, events, detachedConnectors);
  2113. }
  2114. Profiler.leave("ApplicationConnection recursivelyDetach perform detach");
  2115. /*
  2116. * Clear child list and parent
  2117. */
  2118. Profiler.enter("ApplicationConnection recursivelyDetach clear children and parent");
  2119. connector
  2120. .setChildren(Collections.<ServerConnector> emptyList());
  2121. connector.setParent(null);
  2122. Profiler.leave("ApplicationConnection recursivelyDetach clear children and parent");
  2123. /*
  2124. * Create an artificial hierarchy event for containers to give
  2125. * it a chance to clean up after its children if it has any
  2126. */
  2127. Profiler.enter("ApplicationConnection recursivelyDetach create hierarchy event");
  2128. if (connector instanceof HasComponentsConnector) {
  2129. HasComponentsConnector ccc = (HasComponentsConnector) connector;
  2130. List<ComponentConnector> oldChildren = ccc
  2131. .getChildComponents();
  2132. if (!oldChildren.isEmpty()) {
  2133. /*
  2134. * HasComponentsConnector has a separate child component
  2135. * list that should also be cleared
  2136. */
  2137. ccc.setChildComponents(Collections
  2138. .<ComponentConnector> emptyList());
  2139. // Create event and add it to the list of pending events
  2140. ConnectorHierarchyChangeEvent event = GWT
  2141. .create(ConnectorHierarchyChangeEvent.class);
  2142. event.setConnector(connector);
  2143. event.setOldChildren(oldChildren);
  2144. events.add(event);
  2145. }
  2146. }
  2147. Profiler.leave("ApplicationConnection recursivelyDetach create hierarchy event");
  2148. }
  2149. private native void replaceState(AbstractConnector connector,
  2150. Object defaultState)
  2151. /*-{
  2152. connector.@com.vaadin.client.ui.AbstractConnector::state = defaultState;
  2153. }-*/;
  2154. private void handleRpcInvocations(ValueMap json) {
  2155. if (json.containsKey("rpc")) {
  2156. Profiler.enter("handleRpcInvocations");
  2157. VConsole.log(" * Performing server to client RPC calls");
  2158. JSONArray rpcCalls = new JSONArray(
  2159. json.getJavaScriptObject("rpc"));
  2160. int rpcLength = rpcCalls.size();
  2161. for (int i = 0; i < rpcLength; i++) {
  2162. try {
  2163. JSONArray rpcCall = (JSONArray) rpcCalls.get(i);
  2164. rpcManager.parseAndApplyInvocation(rpcCall,
  2165. ApplicationConnection.this);
  2166. } catch (final Throwable e) {
  2167. VConsole.error(e);
  2168. }
  2169. }
  2170. Profiler.leave("handleRpcInvocations");
  2171. }
  2172. }
  2173. };
  2174. ApplicationConfiguration.runWhenDependenciesLoaded(c);
  2175. }
  2176. private void loadStyleDependencies(JsArrayString dependencies) {
  2177. // Assuming no reason to interpret in a defined order
  2178. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  2179. @Override
  2180. public void onLoad(ResourceLoadEvent event) {
  2181. ApplicationConfiguration.endDependencyLoading();
  2182. }
  2183. @Override
  2184. public void onError(ResourceLoadEvent event) {
  2185. VConsole.error(event.getResourceUrl()
  2186. + " could not be loaded, or the load detection failed because the stylesheet is empty.");
  2187. // The show must go on
  2188. onLoad(event);
  2189. }
  2190. };
  2191. ResourceLoader loader = ResourceLoader.get();
  2192. for (int i = 0; i < dependencies.length(); i++) {
  2193. String url = translateVaadinUri(dependencies.get(i));
  2194. ApplicationConfiguration.startDependencyLoading();
  2195. loader.loadStylesheet(url, resourceLoadListener);
  2196. }
  2197. }
  2198. private void loadScriptDependencies(final JsArrayString dependencies) {
  2199. if (dependencies.length() == 0) {
  2200. return;
  2201. }
  2202. // Listener that loads the next when one is completed
  2203. ResourceLoadListener resourceLoadListener = new ResourceLoadListener() {
  2204. @Override
  2205. public void onLoad(ResourceLoadEvent event) {
  2206. if (dependencies.length() != 0) {
  2207. String url = translateVaadinUri(dependencies.shift());
  2208. ApplicationConfiguration.startDependencyLoading();
  2209. // Load next in chain (hopefully already preloaded)
  2210. event.getResourceLoader().loadScript(url, this);
  2211. }
  2212. // Call start for next before calling end for current
  2213. ApplicationConfiguration.endDependencyLoading();
  2214. }
  2215. @Override
  2216. public void onError(ResourceLoadEvent event) {
  2217. VConsole.error(event.getResourceUrl() + " could not be loaded.");
  2218. // The show must go on
  2219. onLoad(event);
  2220. }
  2221. };
  2222. ResourceLoader loader = ResourceLoader.get();
  2223. // Start chain by loading first
  2224. String url = translateVaadinUri(dependencies.shift());
  2225. ApplicationConfiguration.startDependencyLoading();
  2226. loader.loadScript(url, resourceLoadListener);
  2227. if (ResourceLoader.supportsInOrderScriptExecution()) {
  2228. for (int i = 0; i < dependencies.length(); i++) {
  2229. String preloadUrl = translateVaadinUri(dependencies.get(i));
  2230. loader.loadScript(preloadUrl, null);
  2231. }
  2232. } else {
  2233. // Preload all remaining
  2234. for (int i = 0; i < dependencies.length(); i++) {
  2235. String preloadUrl = translateVaadinUri(dependencies.get(i));
  2236. loader.preloadResource(preloadUrl, null);
  2237. }
  2238. }
  2239. }
  2240. // Redirect browser, null reloads current page
  2241. private static native void redirect(String url)
  2242. /*-{
  2243. if (url) {
  2244. $wnd.location = url;
  2245. } else {
  2246. $wnd.location.reload(false);
  2247. }
  2248. }-*/;
  2249. private void addVariableToQueue(String connectorId, String variableName,
  2250. Object value, boolean immediate) {
  2251. boolean lastOnly = !immediate;
  2252. // note that type is now deduced from value
  2253. addMethodInvocationToQueue(new LegacyChangeVariablesInvocation(
  2254. connectorId, variableName, value), lastOnly, lastOnly);
  2255. }
  2256. /**
  2257. * Adds an explicit RPC method invocation to the send queue.
  2258. *
  2259. * @since 7.0
  2260. *
  2261. * @param invocation
  2262. * RPC method invocation
  2263. * @param delayed
  2264. * <code>false</code> to trigger sending within a short time
  2265. * window (possibly combining subsequent calls to a single
  2266. * request), <code>true</code> to let the framework delay sending
  2267. * of RPC calls and variable changes until the next non-delayed
  2268. * change
  2269. * @param lastOnly
  2270. * <code>true</code> to remove all previously delayed invocations
  2271. * of the same method that were also enqueued with lastonly set
  2272. * to <code>true</code>. <code>false</code> to add invocation to
  2273. * the end of the queue without touching previously enqueued
  2274. * invocations.
  2275. */
  2276. public void addMethodInvocationToQueue(MethodInvocation invocation,
  2277. boolean delayed, boolean lastOnly) {
  2278. if (!isApplicationRunning()) {
  2279. getLogger()
  2280. .warning(
  2281. "Trying to invoke method on not yet started or stopped application");
  2282. return;
  2283. }
  2284. String tag;
  2285. if (lastOnly) {
  2286. tag = invocation.getLastOnlyTag();
  2287. assert !tag.matches("\\d+") : "getLastOnlyTag value must have at least one non-digit character";
  2288. pendingInvocations.remove(tag);
  2289. } else {
  2290. tag = Integer.toString(lastInvocationTag++);
  2291. }
  2292. pendingInvocations.put(tag, invocation);
  2293. if (!delayed) {
  2294. sendPendingVariableChanges();
  2295. }
  2296. }
  2297. /**
  2298. * Removes any pending invocation of the given method from the queue
  2299. *
  2300. * @param invocation
  2301. * The invocation to remove
  2302. */
  2303. public void removePendingInvocations(MethodInvocation invocation) {
  2304. Iterator<MethodInvocation> iter = pendingInvocations.values()
  2305. .iterator();
  2306. while (iter.hasNext()) {
  2307. MethodInvocation mi = iter.next();
  2308. if (mi.equals(invocation)) {
  2309. iter.remove();
  2310. }
  2311. }
  2312. }
  2313. /**
  2314. * This method sends currently queued variable changes to server. It is
  2315. * called when immediate variable update must happen.
  2316. *
  2317. * To ensure correct order for variable changes (due servers multithreading
  2318. * or network), we always wait for active request to be handler before
  2319. * sending a new one. If there is an active request, we will put varible
  2320. * "burst" to queue that will be purged after current request is handled.
  2321. *
  2322. */
  2323. public void sendPendingVariableChanges() {
  2324. if (!deferedSendPending) {
  2325. deferedSendPending = true;
  2326. Scheduler.get().scheduleFinally(sendPendingCommand);
  2327. }
  2328. }
  2329. private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
  2330. @Override
  2331. public void execute() {
  2332. deferedSendPending = false;
  2333. doSendPendingVariableChanges();
  2334. }
  2335. };
  2336. private boolean deferedSendPending = false;
  2337. private void doSendPendingVariableChanges() {
  2338. if (isApplicationRunning()) {
  2339. if (hasActiveRequest() || (push != null && !push.isActive())) {
  2340. // skip empty queues if there are pending bursts to be sent
  2341. if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
  2342. pendingBursts.add(pendingInvocations);
  2343. pendingInvocations = new LinkedHashMap<String, MethodInvocation>();
  2344. // Keep tag string short
  2345. lastInvocationTag = 0;
  2346. }
  2347. } else {
  2348. buildAndSendVariableBurst(pendingInvocations);
  2349. }
  2350. } else {
  2351. getLogger()
  2352. .warning(
  2353. "Trying to send variable changes from not yet started or stopped application");
  2354. return;
  2355. }
  2356. }
  2357. /**
  2358. * Build the variable burst and send it to server.
  2359. *
  2360. * When sync is forced, we also force sending of all pending variable-bursts
  2361. * at the same time. This is ok as we can assume that DOM will never be
  2362. * updated after this.
  2363. *
  2364. * @param pendingInvocations
  2365. * List of RPC method invocations to send
  2366. */
  2367. private void buildAndSendVariableBurst(
  2368. LinkedHashMap<String, MethodInvocation> pendingInvocations) {
  2369. JSONArray reqJson = new JSONArray();
  2370. if (!pendingInvocations.isEmpty()) {
  2371. if (ApplicationConfiguration.isDebugMode()) {
  2372. Util.logVariableBurst(this, pendingInvocations.values());
  2373. }
  2374. for (MethodInvocation invocation : pendingInvocations.values()) {
  2375. JSONArray invocationJson = new JSONArray();
  2376. invocationJson.set(0,
  2377. new JSONString(invocation.getConnectorId()));
  2378. invocationJson.set(1,
  2379. new JSONString(invocation.getInterfaceName()));
  2380. invocationJson.set(2,
  2381. new JSONString(invocation.getMethodName()));
  2382. JSONArray paramJson = new JSONArray();
  2383. Type[] parameterTypes = null;
  2384. if (!isLegacyVariableChange(invocation)
  2385. && !isJavascriptRpc(invocation)) {
  2386. try {
  2387. Type type = new Type(invocation.getInterfaceName(),
  2388. null);
  2389. Method method = type.getMethod(invocation
  2390. .getMethodName());
  2391. parameterTypes = method.getParameterTypes();
  2392. } catch (NoDataException e) {
  2393. throw new RuntimeException("No type data for "
  2394. + invocation.toString(), e);
  2395. }
  2396. }
  2397. for (int i = 0; i < invocation.getParameters().length; ++i) {
  2398. // TODO non-static encoder?
  2399. Type type = null;
  2400. if (parameterTypes != null) {
  2401. type = parameterTypes[i];
  2402. }
  2403. Object value = invocation.getParameters()[i];
  2404. paramJson.set(i, JsonEncoder.encode(value, type, this));
  2405. }
  2406. invocationJson.set(3, paramJson);
  2407. reqJson.set(reqJson.size(), invocationJson);
  2408. }
  2409. pendingInvocations.clear();
  2410. // Keep tag string short
  2411. lastInvocationTag = 0;
  2412. }
  2413. String extraParams = "";
  2414. if (!getConfiguration().isWidgetsetVersionSent()) {
  2415. if (!extraParams.isEmpty()) {
  2416. extraParams += "&";
  2417. }
  2418. String widgetsetVersion = Version.getFullVersion();
  2419. extraParams += "v-wsver=" + widgetsetVersion;
  2420. getConfiguration().setWidgetsetVersionSent();
  2421. }
  2422. makeUidlRequest(reqJson, extraParams);
  2423. }
  2424. private boolean isJavascriptRpc(MethodInvocation invocation) {
  2425. return invocation instanceof JavaScriptMethodInvocation;
  2426. }
  2427. private boolean isLegacyVariableChange(MethodInvocation invocation) {
  2428. return ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
  2429. .getInterfaceName())
  2430. && ApplicationConstants.UPDATE_VARIABLE_METHOD
  2431. .equals(invocation.getMethodName());
  2432. }
  2433. /**
  2434. * Sends a new value for the given paintables given variable to the server.
  2435. * <p>
  2436. * The update is actually queued to be sent at a suitable time. If immediate
  2437. * is true, the update is sent as soon as possible. If immediate is false,
  2438. * the update will be sent along with the next immediate update.
  2439. * </p>
  2440. *
  2441. * @param paintableId
  2442. * the id of the paintable that owns the variable
  2443. * @param variableName
  2444. * the name of the variable
  2445. * @param newValue
  2446. * the new value to be sent
  2447. * @param immediate
  2448. * true if the update is to be sent as soon as possible
  2449. */
  2450. public void updateVariable(String paintableId, String variableName,
  2451. ServerConnector newValue, boolean immediate) {
  2452. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2453. }
  2454. /**
  2455. * Sends a new value for the given paintables given variable to the server.
  2456. * <p>
  2457. * The update is actually queued to be sent at a suitable time. If immediate
  2458. * is true, the update is sent as soon as possible. If immediate is false,
  2459. * the update will be sent along with the next immediate update.
  2460. * </p>
  2461. *
  2462. * @param paintableId
  2463. * the id of the paintable that owns the variable
  2464. * @param variableName
  2465. * the name of the variable
  2466. * @param newValue
  2467. * the new value to be sent
  2468. * @param immediate
  2469. * true if the update is to be sent as soon as possible
  2470. */
  2471. public void updateVariable(String paintableId, String variableName,
  2472. String newValue, boolean immediate) {
  2473. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2474. }
  2475. /**
  2476. * Sends a new value for the given paintables given variable to the server.
  2477. * <p>
  2478. * The update is actually queued to be sent at a suitable time. If immediate
  2479. * is true, the update is sent as soon as possible. If immediate is false,
  2480. * the update will be sent along with the next immediate update.
  2481. * </p>
  2482. *
  2483. * @param paintableId
  2484. * the id of the paintable that owns the variable
  2485. * @param variableName
  2486. * the name of the variable
  2487. * @param newValue
  2488. * the new value to be sent
  2489. * @param immediate
  2490. * true if the update is to be sent as soon as possible
  2491. */
  2492. public void updateVariable(String paintableId, String variableName,
  2493. int newValue, boolean immediate) {
  2494. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2495. }
  2496. /**
  2497. * Sends a new value for the given paintables given variable to the server.
  2498. * <p>
  2499. * The update is actually queued to be sent at a suitable time. If immediate
  2500. * is true, the update is sent as soon as possible. If immediate is false,
  2501. * the update will be sent along with the next immediate update.
  2502. * </p>
  2503. *
  2504. * @param paintableId
  2505. * the id of the paintable that owns the variable
  2506. * @param variableName
  2507. * the name of the variable
  2508. * @param newValue
  2509. * the new value to be sent
  2510. * @param immediate
  2511. * true if the update is to be sent as soon as possible
  2512. */
  2513. public void updateVariable(String paintableId, String variableName,
  2514. long newValue, boolean immediate) {
  2515. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2516. }
  2517. /**
  2518. * Sends a new value for the given paintables given variable to the server.
  2519. * <p>
  2520. * The update is actually queued to be sent at a suitable time. If immediate
  2521. * is true, the update is sent as soon as possible. If immediate is false,
  2522. * the update will be sent along with the next immediate update.
  2523. * </p>
  2524. *
  2525. * @param paintableId
  2526. * the id of the paintable that owns the variable
  2527. * @param variableName
  2528. * the name of the variable
  2529. * @param newValue
  2530. * the new value to be sent
  2531. * @param immediate
  2532. * true if the update is to be sent as soon as possible
  2533. */
  2534. public void updateVariable(String paintableId, String variableName,
  2535. float newValue, boolean immediate) {
  2536. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2537. }
  2538. /**
  2539. * Sends a new value for the given paintables given variable to the server.
  2540. * <p>
  2541. * The update is actually queued to be sent at a suitable time. If immediate
  2542. * is true, the update is sent as soon as possible. If immediate is false,
  2543. * the update will be sent along with the next immediate update.
  2544. * </p>
  2545. *
  2546. * @param paintableId
  2547. * the id of the paintable that owns the variable
  2548. * @param variableName
  2549. * the name of the variable
  2550. * @param newValue
  2551. * the new value to be sent
  2552. * @param immediate
  2553. * true if the update is to be sent as soon as possible
  2554. */
  2555. public void updateVariable(String paintableId, String variableName,
  2556. double newValue, boolean immediate) {
  2557. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2558. }
  2559. /**
  2560. * Sends a new value for the given paintables given variable to the server.
  2561. * <p>
  2562. * The update is actually queued to be sent at a suitable time. If immediate
  2563. * is true, the update is sent as soon as possible. If immediate is false,
  2564. * the update will be sent along with the next immediate update.
  2565. * </p>
  2566. *
  2567. * @param paintableId
  2568. * the id of the paintable that owns the variable
  2569. * @param variableName
  2570. * the name of the variable
  2571. * @param newValue
  2572. * the new value to be sent
  2573. * @param immediate
  2574. * true if the update is to be sent as soon as possible
  2575. */
  2576. public void updateVariable(String paintableId, String variableName,
  2577. boolean newValue, boolean immediate) {
  2578. addVariableToQueue(paintableId, variableName, newValue, immediate);
  2579. }
  2580. /**
  2581. * Sends a new value for the given paintables given variable to the server.
  2582. * <p>
  2583. * The update is actually queued to be sent at a suitable time. If immediate
  2584. * is true, the update is sent as soon as possible. If immediate is false,
  2585. * the update will be sent along with the next immediate update.
  2586. * </p>
  2587. *
  2588. * @param paintableId
  2589. * the id of the paintable that owns the variable
  2590. * @param variableName
  2591. * the name of the variable
  2592. * @param map
  2593. * the new values to be sent
  2594. * @param immediate
  2595. * true if the update is to be sent as soon as possible
  2596. */
  2597. public void updateVariable(String paintableId, String variableName,
  2598. Map<String, Object> map, boolean immediate) {
  2599. addVariableToQueue(paintableId, variableName, map, immediate);
  2600. }
  2601. /**
  2602. * Sends a new value for the given paintables given variable to the server.
  2603. *
  2604. * The update is actually queued to be sent at a suitable time. If immediate
  2605. * is true, the update is sent as soon as possible. If immediate is false,
  2606. * the update will be sent along with the next immediate update.
  2607. *
  2608. * A null array is sent as an empty array.
  2609. *
  2610. * @param paintableId
  2611. * the id of the paintable that owns the variable
  2612. * @param variableName
  2613. * the name of the variable
  2614. * @param values
  2615. * the new value to be sent
  2616. * @param immediate
  2617. * true if the update is to be sent as soon as possible
  2618. */
  2619. public void updateVariable(String paintableId, String variableName,
  2620. String[] values, boolean immediate) {
  2621. addVariableToQueue(paintableId, variableName, values, immediate);
  2622. }
  2623. /**
  2624. * Sends a new value for the given paintables given variable to the server.
  2625. *
  2626. * The update is actually queued to be sent at a suitable time. If immediate
  2627. * is true, the update is sent as soon as possible. If immediate is false,
  2628. * the update will be sent along with the next immediate update. </p>
  2629. *
  2630. * A null array is sent as an empty array.
  2631. *
  2632. *
  2633. * @param paintableId
  2634. * the id of the paintable that owns the variable
  2635. * @param variableName
  2636. * the name of the variable
  2637. * @param values
  2638. * the new value to be sent
  2639. * @param immediate
  2640. * true if the update is to be sent as soon as possible
  2641. */
  2642. public void updateVariable(String paintableId, String variableName,
  2643. Object[] values, boolean immediate) {
  2644. addVariableToQueue(paintableId, variableName, values, immediate);
  2645. }
  2646. /**
  2647. * Does absolutely nothing. Replaced by {@link LayoutManager}.
  2648. *
  2649. * @param container
  2650. * @deprecated As of 7.0, serves no purpose
  2651. */
  2652. @Deprecated
  2653. public void runDescendentsLayout(HasWidgets container) {
  2654. }
  2655. /**
  2656. * This will cause re-layouting of all components. Mainly used for
  2657. * development. Published to JavaScript.
  2658. */
  2659. public void forceLayout() {
  2660. Duration duration = new Duration();
  2661. layoutManager.forceLayout();
  2662. VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
  2663. }
  2664. /**
  2665. * Returns false
  2666. *
  2667. * @param paintable
  2668. * @return false, always
  2669. * @deprecated As of 7.0, serves no purpose
  2670. */
  2671. @Deprecated
  2672. private boolean handleComponentRelativeSize(ComponentConnector paintable) {
  2673. return false;
  2674. }
  2675. /**
  2676. * Returns false
  2677. *
  2678. * @param paintable
  2679. * @return false, always
  2680. * @deprecated As of 7.0, serves no purpose
  2681. */
  2682. @Deprecated
  2683. public boolean handleComponentRelativeSize(Widget widget) {
  2684. return handleComponentRelativeSize(connectorMap.getConnector(widget));
  2685. }
  2686. @Deprecated
  2687. public ComponentConnector getPaintable(UIDL uidl) {
  2688. // Non-component connectors shouldn't be painted from legacy connectors
  2689. return (ComponentConnector) getConnector(uidl.getId(),
  2690. Integer.parseInt(uidl.getTag()));
  2691. }
  2692. /**
  2693. * Get either an existing ComponentConnector or create a new
  2694. * ComponentConnector with the given type and id.
  2695. *
  2696. * If a ComponentConnector with the given id already exists, returns it.
  2697. * Otherwise creates and registers a new ComponentConnector of the given
  2698. * type.
  2699. *
  2700. * @param connectorId
  2701. * Id of the paintable
  2702. * @param connectorType
  2703. * Type of the connector, as passed from the server side
  2704. *
  2705. * @return Either an existing ComponentConnector or a new ComponentConnector
  2706. * of the given type
  2707. */
  2708. public ServerConnector getConnector(String connectorId, int connectorType) {
  2709. if (!connectorMap.hasConnector(connectorId)) {
  2710. return createAndRegisterConnector(connectorId, connectorType);
  2711. }
  2712. return connectorMap.getConnector(connectorId);
  2713. }
  2714. /**
  2715. * Creates a new ServerConnector with the given type and id.
  2716. *
  2717. * Creates and registers a new ServerConnector of the given type. Should
  2718. * never be called with the connector id of an existing connector.
  2719. *
  2720. * @param connectorId
  2721. * Id of the new connector
  2722. * @param connectorType
  2723. * Type of the connector, as passed from the server side
  2724. *
  2725. * @return A new ServerConnector of the given type
  2726. */
  2727. private ServerConnector createAndRegisterConnector(String connectorId,
  2728. int connectorType) {
  2729. Profiler.enter("ApplicationConnection.createAndRegisterConnector");
  2730. // Create and register a new connector with the given type
  2731. ServerConnector p = widgetSet.createConnector(connectorType,
  2732. configuration);
  2733. connectorMap.registerConnector(connectorId, p);
  2734. p.doInit(connectorId, this);
  2735. Profiler.leave("ApplicationConnection.createAndRegisterConnector");
  2736. return p;
  2737. }
  2738. /**
  2739. * Gets a recource that has been pre-loaded via UIDL, such as custom
  2740. * layouts.
  2741. *
  2742. * @param name
  2743. * identifier of the resource to get
  2744. * @return the resource
  2745. */
  2746. public String getResource(String name) {
  2747. return resourcesMap.get(name);
  2748. }
  2749. /**
  2750. * Singleton method to get instance of app's context menu.
  2751. *
  2752. * @return VContextMenu object
  2753. */
  2754. public VContextMenu getContextMenu() {
  2755. if (contextMenu == null) {
  2756. contextMenu = new VContextMenu();
  2757. contextMenu.setOwner(uIConnector.getWidget());
  2758. DOM.setElementProperty(contextMenu.getElement(), "id",
  2759. "PID_VAADIN_CM");
  2760. }
  2761. return contextMenu;
  2762. }
  2763. /**
  2764. * Gets an {@link Icon} instance corresponding to a URI.
  2765. *
  2766. * @since 7.2
  2767. * @param uri
  2768. * @return Icon object
  2769. */
  2770. public Icon getIcon(String uri) {
  2771. Icon icon;
  2772. if (uri == null) {
  2773. return null;
  2774. } else if (FontIcon.isFontIconUri(uri)) {
  2775. icon = GWT.create(FontIcon.class);
  2776. } else {
  2777. icon = GWT.create(ImageIcon.class);
  2778. }
  2779. icon.setUri(translateVaadinUri(uri));
  2780. return icon;
  2781. }
  2782. /**
  2783. * Translates custom protocols in UIDL URI's to be recognizable by browser.
  2784. * All uri's from UIDL should be routed via this method before giving them
  2785. * to browser due URI's in UIDL may contain custom protocols like theme://.
  2786. *
  2787. * @param uidlUri
  2788. * Vaadin URI from uidl
  2789. * @return translated URI ready for browser
  2790. */
  2791. public String translateVaadinUri(String uidlUri) {
  2792. if (uidlUri == null) {
  2793. return null;
  2794. }
  2795. if (uidlUri.startsWith("theme://")) {
  2796. final String themeUri = getThemeUri();
  2797. if (themeUri == null) {
  2798. VConsole.error("Theme not set: ThemeResource will not be found. ("
  2799. + uidlUri + ")");
  2800. }
  2801. uidlUri = themeUri + uidlUri.substring(7);
  2802. }
  2803. if (uidlUri.startsWith(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX)) {
  2804. // getAppUri *should* always end with /
  2805. // substring *should* always start with / (published:///foo.bar
  2806. // without published://)
  2807. uidlUri = ApplicationConstants.APP_PROTOCOL_PREFIX
  2808. + ApplicationConstants.PUBLISHED_FILE_PATH
  2809. + uidlUri
  2810. .substring(ApplicationConstants.PUBLISHED_PROTOCOL_PREFIX
  2811. .length());
  2812. // Let translation of app:// urls take care of the rest
  2813. }
  2814. if (uidlUri.startsWith(ApplicationConstants.APP_PROTOCOL_PREFIX)) {
  2815. String relativeUrl = uidlUri
  2816. .substring(ApplicationConstants.APP_PROTOCOL_PREFIX
  2817. .length());
  2818. ApplicationConfiguration conf = getConfiguration();
  2819. String serviceUrl = conf.getServiceUrl();
  2820. if (conf.useServiceUrlPathParam()) {
  2821. // Should put path in v-resourcePath parameter and append query
  2822. // params to base portlet url
  2823. String[] parts = relativeUrl.split("\\?", 2);
  2824. String path = parts[0];
  2825. // If there's a "?" followed by something, append it as a query
  2826. // string to the base URL
  2827. if (parts.length > 1) {
  2828. String appUrlParams = parts[1];
  2829. serviceUrl = addGetParameters(serviceUrl, appUrlParams);
  2830. }
  2831. if (!path.startsWith("/")) {
  2832. path = '/' + path;
  2833. }
  2834. String pathParam = conf.getServiceUrlParameterName() + "="
  2835. + URL.encodeQueryString(path);
  2836. serviceUrl = addGetParameters(serviceUrl, pathParam);
  2837. uidlUri = serviceUrl;
  2838. } else {
  2839. uidlUri = serviceUrl + relativeUrl;
  2840. }
  2841. }
  2842. if (uidlUri.startsWith(ApplicationConstants.VAADIN_PROTOCOL_PREFIX)) {
  2843. final String vaadinUri = configuration.getVaadinDirUrl();
  2844. String relativeUrl = uidlUri
  2845. .substring(ApplicationConstants.VAADIN_PROTOCOL_PREFIX
  2846. .length());
  2847. uidlUri = vaadinUri + relativeUrl;
  2848. }
  2849. return uidlUri;
  2850. }
  2851. /**
  2852. * Gets the URI for the current theme. Can be used to reference theme
  2853. * resources.
  2854. *
  2855. * @return URI to the current theme
  2856. */
  2857. public String getThemeUri() {
  2858. return configuration.getVaadinDirUrl() + "themes/"
  2859. + getUIConnector().getActiveTheme();
  2860. }
  2861. /**
  2862. * Listens for Notification hide event, and redirects. Used for system
  2863. * messages, such as session expired.
  2864. *
  2865. */
  2866. private class NotificationRedirect implements VNotification.EventListener {
  2867. String url;
  2868. NotificationRedirect(String url) {
  2869. this.url = url;
  2870. }
  2871. @Override
  2872. public void notificationHidden(HideEvent event) {
  2873. redirect(url);
  2874. }
  2875. }
  2876. /* Extended title handling */
  2877. private final VTooltip tooltip;
  2878. private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
  2879. protected String getUidlSecurityKey() {
  2880. return getCsrfToken();
  2881. }
  2882. /**
  2883. * Gets the token (aka double submit cookie) that the server uses to protect
  2884. * against Cross Site Request Forgery attacks.
  2885. *
  2886. * @return the CSRF token string
  2887. */
  2888. public String getCsrfToken() {
  2889. return csrfToken;
  2890. }
  2891. /**
  2892. * Use to notify that the given component's caption has changed; layouts may
  2893. * have to be recalculated.
  2894. *
  2895. * @param component
  2896. * the Paintable whose caption has changed
  2897. * @deprecated As of 7.0.2, has not had any effect for a long time
  2898. */
  2899. @Deprecated
  2900. public void captionSizeUpdated(Widget widget) {
  2901. // This doesn't do anything, it's just kept here for compatibility
  2902. }
  2903. /**
  2904. * Gets the main view
  2905. *
  2906. * @return the main view
  2907. */
  2908. public UIConnector getUIConnector() {
  2909. return uIConnector;
  2910. }
  2911. /**
  2912. * Gets the {@link ApplicationConfiguration} for the current application.
  2913. *
  2914. * @see ApplicationConfiguration
  2915. * @return the configuration for this application
  2916. */
  2917. public ApplicationConfiguration getConfiguration() {
  2918. return configuration;
  2919. }
  2920. /**
  2921. * Checks if there is a registered server side listener for the event. The
  2922. * list of events which has server side listeners is updated automatically
  2923. * before the component is updated so the value is correct if called from
  2924. * updatedFromUIDL.
  2925. *
  2926. * @param paintable
  2927. * The connector to register event listeners for
  2928. * @param eventIdentifier
  2929. * The identifier for the event
  2930. * @return true if at least one listener has been registered on server side
  2931. * for the event identified by eventIdentifier.
  2932. * @deprecated As of 7.0. Use
  2933. * {@link AbstractComponentState#hasEventListener(String)}
  2934. * instead
  2935. */
  2936. @Deprecated
  2937. public boolean hasEventListeners(ComponentConnector paintable,
  2938. String eventIdentifier) {
  2939. return paintable.hasEventListener(eventIdentifier);
  2940. }
  2941. /**
  2942. * Adds the get parameters to the uri and returns the new uri that contains
  2943. * the parameters.
  2944. *
  2945. * @param uri
  2946. * The uri to which the parameters should be added.
  2947. * @param extraParams
  2948. * One or more parameters in the format "a=b" or "c=d&e=f". An
  2949. * empty string is allowed but will not modify the url.
  2950. * @return The modified URI with the get parameters in extraParams added.
  2951. */
  2952. public static String addGetParameters(String uri, String extraParams) {
  2953. if (extraParams == null || extraParams.length() == 0) {
  2954. return uri;
  2955. }
  2956. // RFC 3986: The query component is indicated by the first question
  2957. // mark ("?") character and terminated by a number sign ("#") character
  2958. // or by the end of the URI.
  2959. String fragment = null;
  2960. int hashPosition = uri.indexOf('#');
  2961. if (hashPosition != -1) {
  2962. // Fragment including "#"
  2963. fragment = uri.substring(hashPosition);
  2964. // The full uri before the fragment
  2965. uri = uri.substring(0, hashPosition);
  2966. }
  2967. if (uri.contains("?")) {
  2968. uri += "&";
  2969. } else {
  2970. uri += "?";
  2971. }
  2972. uri += extraParams;
  2973. if (fragment != null) {
  2974. uri += fragment;
  2975. }
  2976. return uri;
  2977. }
  2978. ConnectorMap getConnectorMap() {
  2979. return connectorMap;
  2980. }
  2981. /**
  2982. * @deprecated As of 7.0. No longer serves any purpose.
  2983. */
  2984. @Deprecated
  2985. public void unregisterPaintable(ServerConnector p) {
  2986. VConsole.log("unregisterPaintable (unnecessarily) called for "
  2987. + Util.getConnectorString(p));
  2988. }
  2989. /**
  2990. * Get VTooltip instance related to application connection
  2991. *
  2992. * @return VTooltip instance
  2993. */
  2994. public VTooltip getVTooltip() {
  2995. return tooltip;
  2996. }
  2997. /**
  2998. * Method provided for backwards compatibility. Duties previously done by
  2999. * this method is now handled by the state change event handler in
  3000. * AbstractComponentConnector. The only function this method has is to
  3001. * return true if the UIDL is a "cached" update.
  3002. *
  3003. * @param component
  3004. * @param uidl
  3005. * @param manageCaption
  3006. * @deprecated As of 7.0, no longer serves any purpose
  3007. * @return
  3008. */
  3009. @Deprecated
  3010. public boolean updateComponent(Widget component, UIDL uidl,
  3011. boolean manageCaption) {
  3012. ComponentConnector connector = getConnectorMap()
  3013. .getConnector(component);
  3014. if (!AbstractComponentConnector.isRealUpdate(uidl)) {
  3015. return true;
  3016. }
  3017. if (!manageCaption) {
  3018. VConsole.error(Util.getConnectorString(connector)
  3019. + " 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.");
  3020. }
  3021. return false;
  3022. }
  3023. /**
  3024. * @deprecated As of 7.0. Use
  3025. * {@link AbstractComponentConnector#hasEventListener(String)}
  3026. * instead
  3027. */
  3028. @Deprecated
  3029. public boolean hasEventListeners(Widget widget, String eventIdentifier) {
  3030. ComponentConnector connector = getConnectorMap().getConnector(widget);
  3031. if (connector == null) {
  3032. /*
  3033. * No connector will exist in cases where Vaadin widgets have been
  3034. * re-used without implementing server<->client communication.
  3035. */
  3036. return false;
  3037. }
  3038. return hasEventListeners(getConnectorMap().getConnector(widget),
  3039. eventIdentifier);
  3040. }
  3041. LayoutManager getLayoutManager() {
  3042. return layoutManager;
  3043. }
  3044. /**
  3045. * Schedules a heartbeat request to occur after the configured heartbeat
  3046. * interval elapses if the interval is a positive number. Otherwise, does
  3047. * nothing.
  3048. *
  3049. * @deprecated as of 7.2, use {@link Heartbeat#schedule()} instead
  3050. */
  3051. @Deprecated
  3052. protected void scheduleHeartbeat() {
  3053. heartbeat.schedule();
  3054. }
  3055. /**
  3056. * Sends a heartbeat request to the server.
  3057. * <p>
  3058. * Heartbeat requests are used to inform the server that the client-side is
  3059. * still alive. If the client page is closed or the connection lost, the
  3060. * server will eventually close the inactive UI.
  3061. *
  3062. * @deprecated as of 7.2, use {@link Heartbeat#send()} instead
  3063. */
  3064. @Deprecated
  3065. protected void sendHeartbeat() {
  3066. heartbeat.send();
  3067. }
  3068. /**
  3069. * Timer used to make sure that no misbehaving components can delay response
  3070. * handling forever.
  3071. */
  3072. Timer forceHandleMessage = new Timer() {
  3073. @Override
  3074. public void run() {
  3075. VConsole.log("WARNING: reponse handling was never resumed, forcibly removing locks...");
  3076. responseHandlingLocks.clear();
  3077. handlePendingMessages();
  3078. }
  3079. };
  3080. /**
  3081. * This method can be used to postpone rendering of a response for a short
  3082. * period of time (e.g. to avoid the rendering process during animation).
  3083. *
  3084. * @param lock
  3085. */
  3086. public void suspendReponseHandling(Object lock) {
  3087. responseHandlingLocks.add(lock);
  3088. }
  3089. /**
  3090. * Resumes the rendering process once all locks have been removed.
  3091. *
  3092. * @param lock
  3093. */
  3094. public void resumeResponseHandling(Object lock) {
  3095. responseHandlingLocks.remove(lock);
  3096. if (responseHandlingLocks.isEmpty()) {
  3097. // Cancel timer that breaks the lock
  3098. forceHandleMessage.cancel();
  3099. if (!pendingUIDLMessages.isEmpty()) {
  3100. VConsole.log("No more response handling locks, handling pending requests.");
  3101. handlePendingMessages();
  3102. }
  3103. }
  3104. }
  3105. /**
  3106. * Handles all pending UIDL messages queued while response handling was
  3107. * suspended.
  3108. */
  3109. private void handlePendingMessages() {
  3110. if (!pendingUIDLMessages.isEmpty()) {
  3111. /*
  3112. * Clear the list before processing enqueued messages to support
  3113. * reentrancy
  3114. */
  3115. List<PendingUIDLMessage> pendingMessages = pendingUIDLMessages;
  3116. pendingUIDLMessages = new ArrayList<PendingUIDLMessage>();
  3117. for (PendingUIDLMessage pending : pendingMessages) {
  3118. handleReceivedJSONMessage(pending.getStart(),
  3119. pending.getJsonText(), pending.getJson());
  3120. }
  3121. }
  3122. }
  3123. private boolean handleErrorInDelegate(String details, int statusCode) {
  3124. if (communicationErrorDelegate == null) {
  3125. return false;
  3126. }
  3127. return communicationErrorDelegate.onError(details, statusCode);
  3128. }
  3129. /**
  3130. * Sets the delegate that is called whenever a communication error occurrs.
  3131. *
  3132. * @param delegate
  3133. * the delegate.
  3134. */
  3135. public void setCommunicationErrorDelegate(CommunicationErrorHandler delegate) {
  3136. communicationErrorDelegate = delegate;
  3137. }
  3138. public void setApplicationRunning(boolean running) {
  3139. if (applicationRunning && !running) {
  3140. eventBus.fireEvent(new ApplicationStoppedEvent());
  3141. }
  3142. applicationRunning = running;
  3143. }
  3144. public boolean isApplicationRunning() {
  3145. return applicationRunning;
  3146. }
  3147. public <H extends EventHandler> HandlerRegistration addHandler(
  3148. GwtEvent.Type<H> type, H handler) {
  3149. return eventBus.addHandler(type, handler);
  3150. }
  3151. @Override
  3152. public void fireEvent(GwtEvent<?> event) {
  3153. eventBus.fireEvent(event);
  3154. }
  3155. /**
  3156. * Calls {@link ComponentConnector#flush()} on the active connector. Does
  3157. * nothing if there is no active (focused) connector.
  3158. */
  3159. public void flushActiveConnector() {
  3160. ComponentConnector activeConnector = getActiveConnector();
  3161. if (activeConnector == null) {
  3162. return;
  3163. }
  3164. activeConnector.flush();
  3165. }
  3166. /**
  3167. * Gets the active connector for focused element in browser.
  3168. *
  3169. * @return Connector for focused element or null.
  3170. */
  3171. private ComponentConnector getActiveConnector() {
  3172. Element focusedElement = Util.getFocusedElement();
  3173. if (focusedElement == null) {
  3174. return null;
  3175. }
  3176. return Util.getConnectorForElement(this, getUIConnector().getWidget(),
  3177. focusedElement);
  3178. }
  3179. /**
  3180. * Sets the status for the push connection.
  3181. *
  3182. * @param enabled
  3183. * <code>true</code> to enable the push connection;
  3184. * <code>false</code> to disable the push connection.
  3185. */
  3186. public void setPushEnabled(boolean enabled) {
  3187. final PushConfigurationState pushState = uIConnector.getState().pushConfiguration;
  3188. if (enabled && push == null) {
  3189. push = GWT.create(PushConnection.class);
  3190. push.init(this, pushState, new CommunicationErrorHandler() {
  3191. @Override
  3192. public boolean onError(String details, int statusCode) {
  3193. showCommunicationError(details, statusCode);
  3194. return true;
  3195. }
  3196. });
  3197. } else if (!enabled && push != null && push.isActive()) {
  3198. push.disconnect(new Command() {
  3199. @Override
  3200. public void execute() {
  3201. push = null;
  3202. /*
  3203. * If push has been enabled again while we were waiting for
  3204. * the old connection to disconnect, now is the right time
  3205. * to open a new connection
  3206. */
  3207. if (pushState.mode.isEnabled()) {
  3208. setPushEnabled(true);
  3209. }
  3210. /*
  3211. * Send anything that was enqueued while we waited for the
  3212. * connection to close
  3213. */
  3214. if (pendingInvocations.size() > 0) {
  3215. sendPendingVariableChanges();
  3216. }
  3217. }
  3218. });
  3219. }
  3220. }
  3221. public void handlePushMessage(String message) {
  3222. handleJSONText(message, 200);
  3223. }
  3224. /**
  3225. * Returns a human readable string representation of the method used to
  3226. * communicate with the server.
  3227. *
  3228. * @since 7.1
  3229. * @return A string representation of the current transport type
  3230. */
  3231. public String getCommunicationMethodName() {
  3232. if (push != null) {
  3233. return "Push (" + push.getTransportType() + ")";
  3234. } else {
  3235. return "XHR";
  3236. }
  3237. }
  3238. private static Logger getLogger() {
  3239. return Logger.getLogger(ApplicationConnection.class.getName());
  3240. }
  3241. /**
  3242. * Returns the hearbeat instance.
  3243. */
  3244. public Heartbeat getHeartbeat() {
  3245. return heartbeat;
  3246. }
  3247. }