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.

ApplicationConfiguration.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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.terminal.gwt.server.AbstractApplicationServlet#VERSION
  140. */
  141. private native String getVaadinVersion()
  142. /*-{
  143. return this.getConfig("versionInfo").vaadinVersion;
  144. }-*/;
  145. /**
  146. * Gets the version of the application running on the server.
  147. *
  148. * @return a string with the application version
  149. *
  150. * @see com.vaadin.Application#getVersion()
  151. */
  152. private native String getApplicationVersion()
  153. /*-{
  154. return this.getConfig("versionInfo").applicationVersion;
  155. }-*/;
  156. private native String getUIDL()
  157. /*-{
  158. return this.getConfig("uidl");
  159. }-*/;
  160. }
  161. /**
  162. * Wraps a native javascript object containing fields for an error message
  163. *
  164. * @since 7.0
  165. */
  166. public static final class ErrorMessage extends JavaScriptObject {
  167. protected ErrorMessage() {
  168. // JSO constructor
  169. }
  170. public final native String getCaption()
  171. /*-{
  172. return this.caption;
  173. }-*/;
  174. public final native String getMessage()
  175. /*-{
  176. return this.message;
  177. }-*/;
  178. public final native String getUrl()
  179. /*-{
  180. return this.url;
  181. }-*/;
  182. }
  183. private static WidgetSet widgetSet = GWT.create(WidgetSet.class);
  184. private String id;
  185. private String themeUri;
  186. private String appUri;
  187. private int uiId;
  188. private boolean standalone;
  189. private ErrorMessage communicationError;
  190. private ErrorMessage authorizationError;
  191. private int heartbeatInterval;
  192. private HashMap<Integer, String> unknownComponents;
  193. private Map<Integer, Class<? extends ServerConnector>> classes = new HashMap<Integer, Class<? extends ServerConnector>>();
  194. private boolean browserDetailsSent = false;
  195. private boolean widgetsetVersionSent = false;
  196. static// TODO consider to make this hashmap per application
  197. LinkedList<Command> callbacks = new LinkedList<Command>();
  198. private static int dependenciesLoading;
  199. private static ArrayList<ApplicationConnection> runningApplications = new ArrayList<ApplicationConnection>();
  200. private Map<Integer, Integer> componentInheritanceMap = new HashMap<Integer, Integer>();
  201. private Map<Integer, String> tagToServerSideClassName = new HashMap<Integer, String>();
  202. public boolean usePortletURLs() {
  203. return getPortletResourceUrl() != null;
  204. }
  205. public String getPortletResourceUrl() {
  206. return getJsoConfiguration(id).getConfigString(
  207. ApplicationConstants.PORTLET_RESOUCE_URL_BASE);
  208. }
  209. public String getRootPanelId() {
  210. return id;
  211. }
  212. /**
  213. * Gets the application base URI. Using this other than as the download
  214. * action URI can cause problems in Portlet 2.0 deployments.
  215. *
  216. * @return application base URI
  217. */
  218. public String getApplicationUri() {
  219. return appUri;
  220. }
  221. public String getThemeName() {
  222. String uri = getThemeUri();
  223. String themeName = uri.substring(uri.lastIndexOf('/'));
  224. themeName = themeName.replaceAll("[^a-zA-Z0-9]", "");
  225. return themeName;
  226. }
  227. public String getThemeUri() {
  228. return themeUri;
  229. }
  230. public void setAppId(String appId) {
  231. id = appId;
  232. }
  233. /**
  234. * Gets the initial UIDL from the DOM, if it was provided during the init
  235. * process.
  236. *
  237. * @return
  238. */
  239. public String getUIDL() {
  240. return getJsoConfiguration(id).getUIDL();
  241. }
  242. /**
  243. * @return true if the application is served by std. Vaadin servlet and is
  244. * considered to be the only or main content of the host page.
  245. */
  246. public boolean isStandalone() {
  247. return standalone;
  248. }
  249. /**
  250. * Gets the root if of this application instance. The root id should be
  251. * included in every request originating from this instance in order to
  252. * associate it with the right UI instance on the server.
  253. *
  254. * @return the root id
  255. */
  256. public int getUIId() {
  257. return uiId;
  258. }
  259. /**
  260. * @return The interval in seconds between heartbeat requests, or a
  261. * non-positive number if heartbeat is disabled.
  262. */
  263. public int getHeartbeatInterval() {
  264. return heartbeatInterval;
  265. }
  266. public JavaScriptObject getVersionInfoJSObject() {
  267. return getJsoConfiguration(id).getVersionInfoJSObject();
  268. }
  269. public ErrorMessage getCommunicationError() {
  270. return communicationError;
  271. }
  272. public ErrorMessage getAuthorizationError() {
  273. return authorizationError;
  274. }
  275. /**
  276. * Reads the configuration values defined by the bootstrap javascript.
  277. */
  278. private void loadFromDOM() {
  279. JsoConfiguration jsoConfiguration = getJsoConfiguration(id);
  280. appUri = jsoConfiguration.getConfigString("appUri");
  281. if (appUri != null && !appUri.endsWith("/")) {
  282. appUri += '/';
  283. }
  284. themeUri = jsoConfiguration.getConfigString("themeUri");
  285. uiId = jsoConfiguration.getConfigInteger(UIConstants.UI_ID_PARAMETER)
  286. .intValue();
  287. // null -> false
  288. standalone = jsoConfiguration.getConfigBoolean("standalone") == Boolean.TRUE;
  289. heartbeatInterval = jsoConfiguration
  290. .getConfigInteger("heartbeatInterval");
  291. communicationError = jsoConfiguration.getConfigError("comErrMsg");
  292. authorizationError = jsoConfiguration.getConfigError("authErrMsg");
  293. // boostrap sets initPending to false if it has sent the browser details
  294. if (jsoConfiguration.getConfigBoolean("initPending") == Boolean.FALSE) {
  295. setBrowserDetailsSent();
  296. }
  297. }
  298. /**
  299. * Starts the application with a given id by reading the configuration
  300. * options stored by the bootstrap javascript.
  301. *
  302. * @param applicationId
  303. * id of the application to load, this is also the id of the html
  304. * element into which the application should be rendered.
  305. */
  306. public static void startApplication(final String applicationId) {
  307. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  308. @Override
  309. public void execute() {
  310. ApplicationConfiguration appConf = getConfigFromDOM(applicationId);
  311. ApplicationConnection a = GWT
  312. .create(ApplicationConnection.class);
  313. a.init(widgetSet, appConf);
  314. a.start();
  315. runningApplications.add(a);
  316. }
  317. });
  318. }
  319. public static List<ApplicationConnection> getRunningApplications() {
  320. return runningApplications;
  321. }
  322. /**
  323. * Gets the configuration object for a specific application from the
  324. * bootstrap javascript.
  325. *
  326. * @param appId
  327. * the id of the application to get configuration data for
  328. * @return a native javascript object containing the configuration data
  329. */
  330. private native static JsoConfiguration getJsoConfiguration(String appId)
  331. /*-{
  332. return $wnd.vaadin.getApp(appId);
  333. }-*/;
  334. public static ApplicationConfiguration getConfigFromDOM(String appId) {
  335. ApplicationConfiguration conf = new ApplicationConfiguration();
  336. conf.setAppId(appId);
  337. conf.loadFromDOM();
  338. return conf;
  339. }
  340. public String getServletVersion() {
  341. return getJsoConfiguration(id).getVaadinVersion();
  342. }
  343. public String getApplicationVersion() {
  344. return getJsoConfiguration(id).getApplicationVersion();
  345. }
  346. public Class<? extends ServerConnector> getConnectorClassByEncodedTag(
  347. int tag) {
  348. Class<? extends ServerConnector> type = classes.get(tag);
  349. if (type == null && !classes.containsKey(tag)) {
  350. // Initialize if not already loaded
  351. Integer currentTag = Integer.valueOf(tag);
  352. while (type == null && currentTag != null) {
  353. String serverSideClassNameForTag = getServerSideClassNameForTag(currentTag);
  354. if (TypeData.hasIdentifier(serverSideClassNameForTag)) {
  355. try {
  356. type = (Class<? extends ServerConnector>) TypeData
  357. .getClass(serverSideClassNameForTag);
  358. } catch (NoDataException e) {
  359. throw new RuntimeException(e);
  360. }
  361. }
  362. currentTag = getParentTag(currentTag.intValue());
  363. }
  364. if (type == null) {
  365. type = UnknownComponentConnector.class;
  366. if (unknownComponents == null) {
  367. unknownComponents = new HashMap<Integer, String>();
  368. }
  369. unknownComponents.put(tag, getServerSideClassNameForTag(tag));
  370. }
  371. classes.put(tag, type);
  372. }
  373. return type;
  374. }
  375. public void addComponentInheritanceInfo(ValueMap valueMap) {
  376. JsArrayString keyArray = valueMap.getKeyArray();
  377. for (int i = 0; i < keyArray.length(); i++) {
  378. String key = keyArray.get(i);
  379. int value = valueMap.getInt(key);
  380. componentInheritanceMap.put(Integer.parseInt(key), value);
  381. }
  382. }
  383. public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
  384. JsArrayString keyArray = valueMap.getKeyArray();
  385. for (int i = 0; i < keyArray.length(); i++) {
  386. String key = keyArray.get(i).intern();
  387. int value = valueMap.getInt(key);
  388. tagToServerSideClassName.put(value, key);
  389. }
  390. for (int i = 0; i < keyArray.length(); i++) {
  391. String key = keyArray.get(i).intern();
  392. int value = valueMap.getInt(key);
  393. widgetSet.ensureConnectorLoaded(value, this);
  394. }
  395. }
  396. public Integer getParentTag(int tag) {
  397. return componentInheritanceMap.get(tag);
  398. }
  399. public String getServerSideClassNameForTag(Integer tag) {
  400. return tagToServerSideClassName.get(tag);
  401. }
  402. String getUnknownServerClassNameByTag(int tag) {
  403. if (unknownComponents != null) {
  404. return unknownComponents.get(tag);
  405. }
  406. return null;
  407. }
  408. /**
  409. *
  410. * @param c
  411. */
  412. static void runWhenDependenciesLoaded(Command c) {
  413. if (dependenciesLoading == 0) {
  414. c.execute();
  415. } else {
  416. callbacks.add(c);
  417. }
  418. }
  419. static void startDependencyLoading() {
  420. dependenciesLoading++;
  421. }
  422. static void endDependencyLoading() {
  423. dependenciesLoading--;
  424. if (dependenciesLoading == 0 && !callbacks.isEmpty()) {
  425. for (Command cmd : callbacks) {
  426. cmd.execute();
  427. }
  428. callbacks.clear();
  429. } else if (dependenciesLoading == 0
  430. && !ConnectorBundleLoader.get().isBundleLoaded(
  431. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME)) {
  432. ConnectorBundleLoader.get().loadBundle(
  433. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME,
  434. new BundleLoadCallback() {
  435. @Override
  436. public void loaded() {
  437. // Nothing to do
  438. }
  439. @Override
  440. public void failed(Throwable reason) {
  441. VConsole.error(reason);
  442. }
  443. });
  444. }
  445. }
  446. @Override
  447. public void onModuleLoad() {
  448. // Prepare VConsole for debugging
  449. if (isDebugMode()) {
  450. Console console = GWT.create(Console.class);
  451. console.setQuietMode(isQuietDebugMode());
  452. console.init();
  453. VConsole.setImplementation(console);
  454. } else {
  455. VConsole.setImplementation((Console) GWT.create(NullConsole.class));
  456. }
  457. /*
  458. * Display some sort of error of exceptions in web mode to debug
  459. * console. After this, exceptions are reported to VConsole and possible
  460. * GWT hosted mode.
  461. */
  462. GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
  463. @Override
  464. public void onUncaughtException(Throwable e) {
  465. /*
  466. * Note in case of null console (without ?debug) we eat
  467. * exceptions. "a1 is not an object" style errors helps nobody,
  468. * especially end user. It does not work tells just as much.
  469. */
  470. VConsole.getImplementation().error(e);
  471. }
  472. });
  473. if (SuperDevMode.enableBasedOnParameter()) {
  474. // Do not start any application as super dev mode will refresh the
  475. // page once done compiling
  476. return;
  477. }
  478. registerCallback(GWT.getModuleName());
  479. }
  480. /**
  481. * Registers that callback that the bootstrap javascript uses to start
  482. * applications once the widgetset is loaded and all required information is
  483. * available
  484. *
  485. * @param widgetsetName
  486. * the name of this widgetset
  487. */
  488. public native static void registerCallback(String widgetsetName)
  489. /*-{
  490. var callbackHandler = $entry(@com.vaadin.client.ApplicationConfiguration::startApplication(Ljava/lang/String;));
  491. $wnd.vaadin.registerWidgetset(widgetsetName, callbackHandler);
  492. }-*/;
  493. /**
  494. * Checks if client side is in debug mode. Practically this is invoked by
  495. * adding ?debug parameter to URI.
  496. *
  497. * @return true if client side is currently been debugged
  498. */
  499. public static boolean isDebugMode() {
  500. return isDebugAvailable()
  501. && Window.Location.getParameter("debug") != null;
  502. }
  503. private native static boolean isDebugAvailable()
  504. /*-{
  505. if($wnd.vaadin.debug) {
  506. return true;
  507. } else {
  508. return false;
  509. }
  510. }-*/;
  511. /**
  512. * Checks whether debug logging should be quiet
  513. *
  514. * @return <code>true</code> if debug logging should be quiet
  515. */
  516. public static boolean isQuietDebugMode() {
  517. String debugParameter = Window.Location.getParameter("debug");
  518. return isDebugAvailable() && debugParameter != null
  519. && debugParameter.startsWith("q");
  520. }
  521. /**
  522. * Checks whether information from the web browser (e.g. uri fragment and
  523. * screen size) has been sent to the server.
  524. *
  525. * @return <code>true</code> if browser information has already been sent
  526. *
  527. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  528. */
  529. public boolean isBrowserDetailsSent() {
  530. return browserDetailsSent;
  531. }
  532. /**
  533. * Registers that the browser details have been sent.
  534. * {@link #isBrowserDetailsSent()} will return
  535. * <code> after this method has been invoked.
  536. */
  537. public void setBrowserDetailsSent() {
  538. browserDetailsSent = true;
  539. }
  540. /**
  541. * Checks whether the widget set version has been sent to the server. It is
  542. * sent in the first UIDL request.
  543. *
  544. * @return <code>true</code> if browser information has already been sent
  545. *
  546. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  547. */
  548. public boolean isWidgetsetVersionSent() {
  549. return widgetsetVersionSent;
  550. }
  551. /**
  552. * Registers that the widget set version has been sent to the server.
  553. */
  554. public void setWidgetsetVersionSent() {
  555. widgetsetVersionSent = true;
  556. }
  557. }