Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ApplicationConfiguration.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /*
  2. * Copyright 2011 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.LinkedList;
  20. import java.util.List;
  21. import java.util.Map;
  22. import com.google.gwt.core.client.EntryPoint;
  23. import com.google.gwt.core.client.GWT;
  24. import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
  25. import com.google.gwt.core.client.JavaScriptObject;
  26. import com.google.gwt.core.client.JsArrayString;
  27. import com.google.gwt.core.client.Scheduler;
  28. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  29. import com.google.gwt.user.client.Command;
  30. import com.google.gwt.user.client.Window;
  31. import com.vaadin.client.metadata.BundleLoadCallback;
  32. import com.vaadin.client.metadata.ConnectorBundleLoader;
  33. import com.vaadin.client.metadata.NoDataException;
  34. import com.vaadin.client.metadata.TypeData;
  35. import com.vaadin.client.ui.UnknownComponentConnector;
  36. import com.vaadin.shared.ApplicationConstants;
  37. import com.vaadin.shared.ui.ui.UIConstants;
  38. public class ApplicationConfiguration implements EntryPoint {
  39. /**
  40. * Helper class for reading configuration options from the bootstap
  41. * javascript
  42. *
  43. * @since 7.0
  44. */
  45. private static class JsoConfiguration extends JavaScriptObject {
  46. protected JsoConfiguration() {
  47. // JSO Constructor
  48. }
  49. /**
  50. * Reads a configuration parameter as a string. Please note that the
  51. * javascript value of the parameter should also be a string, or else an
  52. * undefined exception may be thrown.
  53. *
  54. * @param name
  55. * name of the configuration parameter
  56. * @return value of the configuration parameter, or <code>null</code> if
  57. * not defined
  58. */
  59. private native String getConfigString(String name)
  60. /*-{
  61. var value = this.getConfig(name);
  62. if (value === null || value === undefined) {
  63. return null;
  64. } else {
  65. return value +"";
  66. }
  67. }-*/;
  68. /**
  69. * Reads a configuration parameter as a boolean object. Please note that
  70. * the javascript value of the parameter should also be a boolean, or
  71. * else an undefined exception may be thrown.
  72. *
  73. * @param name
  74. * name of the configuration parameter
  75. * @return boolean value of the configuration paramter, or
  76. * <code>null</code> if no value is defined
  77. */
  78. private native Boolean getConfigBoolean(String name)
  79. /*-{
  80. var value = this.getConfig(name);
  81. if (value === null || value === undefined) {
  82. return null;
  83. } else {
  84. // $entry not needed as function is not exported
  85. return @java.lang.Boolean::valueOf(Z)(value);
  86. }
  87. }-*/;
  88. /**
  89. * Reads a configuration parameter as an integer object. Please note
  90. * that the javascript value of the parameter should also be an integer,
  91. * or else an undefined exception may be thrown.
  92. *
  93. * @param name
  94. * name of the configuration parameter
  95. * @return integer value of the configuration paramter, or
  96. * <code>null</code> if no value is defined
  97. */
  98. private native Integer getConfigInteger(String name)
  99. /*-{
  100. var value = this.getConfig(name);
  101. if (value === null || value === undefined) {
  102. return null;
  103. } else {
  104. // $entry not needed as function is not exported
  105. return @java.lang.Integer::valueOf(I)(value);
  106. }
  107. }-*/;
  108. /**
  109. * Reads a configuration parameter as an {@link ErrorMessage} object.
  110. * Please note that the javascript value of the parameter should also be
  111. * an object with appropriate fields, or else an undefined exception may
  112. * be thrown when calling this method or when calling methods on the
  113. * returned object.
  114. *
  115. * @param name
  116. * name of the configuration parameter
  117. * @return error message with the given name, or <code>null</code> if no
  118. * value is defined
  119. */
  120. private native ErrorMessage getConfigError(String name)
  121. /*-{
  122. return this.getConfig(name);
  123. }-*/;
  124. /**
  125. * Returns a native javascript object containing version information
  126. * from the server.
  127. *
  128. * @return a javascript object with the version information
  129. */
  130. private native JavaScriptObject getVersionInfoJSObject()
  131. /*-{
  132. return this.getConfig("versionInfo");
  133. }-*/;
  134. /**
  135. * Gets the version of the Vaadin framework used on the server.
  136. *
  137. * @return a string with the version
  138. *
  139. * @see com.vaadin.server.VaadinServlet#VERSION
  140. */
  141. private native String getVaadinVersion()
  142. /*-{
  143. return this.getConfig("versionInfo").vaadinVersion;
  144. }-*/;
  145. private native String getUIDL()
  146. /*-{
  147. return this.getConfig("uidl");
  148. }-*/;
  149. }
  150. /**
  151. * Wraps a native javascript object containing fields for an error message
  152. *
  153. * @since 7.0
  154. */
  155. public static final class ErrorMessage extends JavaScriptObject {
  156. protected ErrorMessage() {
  157. // JSO constructor
  158. }
  159. public final native String getCaption()
  160. /*-{
  161. return this.caption;
  162. }-*/;
  163. public final native String getMessage()
  164. /*-{
  165. return this.message;
  166. }-*/;
  167. public final native String getUrl()
  168. /*-{
  169. return this.url;
  170. }-*/;
  171. }
  172. private static WidgetSet widgetSet = GWT.create(WidgetSet.class);
  173. private String id;
  174. /**
  175. * The URL to the VAADIN directory containing themes and widgetsets. Should
  176. * always end with a slash (/).
  177. */
  178. private String vaadinDirUrl;
  179. private String serviceUrl;
  180. private int uiId;
  181. private boolean standalone;
  182. private ErrorMessage communicationError;
  183. private ErrorMessage authorizationError;
  184. private int heartbeatInterval;
  185. private HashMap<Integer, String> unknownComponents;
  186. private Map<Integer, Class<? extends ServerConnector>> classes = new HashMap<Integer, Class<? extends ServerConnector>>();
  187. private boolean browserDetailsSent = false;
  188. private boolean widgetsetVersionSent = false;
  189. static// TODO consider to make this hashmap per application
  190. LinkedList<Command> callbacks = new LinkedList<Command>();
  191. private static int dependenciesLoading;
  192. private static ArrayList<ApplicationConnection> runningApplications = new ArrayList<ApplicationConnection>();
  193. private Map<Integer, Integer> componentInheritanceMap = new HashMap<Integer, Integer>();
  194. private Map<Integer, String> tagToServerSideClassName = new HashMap<Integer, String>();
  195. /**
  196. * Checks whether path info in requests to the server-side service should be
  197. * in a request parameter (named
  198. * {@value ApplicationConstants#V_RESOURCE_PATH}) or appended to the end of
  199. * the service URL.
  200. *
  201. * @see #getServiceUrl()
  202. *
  203. * @return <code>true</code> if path info should be a request parameter;
  204. * <code>false</code> if the path info goes after the service URL
  205. */
  206. public boolean useServiceUrlPathParam() {
  207. return getJsoConfiguration(id).getConfigBoolean(
  208. ApplicationConstants.SERVICE_URL_PATH_AS_PARAMETER) == Boolean.TRUE;
  209. }
  210. public String getRootPanelId() {
  211. return id;
  212. }
  213. /**
  214. * Gets the URL to the server-side VaadinService. If
  215. * {@link #useServiceUrlPathParam()} return <code>true</code>, the requested
  216. * path info should be in the {@value ApplicationConstants#V_RESOURCE_PATH}
  217. * query parameter; else the path info should be appended to the end of the
  218. * URL.
  219. *
  220. * @see #useServiceUrlPathParam()
  221. *
  222. * @return the URL to the server-side service as a string
  223. */
  224. public String getServiceUrl() {
  225. return serviceUrl;
  226. }
  227. public String getThemeName() {
  228. String themeName = getJsoConfiguration(id).getConfigString("theme");
  229. themeName = themeName.replaceAll("[^a-zA-Z0-9]", "");
  230. return themeName;
  231. }
  232. public String getThemeUri() {
  233. return vaadinDirUrl + "themes/" + getThemeName();
  234. }
  235. public void setAppId(String appId) {
  236. id = appId;
  237. }
  238. /**
  239. * Gets the initial UIDL from the DOM, if it was provided during the init
  240. * process.
  241. *
  242. * @return
  243. */
  244. public String getUIDL() {
  245. return getJsoConfiguration(id).getUIDL();
  246. }
  247. /**
  248. * @return true if the application is served by std. Vaadin servlet and is
  249. * considered to be the only or main content of the host page.
  250. */
  251. public boolean isStandalone() {
  252. return standalone;
  253. }
  254. /**
  255. * Gets the root if of this application instance. The root id should be
  256. * included in every request originating from this instance in order to
  257. * associate it with the right UI instance on the server.
  258. *
  259. * @return the root id
  260. */
  261. public int getUIId() {
  262. return uiId;
  263. }
  264. /**
  265. * @return The interval in seconds between heartbeat requests, or a
  266. * non-positive number if heartbeat is disabled.
  267. */
  268. public int getHeartbeatInterval() {
  269. return heartbeatInterval;
  270. }
  271. public JavaScriptObject getVersionInfoJSObject() {
  272. return getJsoConfiguration(id).getVersionInfoJSObject();
  273. }
  274. public ErrorMessage getCommunicationError() {
  275. return communicationError;
  276. }
  277. public ErrorMessage getAuthorizationError() {
  278. return authorizationError;
  279. }
  280. /**
  281. * Reads the configuration values defined by the bootstrap javascript.
  282. */
  283. private void loadFromDOM() {
  284. JsoConfiguration jsoConfiguration = getJsoConfiguration(id);
  285. serviceUrl = jsoConfiguration
  286. .getConfigString(ApplicationConstants.SERVICE_URL);
  287. if (serviceUrl == null || "".equals(serviceUrl)) {
  288. /*
  289. * Use the current url without query parameters and fragment as the
  290. * default value.
  291. */
  292. serviceUrl = Window.Location.getHref().replaceFirst("[?#].*", "");
  293. } else {
  294. /*
  295. * Resolve potentially relative URLs to ensure they point to the
  296. * desired locations even if the base URL of the page changes later
  297. * (e.g. with pushState)
  298. */
  299. serviceUrl = Util.getAbsoluteUrl(serviceUrl);
  300. }
  301. // Ensure there's an ending slash (to make appending e.g. UIDL work)
  302. if (!useServiceUrlPathParam() && !serviceUrl.endsWith("/")) {
  303. serviceUrl += '/';
  304. }
  305. vaadinDirUrl = Util.getAbsoluteUrl(jsoConfiguration
  306. .getConfigString(ApplicationConstants.VAADIN_DIR_URL));
  307. uiId = jsoConfiguration.getConfigInteger(UIConstants.UI_ID_PARAMETER)
  308. .intValue();
  309. // null -> false
  310. standalone = jsoConfiguration.getConfigBoolean("standalone") == Boolean.TRUE;
  311. heartbeatInterval = jsoConfiguration
  312. .getConfigInteger("heartbeatInterval");
  313. communicationError = jsoConfiguration.getConfigError("comErrMsg");
  314. authorizationError = jsoConfiguration.getConfigError("authErrMsg");
  315. // boostrap sets initPending to false if it has sent the browser details
  316. if (jsoConfiguration.getConfigBoolean("initPending") == Boolean.FALSE) {
  317. setBrowserDetailsSent();
  318. }
  319. }
  320. /**
  321. * Starts the application with a given id by reading the configuration
  322. * options stored by the bootstrap javascript.
  323. *
  324. * @param applicationId
  325. * id of the application to load, this is also the id of the html
  326. * element into which the application should be rendered.
  327. */
  328. public static void startApplication(final String applicationId) {
  329. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  330. @Override
  331. public void execute() {
  332. ApplicationConfiguration appConf = getConfigFromDOM(applicationId);
  333. ApplicationConnection a = GWT
  334. .create(ApplicationConnection.class);
  335. a.init(widgetSet, appConf);
  336. a.start();
  337. runningApplications.add(a);
  338. }
  339. });
  340. }
  341. public static List<ApplicationConnection> getRunningApplications() {
  342. return runningApplications;
  343. }
  344. /**
  345. * Gets the configuration object for a specific application from the
  346. * bootstrap javascript.
  347. *
  348. * @param appId
  349. * the id of the application to get configuration data for
  350. * @return a native javascript object containing the configuration data
  351. */
  352. private native static JsoConfiguration getJsoConfiguration(String appId)
  353. /*-{
  354. return $wnd.vaadin.getApp(appId);
  355. }-*/;
  356. public static ApplicationConfiguration getConfigFromDOM(String appId) {
  357. ApplicationConfiguration conf = new ApplicationConfiguration();
  358. conf.setAppId(appId);
  359. conf.loadFromDOM();
  360. return conf;
  361. }
  362. public String getServletVersion() {
  363. return getJsoConfiguration(id).getVaadinVersion();
  364. }
  365. public Class<? extends ServerConnector> getConnectorClassByEncodedTag(
  366. int tag) {
  367. Class<? extends ServerConnector> type = classes.get(tag);
  368. if (type == null && !classes.containsKey(tag)) {
  369. // Initialize if not already loaded
  370. Integer currentTag = Integer.valueOf(tag);
  371. while (type == null && currentTag != null) {
  372. String serverSideClassNameForTag = getServerSideClassNameForTag(currentTag);
  373. if (TypeData.hasIdentifier(serverSideClassNameForTag)) {
  374. try {
  375. type = (Class<? extends ServerConnector>) TypeData
  376. .getClass(serverSideClassNameForTag);
  377. } catch (NoDataException e) {
  378. throw new RuntimeException(e);
  379. }
  380. }
  381. currentTag = getParentTag(currentTag.intValue());
  382. }
  383. if (type == null) {
  384. type = UnknownComponentConnector.class;
  385. if (unknownComponents == null) {
  386. unknownComponents = new HashMap<Integer, String>();
  387. }
  388. unknownComponents.put(tag, getServerSideClassNameForTag(tag));
  389. }
  390. classes.put(tag, type);
  391. }
  392. return type;
  393. }
  394. public void addComponentInheritanceInfo(ValueMap valueMap) {
  395. JsArrayString keyArray = valueMap.getKeyArray();
  396. for (int i = 0; i < keyArray.length(); i++) {
  397. String key = keyArray.get(i);
  398. int value = valueMap.getInt(key);
  399. componentInheritanceMap.put(Integer.parseInt(key), value);
  400. }
  401. }
  402. public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
  403. JsArrayString keyArray = valueMap.getKeyArray();
  404. for (int i = 0; i < keyArray.length(); i++) {
  405. String key = keyArray.get(i).intern();
  406. int value = valueMap.getInt(key);
  407. tagToServerSideClassName.put(value, key);
  408. }
  409. for (int i = 0; i < keyArray.length(); i++) {
  410. String key = keyArray.get(i).intern();
  411. int value = valueMap.getInt(key);
  412. widgetSet.ensureConnectorLoaded(value, this);
  413. }
  414. }
  415. public Integer getParentTag(int tag) {
  416. return componentInheritanceMap.get(tag);
  417. }
  418. public String getServerSideClassNameForTag(Integer tag) {
  419. return tagToServerSideClassName.get(tag);
  420. }
  421. String getUnknownServerClassNameByTag(int tag) {
  422. if (unknownComponents != null) {
  423. return unknownComponents.get(tag);
  424. }
  425. return null;
  426. }
  427. /**
  428. *
  429. * @param c
  430. */
  431. static void runWhenDependenciesLoaded(Command c) {
  432. if (dependenciesLoading == 0) {
  433. c.execute();
  434. } else {
  435. callbacks.add(c);
  436. }
  437. }
  438. static void startDependencyLoading() {
  439. dependenciesLoading++;
  440. }
  441. static void endDependencyLoading() {
  442. dependenciesLoading--;
  443. if (dependenciesLoading == 0 && !callbacks.isEmpty()) {
  444. for (Command cmd : callbacks) {
  445. cmd.execute();
  446. }
  447. callbacks.clear();
  448. } else if (dependenciesLoading == 0
  449. && !ConnectorBundleLoader.get().isBundleLoaded(
  450. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME)) {
  451. ConnectorBundleLoader.get().loadBundle(
  452. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME,
  453. new BundleLoadCallback() {
  454. @Override
  455. public void loaded() {
  456. // Nothing to do
  457. }
  458. @Override
  459. public void failed(Throwable reason) {
  460. VConsole.error(reason);
  461. }
  462. });
  463. }
  464. }
  465. @Override
  466. public void onModuleLoad() {
  467. // Prepare VConsole for debugging
  468. if (isDebugMode()) {
  469. Console console = GWT.create(Console.class);
  470. console.setQuietMode(isQuietDebugMode());
  471. console.init();
  472. VConsole.setImplementation(console);
  473. } else {
  474. VConsole.setImplementation((Console) GWT.create(NullConsole.class));
  475. }
  476. /*
  477. * Display some sort of error of exceptions in web mode to debug
  478. * console. After this, exceptions are reported to VConsole and possible
  479. * GWT hosted mode.
  480. */
  481. GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
  482. @Override
  483. public void onUncaughtException(Throwable e) {
  484. /*
  485. * Note in case of null console (without ?debug) we eat
  486. * exceptions. "a1 is not an object" style errors helps nobody,
  487. * especially end user. It does not work tells just as much.
  488. */
  489. VConsole.getImplementation().error(e);
  490. }
  491. });
  492. if (SuperDevMode.enableBasedOnParameter()) {
  493. // Do not start any application as super dev mode will refresh the
  494. // page once done compiling
  495. return;
  496. }
  497. registerCallback(GWT.getModuleName());
  498. }
  499. /**
  500. * Registers that callback that the bootstrap javascript uses to start
  501. * applications once the widgetset is loaded and all required information is
  502. * available
  503. *
  504. * @param widgetsetName
  505. * the name of this widgetset
  506. */
  507. public native static void registerCallback(String widgetsetName)
  508. /*-{
  509. var callbackHandler = $entry(@com.vaadin.client.ApplicationConfiguration::startApplication(Ljava/lang/String;));
  510. $wnd.vaadin.registerWidgetset(widgetsetName, callbackHandler);
  511. }-*/;
  512. /**
  513. * Checks if client side is in debug mode. Practically this is invoked by
  514. * adding ?debug parameter to URI.
  515. *
  516. * @return true if client side is currently been debugged
  517. */
  518. public static boolean isDebugMode() {
  519. return isDebugAvailable()
  520. && Window.Location.getParameter("debug") != null;
  521. }
  522. private native static boolean isDebugAvailable()
  523. /*-{
  524. if($wnd.vaadin.debug) {
  525. return true;
  526. } else {
  527. return false;
  528. }
  529. }-*/;
  530. /**
  531. * Checks whether debug logging should be quiet
  532. *
  533. * @return <code>true</code> if debug logging should be quiet
  534. */
  535. public static boolean isQuietDebugMode() {
  536. String debugParameter = Window.Location.getParameter("debug");
  537. return isDebugAvailable() && debugParameter != null
  538. && debugParameter.startsWith("q");
  539. }
  540. /**
  541. * Checks whether information from the web browser (e.g. uri fragment and
  542. * screen size) has been sent to the server.
  543. *
  544. * @return <code>true</code> if browser information has already been sent
  545. *
  546. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  547. */
  548. public boolean isBrowserDetailsSent() {
  549. return browserDetailsSent;
  550. }
  551. /**
  552. * Registers that the browser details have been sent.
  553. * {@link #isBrowserDetailsSent()} will return
  554. * <code> after this method has been invoked.
  555. */
  556. public void setBrowserDetailsSent() {
  557. browserDetailsSent = true;
  558. }
  559. /**
  560. * Checks whether the widget set version has been sent to the server. It is
  561. * sent in the first UIDL request.
  562. *
  563. * @return <code>true</code> if browser information has already been sent
  564. *
  565. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  566. */
  567. public boolean isWidgetsetVersionSent() {
  568. return widgetsetVersionSent;
  569. }
  570. /**
  571. * Registers that the widget set version has been sent to the server.
  572. */
  573. public void setWidgetsetVersionSent() {
  574. widgetsetVersionSent = true;
  575. }
  576. }