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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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.terminal.gwt.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.shared.ApplicationConstants;
  32. import com.vaadin.shared.ui.ui.UIConstants;
  33. import com.vaadin.terminal.gwt.client.metadata.BundleLoadCallback;
  34. import com.vaadin.terminal.gwt.client.metadata.ConnectorBundleLoader;
  35. import com.vaadin.terminal.gwt.client.metadata.NoDataException;
  36. import com.vaadin.terminal.gwt.client.metadata.TypeData;
  37. import com.vaadin.terminal.gwt.client.ui.UnknownComponentConnector;
  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 boolean useDebugIdInDom = true;
  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. public JavaScriptObject getVersionInfoJSObject() {
  260. return getJsoConfiguration(id).getVersionInfoJSObject();
  261. }
  262. public ErrorMessage getCommunicationError() {
  263. return communicationError;
  264. }
  265. public ErrorMessage getAuthorizationError() {
  266. return authorizationError;
  267. }
  268. /**
  269. * Reads the configuration values defined by the bootstrap javascript.
  270. */
  271. private void loadFromDOM() {
  272. JsoConfiguration jsoConfiguration = getJsoConfiguration(id);
  273. appUri = jsoConfiguration.getConfigString("appUri");
  274. if (appUri != null && !appUri.endsWith("/")) {
  275. appUri += '/';
  276. }
  277. themeUri = jsoConfiguration.getConfigString("themeUri");
  278. uiId = jsoConfiguration.getConfigInteger(UIConstants.UI_ID_PARAMETER)
  279. .intValue();
  280. // null -> true
  281. useDebugIdInDom = jsoConfiguration.getConfigBoolean("useDebugIdInDom") != Boolean.FALSE;
  282. // null -> false
  283. standalone = jsoConfiguration.getConfigBoolean("standalone") == Boolean.TRUE;
  284. communicationError = jsoConfiguration.getConfigError("comErrMsg");
  285. authorizationError = jsoConfiguration.getConfigError("authErrMsg");
  286. // boostrap sets initPending to false if it has sent the browser details
  287. if (jsoConfiguration.getConfigBoolean("initPending") == Boolean.FALSE) {
  288. setBrowserDetailsSent();
  289. }
  290. }
  291. /**
  292. * Starts the application with a given id by reading the configuration
  293. * options stored by the bootstrap javascript.
  294. *
  295. * @param applicationId
  296. * id of the application to load, this is also the id of the html
  297. * element into which the application should be rendered.
  298. */
  299. public static void startApplication(final String applicationId) {
  300. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  301. @Override
  302. public void execute() {
  303. ApplicationConfiguration appConf = getConfigFromDOM(applicationId);
  304. ApplicationConnection a = GWT
  305. .create(ApplicationConnection.class);
  306. a.init(widgetSet, appConf);
  307. a.start();
  308. runningApplications.add(a);
  309. }
  310. });
  311. }
  312. public static List<ApplicationConnection> getRunningApplications() {
  313. return runningApplications;
  314. }
  315. /**
  316. * Gets the configuration object for a specific application from the
  317. * bootstrap javascript.
  318. *
  319. * @param appId
  320. * the id of the application to get configuration data for
  321. * @return a native javascript object containing the configuration data
  322. */
  323. private native static JsoConfiguration getJsoConfiguration(String appId)
  324. /*-{
  325. return $wnd.vaadin.getApp(appId);
  326. }-*/;
  327. public static ApplicationConfiguration getConfigFromDOM(String appId) {
  328. ApplicationConfiguration conf = new ApplicationConfiguration();
  329. conf.setAppId(appId);
  330. conf.loadFromDOM();
  331. return conf;
  332. }
  333. public String getServletVersion() {
  334. return getJsoConfiguration(id).getVaadinVersion();
  335. }
  336. public String getApplicationVersion() {
  337. return getJsoConfiguration(id).getApplicationVersion();
  338. }
  339. public boolean useDebugIdInDOM() {
  340. return useDebugIdInDom;
  341. }
  342. public Class<? extends ServerConnector> getConnectorClassByEncodedTag(
  343. int tag) {
  344. Class<? extends ServerConnector> type = classes.get(tag);
  345. if (type == null && !classes.containsKey(tag)) {
  346. // Initialize if not already loaded
  347. Integer currentTag = Integer.valueOf(tag);
  348. while (type == null && currentTag != null) {
  349. String serverSideClassNameForTag = getServerSideClassNameForTag(currentTag);
  350. if (TypeData.hasIdentifier(serverSideClassNameForTag)) {
  351. try {
  352. type = (Class<? extends ServerConnector>) TypeData
  353. .getClass(serverSideClassNameForTag);
  354. } catch (NoDataException e) {
  355. throw new RuntimeException(e);
  356. }
  357. }
  358. currentTag = getParentTag(currentTag.intValue());
  359. }
  360. if (type == null) {
  361. type = UnknownComponentConnector.class;
  362. if (unknownComponents == null) {
  363. unknownComponents = new HashMap<Integer, String>();
  364. }
  365. unknownComponents.put(tag, getServerSideClassNameForTag(tag));
  366. }
  367. classes.put(tag, type);
  368. }
  369. return type;
  370. }
  371. public void addComponentInheritanceInfo(ValueMap valueMap) {
  372. JsArrayString keyArray = valueMap.getKeyArray();
  373. for (int i = 0; i < keyArray.length(); i++) {
  374. String key = keyArray.get(i);
  375. int value = valueMap.getInt(key);
  376. componentInheritanceMap.put(Integer.parseInt(key), value);
  377. }
  378. }
  379. public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
  380. JsArrayString keyArray = valueMap.getKeyArray();
  381. for (int i = 0; i < keyArray.length(); i++) {
  382. String key = keyArray.get(i).intern();
  383. int value = valueMap.getInt(key);
  384. tagToServerSideClassName.put(value, key);
  385. }
  386. for (int i = 0; i < keyArray.length(); i++) {
  387. String key = keyArray.get(i).intern();
  388. int value = valueMap.getInt(key);
  389. widgetSet.ensureConnectorLoaded(value, this);
  390. }
  391. }
  392. public Integer getParentTag(int tag) {
  393. return componentInheritanceMap.get(tag);
  394. }
  395. public String getServerSideClassNameForTag(Integer tag) {
  396. return tagToServerSideClassName.get(tag);
  397. }
  398. String getUnknownServerClassNameByTag(int tag) {
  399. if (unknownComponents != null) {
  400. return unknownComponents.get(tag);
  401. }
  402. return null;
  403. }
  404. /**
  405. *
  406. * @param c
  407. */
  408. static void runWhenDependenciesLoaded(Command c) {
  409. if (dependenciesLoading == 0) {
  410. c.execute();
  411. } else {
  412. callbacks.add(c);
  413. }
  414. }
  415. static void startDependencyLoading() {
  416. dependenciesLoading++;
  417. }
  418. static void endDependencyLoading() {
  419. dependenciesLoading--;
  420. if (dependenciesLoading == 0 && !callbacks.isEmpty()) {
  421. for (Command cmd : callbacks) {
  422. cmd.execute();
  423. }
  424. callbacks.clear();
  425. } else if (dependenciesLoading == 0
  426. && !ConnectorBundleLoader.get().isBundleLoaded(
  427. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME)) {
  428. ConnectorBundleLoader.get().loadBundle(
  429. ConnectorBundleLoader.DEFERRED_BUNDLE_NAME,
  430. new BundleLoadCallback() {
  431. @Override
  432. public void loaded() {
  433. // Nothing to do
  434. }
  435. @Override
  436. public void failed(Throwable reason) {
  437. VConsole.error(reason);
  438. }
  439. });
  440. }
  441. }
  442. @Override
  443. public void onModuleLoad() {
  444. // Prepare VConsole for debugging
  445. if (isDebugMode()) {
  446. Console console = GWT.create(Console.class);
  447. console.setQuietMode(isQuietDebugMode());
  448. console.init();
  449. VConsole.setImplementation(console);
  450. } else {
  451. VConsole.setImplementation((Console) GWT.create(NullConsole.class));
  452. }
  453. /*
  454. * Display some sort of error of exceptions in web mode to debug
  455. * console. After this, exceptions are reported to VConsole and possible
  456. * GWT hosted mode.
  457. */
  458. GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
  459. @Override
  460. public void onUncaughtException(Throwable e) {
  461. /*
  462. * Note in case of null console (without ?debug) we eat
  463. * exceptions. "a1 is not an object" style errors helps nobody,
  464. * especially end user. It does not work tells just as much.
  465. */
  466. VConsole.getImplementation().error(e);
  467. }
  468. });
  469. if (SuperDevMode.enableBasedOnParameter()) {
  470. // Do not start any application as super dev mode will refresh the
  471. // page once done compiling
  472. return;
  473. }
  474. registerCallback(GWT.getModuleName());
  475. }
  476. /**
  477. * Registers that callback that the bootstrap javascript uses to start
  478. * applications once the widgetset is loaded and all required information is
  479. * available
  480. *
  481. * @param widgetsetName
  482. * the name of this widgetset
  483. */
  484. public native static void registerCallback(String widgetsetName)
  485. /*-{
  486. var callbackHandler = $entry(@com.vaadin.terminal.gwt.client.ApplicationConfiguration::startApplication(Ljava/lang/String;));
  487. $wnd.vaadin.registerWidgetset(widgetsetName, callbackHandler);
  488. }-*/;
  489. /**
  490. * Checks if client side is in debug mode. Practically this is invoked by
  491. * adding ?debug parameter to URI.
  492. *
  493. * @return true if client side is currently been debugged
  494. */
  495. public static boolean isDebugMode() {
  496. return isDebugAvailable()
  497. && Window.Location.getParameter("debug") != null;
  498. }
  499. private native static boolean isDebugAvailable()
  500. /*-{
  501. if($wnd.vaadin.debug) {
  502. return true;
  503. } else {
  504. return false;
  505. }
  506. }-*/;
  507. /**
  508. * Checks whether debug logging should be quiet
  509. *
  510. * @return <code>true</code> if debug logging should be quiet
  511. */
  512. public static boolean isQuietDebugMode() {
  513. String debugParameter = Window.Location.getParameter("debug");
  514. return isDebugAvailable() && debugParameter != null
  515. && debugParameter.startsWith("q");
  516. }
  517. /**
  518. * Checks whether information from the web browser (e.g. uri fragment and
  519. * screen size) has been sent to the server.
  520. *
  521. * @return <code>true</code> if browser information has already been sent
  522. *
  523. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  524. */
  525. public boolean isBrowserDetailsSent() {
  526. return browserDetailsSent;
  527. }
  528. /**
  529. * Registers that the browser details have been sent.
  530. * {@link #isBrowserDetailsSent()} will return
  531. * <code> after this method has been invoked.
  532. */
  533. public void setBrowserDetailsSent() {
  534. browserDetailsSent = true;
  535. }
  536. /**
  537. * Checks whether the widget set version has been sent to the server. It is
  538. * sent in the first UIDL request.
  539. *
  540. * @return <code>true</code> if browser information has already been sent
  541. *
  542. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  543. */
  544. public boolean isWidgetsetVersionSent() {
  545. return widgetsetVersionSent;
  546. }
  547. /**
  548. * Registers that the widget set version has been sent to the server.
  549. */
  550. public void setWidgetsetVersionSent() {
  551. widgetsetVersionSent = true;
  552. }
  553. }