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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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.Timer;
  31. import com.google.gwt.user.client.Window;
  32. import com.vaadin.shared.ApplicationConstants;
  33. import com.vaadin.terminal.gwt.client.ui.UnknownComponentConnector;
  34. public class ApplicationConfiguration implements EntryPoint {
  35. /**
  36. * Helper class for reading configuration options from the bootstap
  37. * javascript
  38. *
  39. * @since 7.0
  40. */
  41. private static class JsoConfiguration extends JavaScriptObject {
  42. protected JsoConfiguration() {
  43. // JSO Constructor
  44. }
  45. /**
  46. * Reads a configuration parameter as a string. Please note that the
  47. * javascript value of the parameter should also be a string, or else an
  48. * undefined exception may be thrown.
  49. *
  50. * @param name
  51. * name of the configuration parameter
  52. * @return value of the configuration parameter, or <code>null</code> if
  53. * not defined
  54. */
  55. private native String getConfigString(String name)
  56. /*-{
  57. var value = this.getConfig(name);
  58. if (value === null || value === undefined) {
  59. return null;
  60. } else {
  61. return value +"";
  62. }
  63. }-*/;
  64. /**
  65. * Reads a configuration parameter as a boolean object. Please note that
  66. * the javascript value of the parameter should also be a boolean, or
  67. * else an undefined exception may be thrown.
  68. *
  69. * @param name
  70. * name of the configuration parameter
  71. * @return boolean value of the configuration paramter, or
  72. * <code>null</code> if no value is defined
  73. */
  74. private native Boolean getConfigBoolean(String name)
  75. /*-{
  76. var value = this.getConfig(name);
  77. if (value === null || value === undefined) {
  78. return null;
  79. } else {
  80. // $entry not needed as function is not exported
  81. return @java.lang.Boolean::valueOf(Z)(value);
  82. }
  83. }-*/;
  84. /**
  85. * Reads a configuration parameter as an integer object. Please note
  86. * that the javascript value of the parameter should also be an integer,
  87. * or else an undefined exception may be thrown.
  88. *
  89. * @param name
  90. * name of the configuration parameter
  91. * @return integer value of the configuration paramter, or
  92. * <code>null</code> if no value is defined
  93. */
  94. private native Integer getConfigInteger(String name)
  95. /*-{
  96. var value = this.getConfig(name);
  97. if (value === null || value === undefined) {
  98. return null;
  99. } else {
  100. // $entry not needed as function is not exported
  101. return @java.lang.Integer::valueOf(I)(value);
  102. }
  103. }-*/;
  104. /**
  105. * Reads a configuration parameter as an {@link ErrorMessage} object.
  106. * Please note that the javascript value of the parameter should also be
  107. * an object with appropriate fields, or else an undefined exception may
  108. * be thrown when calling this method or when calling methods on the
  109. * returned object.
  110. *
  111. * @param name
  112. * name of the configuration parameter
  113. * @return error message with the given name, or <code>null</code> if no
  114. * value is defined
  115. */
  116. private native ErrorMessage getConfigError(String name)
  117. /*-{
  118. return this.getConfig(name);
  119. }-*/;
  120. /**
  121. * Returns a native javascript object containing version information
  122. * from the server.
  123. *
  124. * @return a javascript object with the version information
  125. */
  126. private native JavaScriptObject getVersionInfoJSObject()
  127. /*-{
  128. return this.getConfig("versionInfo");
  129. }-*/;
  130. /**
  131. * Gets the version of the Vaadin framework used on the server.
  132. *
  133. * @return a string with the version
  134. *
  135. * @see com.vaadin.terminal.gwt.server.AbstractApplicationServlet#VERSION
  136. */
  137. private native String getVaadinVersion()
  138. /*-{
  139. return this.getConfig("versionInfo").vaadinVersion;
  140. }-*/;
  141. /**
  142. * Gets the version of the application running on the server.
  143. *
  144. * @return a string with the application version
  145. *
  146. * @see com.vaadin.Application#getVersion()
  147. */
  148. private native String getApplicationVersion()
  149. /*-{
  150. return this.getConfig("versionInfo").applicationVersion;
  151. }-*/;
  152. private native String getUIDL()
  153. /*-{
  154. return this.getConfig("uidl");
  155. }-*/;
  156. }
  157. /**
  158. * Wraps a native javascript object containing fields for an error message
  159. *
  160. * @since 7.0
  161. */
  162. public static final class ErrorMessage extends JavaScriptObject {
  163. protected ErrorMessage() {
  164. // JSO constructor
  165. }
  166. public final native String getCaption()
  167. /*-{
  168. return this.caption;
  169. }-*/;
  170. public final native String getMessage()
  171. /*-{
  172. return this.message;
  173. }-*/;
  174. public final native String getUrl()
  175. /*-{
  176. return this.url;
  177. }-*/;
  178. }
  179. private static WidgetSet widgetSet = GWT.create(WidgetSet.class);
  180. private String id;
  181. private String themeUri;
  182. private String appUri;
  183. private int rootId;
  184. private boolean standalone;
  185. private ErrorMessage communicationError;
  186. private ErrorMessage authorizationError;
  187. private boolean useDebugIdInDom = true;
  188. private int heartbeatInterval;
  189. private HashMap<Integer, String> unknownComponents;
  190. private Class<? extends ServerConnector>[] classes = new Class[1024];
  191. private boolean browserDetailsSent = false;
  192. private boolean widgetsetVersionSent = false;
  193. static// TODO consider to make this hashmap per application
  194. LinkedList<Command> callbacks = new LinkedList<Command>();
  195. private static int dependenciesLoading;
  196. private static ArrayList<ApplicationConnection> runningApplications = new ArrayList<ApplicationConnection>();
  197. private Map<Integer, Integer> componentInheritanceMap = new HashMap<Integer, Integer>();
  198. private Map<Integer, String> tagToServerSideClassName = new HashMap<Integer, String>();
  199. public boolean usePortletURLs() {
  200. return getPortletResourceUrl() != null;
  201. }
  202. public String getPortletResourceUrl() {
  203. return getJsoConfiguration(id).getConfigString(
  204. ApplicationConstants.PORTLET_RESOUCE_URL_BASE);
  205. }
  206. public String getRootPanelId() {
  207. return id;
  208. }
  209. /**
  210. * Gets the application base URI. Using this other than as the download
  211. * action URI can cause problems in Portlet 2.0 deployments.
  212. *
  213. * @return application base URI
  214. */
  215. public String getApplicationUri() {
  216. return appUri;
  217. }
  218. public String getThemeName() {
  219. String uri = getThemeUri();
  220. String themeName = uri.substring(uri.lastIndexOf('/'));
  221. themeName = themeName.replaceAll("[^a-zA-Z0-9]", "");
  222. return themeName;
  223. }
  224. public String getThemeUri() {
  225. return themeUri;
  226. }
  227. public void setAppId(String appId) {
  228. id = appId;
  229. }
  230. /**
  231. * Gets the initial UIDL from the DOM, if it was provided during the init
  232. * process.
  233. *
  234. * @return
  235. */
  236. public String getUIDL() {
  237. return getJsoConfiguration(id).getUIDL();
  238. }
  239. /**
  240. * @return true if the application is served by std. Vaadin servlet and is
  241. * considered to be the only or main content of the host page.
  242. */
  243. public boolean isStandalone() {
  244. return standalone;
  245. }
  246. /**
  247. * Gets the root if of this application instance. The root id should be
  248. * included in every request originating from this instance in order to
  249. * associate it with the right Root instance on the server.
  250. *
  251. * @return the root id
  252. */
  253. public int getRootId() {
  254. return rootId;
  255. }
  256. /**
  257. * @return The interval in seconds between heartbeat requests, or a
  258. * non-positive number if heartbeat is disabled.
  259. */
  260. public int getHeartbeatInterval() {
  261. return heartbeatInterval;
  262. }
  263. public JavaScriptObject getVersionInfoJSObject() {
  264. return getJsoConfiguration(id).getVersionInfoJSObject();
  265. }
  266. public ErrorMessage getCommunicationError() {
  267. return communicationError;
  268. }
  269. public ErrorMessage getAuthorizationError() {
  270. return authorizationError;
  271. }
  272. /**
  273. * Reads the configuration values defined by the bootstrap javascript.
  274. */
  275. private void loadFromDOM() {
  276. JsoConfiguration jsoConfiguration = getJsoConfiguration(id);
  277. appUri = jsoConfiguration.getConfigString("appUri");
  278. if (appUri != null && !appUri.endsWith("/")) {
  279. appUri += '/';
  280. }
  281. themeUri = jsoConfiguration.getConfigString("themeUri");
  282. rootId = jsoConfiguration.getConfigInteger("rootId").intValue();
  283. // null -> true
  284. useDebugIdInDom = jsoConfiguration.getConfigBoolean("useDebugIdInDom") != Boolean.FALSE;
  285. // null -> false
  286. standalone = jsoConfiguration.getConfigBoolean("standalone") == Boolean.TRUE;
  287. heartbeatInterval = jsoConfiguration
  288. .getConfigInteger("heartbeatInterval");
  289. communicationError = jsoConfiguration.getConfigError("comErrMsg");
  290. authorizationError = jsoConfiguration.getConfigError("authErrMsg");
  291. // boostrap sets initPending to false if it has sent the browser details
  292. if (jsoConfiguration.getConfigBoolean("initPending") == Boolean.FALSE) {
  293. setBrowserDetailsSent();
  294. }
  295. }
  296. /**
  297. * Starts the application with a given id by reading the configuration
  298. * options stored by the bootstrap javascript.
  299. *
  300. * @param applicationId
  301. * id of the application to load, this is also the id of the html
  302. * element into which the application should be rendered.
  303. */
  304. public static void startApplication(final String applicationId) {
  305. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  306. @Override
  307. public void execute() {
  308. ApplicationConfiguration appConf = getConfigFromDOM(applicationId);
  309. ApplicationConnection a = GWT
  310. .create(ApplicationConnection.class);
  311. a.init(widgetSet, appConf);
  312. a.start();
  313. runningApplications.add(a);
  314. }
  315. });
  316. }
  317. public static List<ApplicationConnection> getRunningApplications() {
  318. return runningApplications;
  319. }
  320. /**
  321. * Gets the configuration object for a specific application from the
  322. * bootstrap javascript.
  323. *
  324. * @param appId
  325. * the id of the application to get configuration data for
  326. * @return a native javascript object containing the configuration data
  327. */
  328. private native static JsoConfiguration getJsoConfiguration(String appId)
  329. /*-{
  330. return $wnd.vaadin.getApp(appId);
  331. }-*/;
  332. public static ApplicationConfiguration getConfigFromDOM(String appId) {
  333. ApplicationConfiguration conf = new ApplicationConfiguration();
  334. conf.setAppId(appId);
  335. conf.loadFromDOM();
  336. return conf;
  337. }
  338. public String getServletVersion() {
  339. return getJsoConfiguration(id).getVaadinVersion();
  340. }
  341. public String getApplicationVersion() {
  342. return getJsoConfiguration(id).getApplicationVersion();
  343. }
  344. public boolean useDebugIdInDOM() {
  345. return useDebugIdInDom;
  346. }
  347. public Class<? extends ServerConnector> getConnectorClassByEncodedTag(
  348. int tag) {
  349. try {
  350. return classes[tag];
  351. } catch (Exception e) {
  352. // component was not present in mappings
  353. return UnknownComponentConnector.class;
  354. }
  355. }
  356. public void addComponentInheritanceInfo(ValueMap valueMap) {
  357. JsArrayString keyArray = valueMap.getKeyArray();
  358. for (int i = 0; i < keyArray.length(); i++) {
  359. String key = keyArray.get(i);
  360. int value = valueMap.getInt(key);
  361. componentInheritanceMap.put(Integer.parseInt(key), value);
  362. }
  363. }
  364. public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
  365. JsArrayString keyArray = valueMap.getKeyArray();
  366. for (int i = 0; i < keyArray.length(); i++) {
  367. String key = keyArray.get(i).intern();
  368. int value = valueMap.getInt(key);
  369. tagToServerSideClassName.put(value, key);
  370. }
  371. for (int i = 0; i < keyArray.length(); i++) {
  372. String key = keyArray.get(i).intern();
  373. int value = valueMap.getInt(key);
  374. classes[value] = widgetSet.getConnectorClassByTag(value, this);
  375. if (classes[value] == UnknownComponentConnector.class) {
  376. if (unknownComponents == null) {
  377. unknownComponents = new HashMap<Integer, String>();
  378. }
  379. unknownComponents.put(value, key);
  380. }
  381. }
  382. }
  383. public Integer getParentTag(int tag) {
  384. return componentInheritanceMap.get(tag);
  385. }
  386. public String getServerSideClassNameForTag(Integer tag) {
  387. return tagToServerSideClassName.get(tag);
  388. }
  389. String getUnknownServerClassNameByTag(int tag) {
  390. if (unknownComponents != null) {
  391. return unknownComponents.get(tag);
  392. }
  393. return null;
  394. }
  395. /**
  396. *
  397. * @param c
  398. */
  399. static void runWhenDependenciesLoaded(Command c) {
  400. if (dependenciesLoading == 0) {
  401. c.execute();
  402. } else {
  403. callbacks.add(c);
  404. }
  405. }
  406. static void startDependencyLoading() {
  407. dependenciesLoading++;
  408. }
  409. static void endDependencyLoading() {
  410. dependenciesLoading--;
  411. if (dependenciesLoading == 0 && !callbacks.isEmpty()) {
  412. for (Command cmd : callbacks) {
  413. cmd.execute();
  414. }
  415. callbacks.clear();
  416. } else if (dependenciesLoading == 0 && deferredWidgetLoader != null) {
  417. deferredWidgetLoader.trigger();
  418. }
  419. }
  420. /*
  421. * This loop loads widget implementation that should be loaded deferred.
  422. */
  423. static class DeferredWidgetLoader extends Timer {
  424. private static final int FREE_LIMIT = 4;
  425. private static final int FREE_CHECK_TIMEOUT = 100;
  426. int communicationFree = 0;
  427. int nextWidgetIndex = 0;
  428. private boolean pending;
  429. public DeferredWidgetLoader() {
  430. schedule(5000);
  431. }
  432. public void trigger() {
  433. if (!pending) {
  434. schedule(FREE_CHECK_TIMEOUT);
  435. }
  436. }
  437. @Override
  438. public void schedule(int delayMillis) {
  439. super.schedule(delayMillis);
  440. pending = true;
  441. }
  442. @Override
  443. public void run() {
  444. pending = false;
  445. if (!isBusy()) {
  446. Class<? extends ServerConnector> nextType = getNextType();
  447. if (nextType == null) {
  448. // ensured that all widgets are loaded
  449. deferredWidgetLoader = null;
  450. } else {
  451. communicationFree = 0;
  452. widgetSet.loadImplementation(nextType);
  453. }
  454. } else {
  455. schedule(FREE_CHECK_TIMEOUT);
  456. }
  457. }
  458. private Class<? extends ServerConnector> getNextType() {
  459. Class<? extends ServerConnector>[] deferredLoadedConnectors = widgetSet
  460. .getDeferredLoadedConnectors();
  461. if (deferredLoadedConnectors.length <= nextWidgetIndex) {
  462. return null;
  463. } else {
  464. return deferredLoadedConnectors[nextWidgetIndex++];
  465. }
  466. }
  467. private boolean isBusy() {
  468. if (dependenciesLoading > 0) {
  469. communicationFree = 0;
  470. return true;
  471. }
  472. for (ApplicationConnection app : runningApplications) {
  473. if (app.hasActiveRequest()) {
  474. // if an UIDL request or widget loading is active, mark as
  475. // busy
  476. communicationFree = 0;
  477. return true;
  478. }
  479. }
  480. communicationFree++;
  481. return communicationFree < FREE_LIMIT;
  482. }
  483. }
  484. private static DeferredWidgetLoader deferredWidgetLoader;
  485. @Override
  486. public void onModuleLoad() {
  487. // Prepare VConsole for debugging
  488. if (isDebugMode()) {
  489. Console console = GWT.create(Console.class);
  490. console.setQuietMode(isQuietDebugMode());
  491. console.init();
  492. VConsole.setImplementation(console);
  493. } else {
  494. VConsole.setImplementation((Console) GWT.create(NullConsole.class));
  495. }
  496. /*
  497. * Display some sort of error of exceptions in web mode to debug
  498. * console. After this, exceptions are reported to VConsole and possible
  499. * GWT hosted mode.
  500. */
  501. GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
  502. @Override
  503. public void onUncaughtException(Throwable e) {
  504. /*
  505. * Note in case of null console (without ?debug) we eat
  506. * exceptions. "a1 is not an object" style errors helps nobody,
  507. * especially end user. It does not work tells just as much.
  508. */
  509. VConsole.getImplementation().error(e);
  510. }
  511. });
  512. if (SuperDevMode.enableBasedOnParameter()) {
  513. // Do not start any application as super dev mode will refresh the
  514. // page once done compiling
  515. return;
  516. }
  517. registerCallback(GWT.getModuleName());
  518. deferredWidgetLoader = new DeferredWidgetLoader();
  519. }
  520. /**
  521. * Registers that callback that the bootstrap javascript uses to start
  522. * applications once the widgetset is loaded and all required information is
  523. * available
  524. *
  525. * @param widgetsetName
  526. * the name of this widgetset
  527. */
  528. public native static void registerCallback(String widgetsetName)
  529. /*-{
  530. var callbackHandler = $entry(@com.vaadin.terminal.gwt.client.ApplicationConfiguration::startApplication(Ljava/lang/String;));
  531. $wnd.vaadin.registerWidgetset(widgetsetName, callbackHandler);
  532. }-*/;
  533. /**
  534. * Checks if client side is in debug mode. Practically this is invoked by
  535. * adding ?debug parameter to URI.
  536. *
  537. * @return true if client side is currently been debugged
  538. */
  539. public static boolean isDebugMode() {
  540. return isDebugAvailable()
  541. && Window.Location.getParameter("debug") != null;
  542. }
  543. private native static boolean isDebugAvailable()
  544. /*-{
  545. if($wnd.vaadin.debug) {
  546. return true;
  547. } else {
  548. return false;
  549. }
  550. }-*/;
  551. /**
  552. * Checks whether debug logging should be quiet
  553. *
  554. * @return <code>true</code> if debug logging should be quiet
  555. */
  556. public static boolean isQuietDebugMode() {
  557. String debugParameter = Window.Location.getParameter("debug");
  558. return isDebugAvailable() && debugParameter != null
  559. && debugParameter.startsWith("q");
  560. }
  561. /**
  562. * Checks whether information from the web browser (e.g. uri fragment and
  563. * screen size) has been sent to the server.
  564. *
  565. * @return <code>true</code> if browser information has already been sent
  566. *
  567. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  568. */
  569. public boolean isBrowserDetailsSent() {
  570. return browserDetailsSent;
  571. }
  572. /**
  573. * Registers that the browser details have been sent.
  574. * {@link #isBrowserDetailsSent()} will return
  575. * <code> after this method has been invoked.
  576. */
  577. public void setBrowserDetailsSent() {
  578. browserDetailsSent = true;
  579. }
  580. /**
  581. * Checks whether the widget set version has been sent to the server. It is
  582. * sent in the first UIDL request.
  583. *
  584. * @return <code>true</code> if browser information has already been sent
  585. *
  586. * @see ApplicationConnection#getNativeBrowserDetailsParameters(String)
  587. */
  588. public boolean isWidgetsetVersionSent() {
  589. return widgetsetVersionSent;
  590. }
  591. /**
  592. * Registers that the widget set version has been sent to the server.
  593. */
  594. public void setWidgetsetVersionSent() {
  595. widgetsetVersionSent = true;
  596. }
  597. }