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

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