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.

DesignContext.java 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /*
  2. * Copyright 2000-2016 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.ui.declarative;
  17. import java.io.Serializable;
  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.concurrent.ConcurrentHashMap;
  25. import org.jsoup.nodes.Attributes;
  26. import org.jsoup.nodes.Document;
  27. import org.jsoup.nodes.Element;
  28. import org.jsoup.nodes.Node;
  29. import com.vaadin.annotations.DesignRoot;
  30. import com.vaadin.server.Constants;
  31. import com.vaadin.server.DeploymentConfiguration;
  32. import com.vaadin.server.VaadinService;
  33. import com.vaadin.ui.Component;
  34. import com.vaadin.ui.HasComponents;
  35. import com.vaadin.ui.declarative.Design.ComponentFactory;
  36. import com.vaadin.ui.declarative.Design.ComponentMapper;
  37. /**
  38. * This class contains contextual information that is collected when a component
  39. * tree is constructed based on HTML design template. This information includes
  40. * mappings from local ids, global ids and captions to components , as well as a
  41. * mapping between prefixes and package names (such as "vaadin" ->
  42. * "com.vaadin.ui").
  43. *
  44. * Versions prior to 7.6 use "v" as the default prefix. Versions starting with
  45. * 7.6 support reading designs with either "v" or "vaadin" as the prefix, but
  46. * only write "vaadin" by default. Writing with the legacy prefix can be
  47. * activated with the property or context parameter
  48. * {@link Constants#SERVLET_PARAMETER_LEGACY_DESIGN_PREFIX}.
  49. *
  50. * @since 7.4
  51. * @author Vaadin Ltd
  52. */
  53. public class DesignContext implements Serializable {
  54. private static final String LEGACY_PREFIX = "v";
  55. private static final String VAADIN_PREFIX = "vaadin";
  56. private static final String VAADIN7_PREFIX = "vaadin7";
  57. private static final String VAADIN_UI_PACKAGE = "com.vaadin.ui";
  58. private static final String VAADIN7_UI_PACKAGE = "com.vaadin.v7.ui";
  59. // cache for object instances
  60. private static Map<Class<?>, Component> instanceCache = new ConcurrentHashMap<Class<?>, Component>();
  61. // The root component of the component hierarchy
  62. private Component rootComponent = null;
  63. // Attribute names for global id and caption and the prefix name for a local
  64. // id
  65. public static final String ID_ATTRIBUTE = "id";
  66. public static final String CAPTION_ATTRIBUTE = "caption";
  67. public static final String LOCAL_ID_ATTRIBUTE = "_id";
  68. // Mappings from ids to components. Modified when reading from design.
  69. private Map<String, Component> idToComponent = new HashMap<String, Component>();
  70. private Map<String, Component> localIdToComponent = new HashMap<String, Component>();
  71. private Map<String, Component> captionToComponent = new HashMap<String, Component>();
  72. // Mapping from components to local ids. Accessed when writing to
  73. // design. Modified when reading from design.
  74. private Map<Component, String> componentToLocalId = new HashMap<Component, String>();
  75. private Document doc; // required for calling createElement(String)
  76. // namespace mappings
  77. private Map<String, String> packageToPrefix = new HashMap<String, String>();
  78. private Map<String, String> prefixToPackage = new HashMap<String, String>();
  79. private final Map<Component, Map<String, String>> customAttributes = new HashMap<Component, Map<String, String>>();
  80. // component creation listeners
  81. private List<ComponentCreationListener> listeners = new ArrayList<ComponentCreationListener>();
  82. private ShouldWriteDataDelegate shouldWriteDataDelegate = ShouldWriteDataDelegate.DEFAULT;
  83. // this cannot be static because of testability issues
  84. private Boolean legacyDesignPrefix = null;
  85. public DesignContext(Document doc) {
  86. this.doc = doc;
  87. // Initialize the mapping between prefixes and package names.
  88. if (isLegacyPrefixEnabled()) {
  89. addPackagePrefix(LEGACY_PREFIX, VAADIN_UI_PACKAGE);
  90. prefixToPackage.put(VAADIN_PREFIX, VAADIN_UI_PACKAGE);
  91. } else {
  92. addPackagePrefix(VAADIN_PREFIX, VAADIN_UI_PACKAGE);
  93. prefixToPackage.put(LEGACY_PREFIX, VAADIN_UI_PACKAGE);
  94. }
  95. addPackagePrefix(VAADIN7_PREFIX, VAADIN7_UI_PACKAGE);
  96. }
  97. public DesignContext() {
  98. this(new Document(""));
  99. }
  100. /**
  101. * Returns a component having the specified local id. If no component is
  102. * found, returns null.
  103. *
  104. * @param localId
  105. * The local id of the component
  106. * @return a component whose local id equals localId
  107. */
  108. public Component getComponentByLocalId(String localId) {
  109. return localIdToComponent.get(localId);
  110. }
  111. /**
  112. * Returns a component having the specified global id. If no component is
  113. * found, returns null.
  114. *
  115. * @param globalId
  116. * The global id of the component
  117. * @return a component whose global id equals globalId
  118. */
  119. public Component getComponentById(String globalId) {
  120. return idToComponent.get(globalId);
  121. }
  122. /**
  123. * Returns a component having the specified caption. If no component is
  124. * found, returns null.
  125. *
  126. * @param caption
  127. * The caption of the component
  128. * @return a component whose caption equals the caption given as a parameter
  129. */
  130. public Component getComponentByCaption(String caption) {
  131. return captionToComponent.get(caption);
  132. }
  133. /**
  134. * Creates a mapping between the given global id and the component. Returns
  135. * true if globalId was already mapped to some component. Otherwise returns
  136. * false. Also sets the id of the component to globalId.
  137. *
  138. * If there is a mapping from the component to a global id (gid) different
  139. * from globalId, the mapping from gid to component is removed.
  140. *
  141. * If the string was mapped to a component c different from the given
  142. * component, the mapping from c to the string is removed. Similarly, if
  143. * component was mapped to some string s different from globalId, the
  144. * mapping from s to component is removed.
  145. *
  146. * @param globalId
  147. * The new global id of the component.
  148. * @param component
  149. * The component whose global id is to be set.
  150. * @return true, if there already was a global id mapping from the string to
  151. * some component.
  152. */
  153. private boolean mapId(String globalId, Component component) {
  154. Component oldComponent = idToComponent.get(globalId);
  155. if (oldComponent != null && !oldComponent.equals(component)) {
  156. oldComponent.setId(null);
  157. }
  158. String oldGID = component.getId();
  159. if (oldGID != null && !oldGID.equals(globalId)) {
  160. idToComponent.remove(oldGID);
  161. }
  162. component.setId(globalId);
  163. idToComponent.put(globalId, component);
  164. return oldComponent != null && !oldComponent.equals(component);
  165. }
  166. /**
  167. * Creates a mapping between the given local id and the component. Returns
  168. * true if localId was already mapped to some component or if component was
  169. * mapped to some string. Otherwise returns false.
  170. *
  171. * If the string was mapped to a component c different from the given
  172. * component, the mapping from c to the string is removed. Similarly, if
  173. * component was mapped to some string s different from localId, the mapping
  174. * from s to component is removed.
  175. *
  176. * @since 7.5.0
  177. *
  178. * @param component
  179. * The component whose local id is to be set.
  180. * @param localId
  181. * The new local id of the component.
  182. *
  183. * @return true, if there already was a local id mapping from the string to
  184. * some component or from the component to some string. Otherwise
  185. * returns false.
  186. */
  187. public boolean setComponentLocalId(Component component, String localId) {
  188. return twoWayMap(localId, component, localIdToComponent,
  189. componentToLocalId);
  190. }
  191. /**
  192. * Returns the local id for a component.
  193. *
  194. * @since 7.5.0
  195. *
  196. * @param component
  197. * The component whose local id to get.
  198. * @return the local id of the component, or null if the component has no
  199. * local id assigned
  200. */
  201. public String getComponentLocalId(Component component) {
  202. return componentToLocalId.get(component);
  203. }
  204. /**
  205. * Creates a mapping between the given caption and the component. Returns
  206. * true if caption was already mapped to some component.
  207. *
  208. * Note that unlike mapGlobalId, if some component already has the given
  209. * caption, the caption is not cleared from the component. This allows
  210. * non-unique captions. However, only one of the components corresponding to
  211. * a given caption can be found using the map captionToComponent. Hence, any
  212. * captions that are used to identify an object should be unique.
  213. *
  214. * @param caption
  215. * The new caption of the component.
  216. * @param component
  217. * The component whose caption is to be set.
  218. * @return true, if there already was a caption mapping from the string to
  219. * some component.
  220. */
  221. private boolean mapCaption(String caption, Component component) {
  222. return captionToComponent.put(caption, component) != null;
  223. }
  224. /**
  225. * Creates a two-way mapping between key and value, i.e. adds key -> value
  226. * to keyToValue and value -> key to valueToKey. If key was mapped to a
  227. * value v different from the given value, the mapping from v to key is
  228. * removed. Similarly, if value was mapped to some key k different from key,
  229. * the mapping from k to value is removed.
  230. *
  231. * Returns true if there already was a mapping from key to some value v or
  232. * if there was a mapping from value to some key k. Otherwise returns false.
  233. *
  234. * @param key
  235. * The new key in keyToValue.
  236. * @param value
  237. * The new value in keyToValue.
  238. * @param keyToValue
  239. * A map from keys to values.
  240. * @param valueToKey
  241. * A map from values to keys.
  242. * @return whether there already was some mapping from key to a value or
  243. * from value to a key.
  244. */
  245. private <S, T> boolean twoWayMap(S key, T value, Map<S, T> keyToValue,
  246. Map<T, S> valueToKey) {
  247. T oldValue = keyToValue.put(key, value);
  248. if (oldValue != null && !oldValue.equals(value)) {
  249. valueToKey.remove(oldValue);
  250. }
  251. S oldKey = valueToKey.put(value, key);
  252. if (oldKey != null && !oldKey.equals(key)) {
  253. keyToValue.remove(oldKey);
  254. }
  255. return oldValue != null || oldKey != null;
  256. }
  257. /**
  258. * Creates a two-way mapping between a prefix and a package name.
  259. *
  260. * Note that modifying the mapping for {@value #VAADIN_UI_PACKAGE} may
  261. * invalidate the backwards compatibility mechanism supporting reading such
  262. * components with either {@value #LEGACY_PREFIX} or {@value #VAADIN_PREFIX}
  263. * as prefix.
  264. *
  265. * @param prefix
  266. * the prefix name without an ending dash (for instance, "vaadin"
  267. * is by default used for "com.vaadin.ui")
  268. * @param packageName
  269. * the name of the package corresponding to prefix
  270. *
  271. * @see #getPackagePrefixes()
  272. * @see #getPackagePrefix(String)
  273. * @see #getPackage(String)
  274. * @since 7.5.0
  275. */
  276. public void addPackagePrefix(String prefix, String packageName) {
  277. twoWayMap(prefix, packageName, prefixToPackage, packageToPrefix);
  278. }
  279. /**
  280. * Gets the prefix mapping for a given package, or <code>null</code> if
  281. * there is no mapping for the package.
  282. *
  283. * @see #addPackagePrefix(String, String)
  284. * @see #getPackagePrefixes()
  285. *
  286. * @since 7.5.0
  287. * @param packageName
  288. * the package name to get a prefix for
  289. * @return the prefix for the package, or <code>null</code> if no prefix is
  290. * registered
  291. */
  292. public String getPackagePrefix(String packageName) {
  293. if (VAADIN_UI_PACKAGE.equals(packageName)) {
  294. return isLegacyPrefixEnabled() ? LEGACY_PREFIX : VAADIN_PREFIX;
  295. } else {
  296. return packageToPrefix.get(packageName);
  297. }
  298. }
  299. /**
  300. * Gets all registered package prefixes.
  301. *
  302. *
  303. * @since 7.5.0
  304. * @see #getPackage(String)
  305. * @return a collection of package prefixes
  306. */
  307. public Collection<String> getPackagePrefixes() {
  308. return Collections.unmodifiableCollection(prefixToPackage.keySet());
  309. }
  310. /**
  311. * Gets the package corresponding to the give prefix, or <code>null</code>
  312. * no package has been registered for the prefix
  313. *
  314. * @since 7.5.0
  315. * @see #addPackagePrefix(String, String)
  316. * @param prefix
  317. * the prefix to find a package for
  318. * @return the package prefix, or <code>null</code> if no package is
  319. * registered for the provided prefix
  320. */
  321. public String getPackage(String prefix) {
  322. return prefixToPackage.get(prefix);
  323. }
  324. /**
  325. * Returns the default instance for the given class. The instance must not
  326. * be modified by the caller.
  327. *
  328. * @param abstractComponent
  329. * @return the default instance for the given class. The return value must
  330. * not be modified by the caller
  331. */
  332. public <T> T getDefaultInstance(Component component) {
  333. // If the root is a @DesignRoot component, it can't use itself as a
  334. // reference or the written design will be empty
  335. // If the root component in some other way initializes itself in the
  336. // constructor
  337. if (getRootComponent() == component
  338. && component.getClass().isAnnotationPresent(DesignRoot.class)) {
  339. return (T) getDefaultInstance((Class<? extends Component>) component
  340. .getClass().getSuperclass());
  341. }
  342. return (T) getDefaultInstance(component.getClass());
  343. }
  344. private Component getDefaultInstance(
  345. Class<? extends Component> componentClass) {
  346. Component instance = instanceCache.get(componentClass);
  347. if (instance == null) {
  348. instance = instantiateClass(componentClass.getName());
  349. instanceCache.put(componentClass, instance);
  350. }
  351. return instance;
  352. }
  353. /**
  354. * Reads and stores the mappings from prefixes to package names from meta
  355. * tags located under <head> in the html document.
  356. */
  357. protected void readPackageMappings(Document doc) {
  358. Element head = doc.head();
  359. if (head == null) {
  360. return;
  361. }
  362. for (Node child : head.childNodes()) {
  363. if (child instanceof Element) {
  364. Element childElement = (Element) child;
  365. if ("meta".equals(childElement.tagName())) {
  366. Attributes attributes = childElement.attributes();
  367. if (attributes.hasKey("name")
  368. && attributes.hasKey("content") && "package-mapping"
  369. .equals(attributes.get("name"))) {
  370. String contentString = attributes.get("content");
  371. String[] parts = contentString.split(":");
  372. if (parts.length != 2) {
  373. throw new DesignException("The meta tag '"
  374. + child.toString() + "' cannot be parsed.");
  375. }
  376. String prefixName = parts[0];
  377. String packageName = parts[1];
  378. addPackagePrefix(prefixName, packageName);
  379. }
  380. }
  381. }
  382. }
  383. }
  384. /**
  385. * Writes the package mappings (prefix -> package name) of this object to
  386. * the specified document.
  387. * <p>
  388. * The prefixes are stored as <meta> tags under <head> in the document.
  389. *
  390. * @param doc
  391. * the Jsoup document tree where the package mappings are written
  392. */
  393. public void writePackageMappings(Document doc) {
  394. Element head = doc.head();
  395. for (String prefix : getPackagePrefixes()) {
  396. // Only store the prefix-name mapping if it is not a default mapping
  397. // (such as "vaadin" -> "com.vaadin.ui")
  398. if (!VAADIN_PREFIX.equals(prefix) && !VAADIN7_PREFIX.equals(prefix)
  399. && !LEGACY_PREFIX.equals(prefix)) {
  400. Node newNode = doc.createElement("meta");
  401. newNode.attr("name", "package-mapping");
  402. String prefixToPackageName = prefix + ":" + getPackage(prefix);
  403. newNode.attr("content", prefixToPackageName);
  404. head.appendChild(newNode);
  405. }
  406. }
  407. }
  408. /**
  409. * Check whether the legacy prefix "v" or the default prefix "vaadin" should
  410. * be used when writing designs. The property or context parameter
  411. * {@link Constants#SERVLET_PARAMETER_LEGACY_DESIGN_PREFIX} can be used to
  412. * switch to the legacy prefix.
  413. *
  414. * @since 7.5.7
  415. * @return true to use the legacy prefix, false by default
  416. */
  417. protected boolean isLegacyPrefixEnabled() {
  418. if (legacyDesignPrefix != null) {
  419. return legacyDesignPrefix.booleanValue();
  420. }
  421. if (VaadinService.getCurrent() == null) {
  422. // This will happen at least in JUnit tests.
  423. return false;
  424. }
  425. DeploymentConfiguration configuration = VaadinService.getCurrent()
  426. .getDeploymentConfiguration();
  427. legacyDesignPrefix = configuration.getApplicationOrSystemProperty(
  428. Constants.SERVLET_PARAMETER_LEGACY_DESIGN_PREFIX, "false")
  429. .equals("true");
  430. return legacyDesignPrefix.booleanValue();
  431. }
  432. /**
  433. * Creates an html tree node corresponding to the given element. Also
  434. * initializes its attributes by calling writeDesign. As a result of the
  435. * writeDesign() call, this method creates the entire subtree rooted at the
  436. * returned Node.
  437. *
  438. * @param childComponent
  439. * The component with state that is written in to the node
  440. * @return An html tree node corresponding to the given component. The tag
  441. * name of the created node is derived from the class name of
  442. * childComponent.
  443. */
  444. public Element createElement(Component childComponent) {
  445. ComponentMapper componentMapper = Design.getComponentMapper();
  446. String tagName = componentMapper.componentToTag(childComponent, this);
  447. Element newElement = doc.createElement(tagName);
  448. childComponent.writeDesign(newElement, this);
  449. // Handle the local id. Global id and caption should have been taken
  450. // care of by writeDesign.
  451. String localId = componentToLocalId.get(childComponent);
  452. if (localId != null) {
  453. newElement.attr(LOCAL_ID_ATTRIBUTE, localId);
  454. }
  455. return newElement;
  456. }
  457. /**
  458. * Reads the given design node and creates the corresponding component tree
  459. *
  460. * @param componentDesign
  461. * The design element containing the description of the component
  462. * to be created.
  463. * @return the root component of component tree
  464. */
  465. public Component readDesign(Element componentDesign) {
  466. // Create the component.
  467. Component component = instantiateComponent(componentDesign);
  468. readDesign(componentDesign, component);
  469. fireComponentCreatedEvent(componentToLocalId.get(component), component);
  470. return component;
  471. }
  472. /**
  473. *
  474. * Reads the given design node and populates the given component with the
  475. * corresponding component tree
  476. * <p>
  477. * Additionally registers the component id, local id and caption of the
  478. * given component and all its children in the context
  479. *
  480. * @param componentDesign
  481. * The design element containing the description of the component
  482. * to be created
  483. * @param component
  484. * The component which corresponds to the design element
  485. */
  486. public void readDesign(Element componentDesign, Component component) {
  487. component.readDesign(componentDesign, this);
  488. // Get the ids and the caption of the component and store them in the
  489. // maps of this design context.
  490. org.jsoup.nodes.Attributes attributes = componentDesign.attributes();
  491. // global id: only update the mapping, the id has already been set for
  492. // the component
  493. String id = component.getId();
  494. if (id != null && id.length() > 0) {
  495. boolean mappingExists = mapId(id, component);
  496. if (mappingExists) {
  497. throw new DesignException(
  498. "The following global id is not unique: " + id);
  499. }
  500. }
  501. // local id: this is not a property of a component, so need to fetch it
  502. // from the attributes of componentDesign
  503. if (attributes.hasKey(LOCAL_ID_ATTRIBUTE)) {
  504. String localId = attributes.get(LOCAL_ID_ATTRIBUTE);
  505. boolean mappingExists = setComponentLocalId(component, localId);
  506. if (mappingExists) {
  507. throw new DesignException(
  508. "the following local id is not unique: " + localId);
  509. }
  510. }
  511. // caption: a property of a component, possibly not unique
  512. String caption = component.getCaption();
  513. if (caption != null) {
  514. mapCaption(caption, component);
  515. }
  516. }
  517. /**
  518. * Creates a Component corresponding to the given node. Does not set the
  519. * attributes for the created object.
  520. *
  521. * @param node
  522. * a node of an html tree
  523. * @return a Component corresponding to node, with no attributes set.
  524. */
  525. private Component instantiateComponent(Node node) {
  526. String tag = node.nodeName();
  527. ComponentMapper componentMapper = Design.getComponentMapper();
  528. Component component = componentMapper.tagToComponent(tag,
  529. Design.getComponentFactory(), this);
  530. assert tagEquals(tag, componentMapper.componentToTag(component, this));
  531. return component;
  532. }
  533. private boolean tagEquals(String tag1, String tag2) {
  534. return tag1.equals(tag2)
  535. || (hasVaadinPrefix(tag1) && hasVaadinPrefix(tag2));
  536. }
  537. private boolean hasVaadinPrefix(String tag) {
  538. return tag.startsWith(LEGACY_PREFIX + "-")
  539. || tag.startsWith(VAADIN_PREFIX + "-");
  540. }
  541. /**
  542. * Instantiates given class via ComponentFactory.
  543. *
  544. * @param qualifiedClassName
  545. * class name to instantiate
  546. * @return instance of a given class
  547. */
  548. private Component instantiateClass(String qualifiedClassName) {
  549. ComponentFactory factory = Design.getComponentFactory();
  550. Component component = factory.createComponent(qualifiedClassName, this);
  551. if (component == null) {
  552. throw new DesignException("Got unexpected null component from "
  553. + factory.getClass().getName() + " for class "
  554. + qualifiedClassName);
  555. }
  556. return component;
  557. }
  558. /**
  559. * Returns the root component of a created component hierarchy.
  560. *
  561. * @return the root component of the hierarchy
  562. */
  563. public Component getRootComponent() {
  564. return rootComponent;
  565. }
  566. /**
  567. * Sets the root component of a created component hierarchy.
  568. *
  569. * @param rootComponent
  570. * the root component of the hierarchy
  571. */
  572. public void setRootComponent(Component rootComponent) {
  573. this.rootComponent = rootComponent;
  574. }
  575. /**
  576. * Adds a component creation listener. The listener will be notified when
  577. * components are created while parsing a design template
  578. *
  579. * @param listener
  580. * the component creation listener to be added
  581. */
  582. public void addComponentCreationListener(
  583. ComponentCreationListener listener) {
  584. listeners.add(listener);
  585. }
  586. /**
  587. * Removes a component creation listener.
  588. *
  589. * @param listener
  590. * the component creation listener to be removed
  591. */
  592. public void removeComponentCreationListener(
  593. ComponentCreationListener listener) {
  594. listeners.remove(listener);
  595. }
  596. /**
  597. * Fires component creation event
  598. *
  599. * @param localId
  600. * localId of the component
  601. * @param component
  602. * the component that was created
  603. */
  604. private void fireComponentCreatedEvent(String localId,
  605. Component component) {
  606. ComponentCreatedEvent event = new ComponentCreatedEvent(localId,
  607. component);
  608. for (ComponentCreationListener listener : listeners) {
  609. listener.componentCreated(event);
  610. }
  611. }
  612. /**
  613. * Interface to be implemented by component creation listeners
  614. *
  615. * @author Vaadin Ltd
  616. */
  617. public interface ComponentCreationListener extends Serializable {
  618. /**
  619. * Called when component has been created in the design context
  620. *
  621. * @param event
  622. * the component creation event containing information on the
  623. * created component
  624. */
  625. public void componentCreated(ComponentCreatedEvent event);
  626. }
  627. /**
  628. * Component creation event that is fired when a component is created in the
  629. * context
  630. *
  631. * @author Vaadin Ltd
  632. */
  633. public class ComponentCreatedEvent implements Serializable {
  634. private String localId;
  635. private Component component;
  636. private DesignContext context;
  637. /**
  638. * Creates a new instance of ComponentCreatedEvent
  639. *
  640. * @param localId
  641. * the local id of the created component
  642. * @param component
  643. * the created component
  644. */
  645. private ComponentCreatedEvent(String localId, Component component) {
  646. this.localId = localId;
  647. this.component = component;
  648. context = DesignContext.this;
  649. }
  650. /**
  651. * Returns the local id of the created component or null if not exist
  652. *
  653. * @return the localId
  654. */
  655. public String getLocalId() {
  656. return localId;
  657. }
  658. /**
  659. * Returns the created component
  660. *
  661. * @return the component
  662. */
  663. public Component getComponent() {
  664. return component;
  665. }
  666. }
  667. /**
  668. * Helper method for component write implementors to determine whether their
  669. * children should be written out or not
  670. *
  671. * @param c
  672. * The component being written
  673. * @param defaultC
  674. * The default instance for the component
  675. * @return whether the children of c should be written
  676. */
  677. public boolean shouldWriteChildren(Component c, Component defaultC) {
  678. if (c == getRootComponent()) {
  679. // The root component should always write its children - otherwise
  680. // the result is empty
  681. return true;
  682. }
  683. if (defaultC instanceof HasComponents
  684. && ((HasComponents) defaultC).iterator().hasNext()) {
  685. // Easy version which assumes that this is a custom component if the
  686. // constructor adds children
  687. return false;
  688. }
  689. return true;
  690. }
  691. /**
  692. * Determines whether the container data of a component should be written
  693. * out by delegating to a {@link ShouldWriteDataDelegate}. The default
  694. * delegate assumes that all component data is provided by a data source
  695. * connected to a back end system and that the data should thus not be
  696. * written.
  697. *
  698. * @since 7.5.0
  699. * @see #setShouldWriteDataDelegate(ShouldWriteDataDelegate)
  700. * @param component
  701. * the component to check
  702. * @return <code>true</code> if container data should be written out for the
  703. * provided component; otherwise <code>false</code>.
  704. */
  705. public boolean shouldWriteData(Component component) {
  706. return getShouldWriteDataDelegate().shouldWriteData(component);
  707. }
  708. /**
  709. * Sets the delegate that determines whether the container data of a
  710. * component should be written out.
  711. *
  712. * @since 7.5.0
  713. * @see #shouldWriteChildren(Component, Component)
  714. * @see #getShouldWriteDataDelegate()
  715. * @param shouldWriteDataDelegate
  716. * the delegate to set, not <code>null</code>
  717. * @throws IllegalArgumentException
  718. * if the provided delegate is <code>null</code>
  719. */
  720. public void setShouldWriteDataDelegate(
  721. ShouldWriteDataDelegate shouldWriteDataDelegate) {
  722. if (shouldWriteDataDelegate == null) {
  723. throw new IllegalArgumentException("Delegate cannot be null");
  724. }
  725. this.shouldWriteDataDelegate = shouldWriteDataDelegate;
  726. }
  727. /**
  728. * Gets the delegate that determines whether the container data of a
  729. * component should be written out.
  730. *
  731. * @since 7.5.0
  732. * @see #setShouldWriteDataDelegate(ShouldWriteDataDelegate)
  733. * @see #shouldWriteChildren(Component, Component)
  734. * @return the shouldWriteDataDelegate the currently use delegate
  735. */
  736. public ShouldWriteDataDelegate getShouldWriteDataDelegate() {
  737. return shouldWriteDataDelegate;
  738. }
  739. /**
  740. * Gets the attributes that the component did not handle
  741. *
  742. * @since 7.7
  743. * @param component
  744. * the component to get the attributes for
  745. * @return map of the attributes which were not recognized by the component
  746. */
  747. public Map<String, String> getCustomAttributes(Component component) {
  748. return customAttributes.get(component);
  749. }
  750. /**
  751. * Sets a custom attribute not handled by the component. These attributes
  752. * are directly written to the component tag.
  753. *
  754. * @since 7.7
  755. * @param component
  756. * the component to set the attribute for
  757. * @param attribute
  758. * the attribute to set
  759. * @param value
  760. * the value of the attribute
  761. */
  762. public void setCustomAttribute(Component component, String attribute,
  763. String value) {
  764. Map<String, String> map = customAttributes.get(component);
  765. if (map == null) {
  766. customAttributes.put(component,
  767. map = new HashMap<String, String>());
  768. }
  769. map.put(attribute, value);
  770. }
  771. }