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

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