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

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