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.

FieldGroup.java 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /*
  2. * Copyright 2000-2014 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.data.fieldgroup;
  17. import java.io.Serializable;
  18. import java.lang.reflect.InvocationTargetException;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.LinkedHashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import com.vaadin.data.Item;
  27. import com.vaadin.data.Property;
  28. import com.vaadin.data.Validator.InvalidValueException;
  29. import com.vaadin.data.util.TransactionalPropertyWrapper;
  30. import com.vaadin.ui.AbstractField;
  31. import com.vaadin.ui.DefaultFieldFactory;
  32. import com.vaadin.ui.Field;
  33. import com.vaadin.ui.Form;
  34. import com.vaadin.util.ReflectTools;
  35. /**
  36. * FieldGroup provides an easy way of binding fields to data and handling
  37. * commits of these fields.
  38. * <p>
  39. * The functionality of FieldGroup is similar to {@link Form} but
  40. * {@link FieldGroup} does not handle layouts in any way. The typical use case
  41. * is to create a layout outside the FieldGroup and then use FieldGroup to bind
  42. * the fields to a data source.
  43. * </p>
  44. * <p>
  45. * {@link FieldGroup} is not a UI component so it cannot be added to a layout.
  46. * Using the buildAndBind methods {@link FieldGroup} can create fields for you
  47. * using a FieldGroupFieldFactory but you still have to add them to the correct
  48. * position in your layout.
  49. * </p>
  50. *
  51. * @author Vaadin Ltd
  52. * @since 7.0
  53. */
  54. public class FieldGroup implements Serializable {
  55. private Item itemDataSource;
  56. private boolean buffered = true;
  57. private boolean enabled = true;
  58. private boolean readOnly = false;
  59. private HashMap<Object, Field<?>> propertyIdToField = new HashMap<Object, Field<?>>();
  60. private LinkedHashMap<Field<?>, Object> fieldToPropertyId = new LinkedHashMap<Field<?>, Object>();
  61. private List<CommitHandler> commitHandlers = new ArrayList<CommitHandler>();
  62. /**
  63. * The field factory used by builder methods.
  64. */
  65. private FieldGroupFieldFactory fieldFactory = DefaultFieldGroupFieldFactory
  66. .get();
  67. /**
  68. * Constructs a field binder. Use {@link #setItemDataSource(Item)} to set a
  69. * data source for the field binder.
  70. *
  71. */
  72. public FieldGroup() {
  73. }
  74. /**
  75. * Constructs a field binder that uses the given data source.
  76. *
  77. * @param itemDataSource
  78. * The data source to bind the fields to
  79. */
  80. public FieldGroup(Item itemDataSource) {
  81. setItemDataSource(itemDataSource);
  82. }
  83. /**
  84. * Updates the item that is used by this FieldBinder. Rebinds all fields to
  85. * the properties in the new item.
  86. *
  87. * @param itemDataSource
  88. * The new item to use
  89. */
  90. public void setItemDataSource(Item itemDataSource) {
  91. this.itemDataSource = itemDataSource;
  92. for (Field<?> f : fieldToPropertyId.keySet()) {
  93. bind(f, fieldToPropertyId.get(f));
  94. }
  95. }
  96. /**
  97. * Gets the item used by this FieldBinder. Note that you must call
  98. * {@link #commit()} for the item to be updated unless buffered mode has
  99. * been switched off.
  100. *
  101. * @see #setBuffered(boolean)
  102. * @see #commit()
  103. *
  104. * @return The item used by this FieldBinder
  105. */
  106. public Item getItemDataSource() {
  107. return itemDataSource;
  108. }
  109. /**
  110. * Checks the buffered mode for the bound fields.
  111. * <p>
  112. *
  113. * @see #setBuffered(boolean) for more details on buffered mode
  114. *
  115. * @see Field#isBuffered()
  116. * @return true if buffered mode is on, false otherwise
  117. *
  118. */
  119. public boolean isBuffered() {
  120. return buffered;
  121. }
  122. /**
  123. * Sets the buffered mode for the bound fields.
  124. * <p>
  125. * When buffered mode is on the item will not be updated until
  126. * {@link #commit()} is called. If buffered mode is off the item will be
  127. * updated once the fields are updated.
  128. * </p>
  129. * <p>
  130. * The default is to use buffered mode.
  131. * </p>
  132. *
  133. * @see Field#setBuffered(boolean)
  134. * @param buffered
  135. * true to turn on buffered mode, false otherwise
  136. */
  137. public void setBuffered(boolean buffered) {
  138. if (buffered == this.buffered) {
  139. return;
  140. }
  141. this.buffered = buffered;
  142. for (Field<?> field : getFields()) {
  143. field.setBuffered(buffered);
  144. }
  145. }
  146. /**
  147. * Returns the enabled status for the fields.
  148. * <p>
  149. * Note that this will not accurately represent the enabled status of all
  150. * fields if you change the enabled status of the fields through some other
  151. * method than {@link #setEnabled(boolean)}.
  152. *
  153. * @return true if the fields are enabled, false otherwise
  154. */
  155. public boolean isEnabled() {
  156. return enabled;
  157. }
  158. /**
  159. * Updates the enabled state of all bound fields.
  160. *
  161. * @param fieldsEnabled
  162. * true to enable all bound fields, false to disable them
  163. */
  164. public void setEnabled(boolean fieldsEnabled) {
  165. enabled = fieldsEnabled;
  166. for (Field<?> field : getFields()) {
  167. field.setEnabled(fieldsEnabled);
  168. }
  169. }
  170. /**
  171. * Returns the read only status that is used by default with all fields that
  172. * have a writable data source.
  173. * <p>
  174. * Note that this will not accurately represent the read only status of all
  175. * fields if you change the read only status of the fields through some
  176. * other method than {@link #setReadOnly(boolean)}.
  177. *
  178. * @return true if the fields are set to read only, false otherwise
  179. */
  180. public boolean isReadOnly() {
  181. return readOnly;
  182. }
  183. /**
  184. * Sets the read only state to the given value for all fields with writable
  185. * data source. Fields with read only data source will always be set to read
  186. * only.
  187. *
  188. * @param fieldsReadOnly
  189. * true to set the fields with writable data source to read only,
  190. * false to set them to read write
  191. */
  192. public void setReadOnly(boolean fieldsReadOnly) {
  193. readOnly = fieldsReadOnly;
  194. for (Field<?> field : getFields()) {
  195. if (field.getPropertyDataSource() == null
  196. || !field.getPropertyDataSource().isReadOnly()) {
  197. field.setReadOnly(fieldsReadOnly);
  198. } else {
  199. field.setReadOnly(true);
  200. }
  201. }
  202. }
  203. /**
  204. * Returns a collection of all fields that have been bound.
  205. * <p>
  206. * The fields are not returned in any specific order.
  207. * </p>
  208. *
  209. * @return A collection with all bound Fields
  210. */
  211. public Collection<Field<?>> getFields() {
  212. return fieldToPropertyId.keySet();
  213. }
  214. /**
  215. * Binds the field with the given propertyId from the current item. If an
  216. * item has not been set then the binding is postponed until the item is set
  217. * using {@link #setItemDataSource(Item)}.
  218. * <p>
  219. * This method also adds validators when applicable.
  220. * </p>
  221. *
  222. * @param field
  223. * The field to bind
  224. * @param propertyId
  225. * The propertyId to bind to the field
  226. * @throws BindException
  227. * If the field is null or the property id is already bound to
  228. * another field by this field binder
  229. */
  230. public void bind(Field<?> field, Object propertyId) throws BindException {
  231. throwIfFieldIsNull(field, propertyId);
  232. throwIfPropertyIdAlreadyBound(field, propertyId);
  233. fieldToPropertyId.put(field, propertyId);
  234. propertyIdToField.put(propertyId, field);
  235. if (itemDataSource == null) {
  236. // Clear any possible existing binding to clear the field
  237. field.setPropertyDataSource(null);
  238. boolean fieldReadOnly = field.isReadOnly();
  239. if (!fieldReadOnly) {
  240. field.clear();
  241. } else {
  242. // Temporarily make the field read-write so we can clear the
  243. // value. Needed because setPropertyDataSource(null) does not
  244. // currently clear the field
  245. // (https://dev.vaadin.com/ticket/14733)
  246. field.setReadOnly(false);
  247. field.clear();
  248. field.setReadOnly(true);
  249. }
  250. // Will be bound when data source is set
  251. return;
  252. }
  253. field.setPropertyDataSource(wrapInTransactionalProperty(getItemProperty(propertyId)));
  254. configureField(field);
  255. }
  256. /**
  257. * Wrap property to transactional property.
  258. */
  259. protected <T> Property.Transactional<T> wrapInTransactionalProperty(
  260. Property<T> itemProperty) {
  261. return new TransactionalPropertyWrapper<T>(itemProperty);
  262. }
  263. private void throwIfFieldIsNull(Field<?> field, Object propertyId) {
  264. if (field == null) {
  265. throw new BindException(
  266. String.format(
  267. "Cannot bind property id '%s' to a null field.",
  268. propertyId));
  269. }
  270. }
  271. private void throwIfPropertyIdAlreadyBound(Field<?> field, Object propertyId) {
  272. if (propertyIdToField.containsKey(propertyId)
  273. && propertyIdToField.get(propertyId) != field) {
  274. throw new BindException("Property id " + propertyId
  275. + " is already bound to another field");
  276. }
  277. }
  278. /**
  279. * Gets the property with the given property id from the item.
  280. *
  281. * @param propertyId
  282. * The id if the property to find
  283. * @return The property with the given id from the item
  284. * @throws BindException
  285. * If the property was not found in the item or no item has been
  286. * set
  287. */
  288. protected Property getItemProperty(Object propertyId) throws BindException {
  289. Item item = getItemDataSource();
  290. if (item == null) {
  291. throw new BindException("Could not lookup property with id "
  292. + propertyId + " as no item has been set");
  293. }
  294. Property<?> p = item.getItemProperty(propertyId);
  295. if (p == null) {
  296. throw new BindException("A property with id " + propertyId
  297. + " was not found in the item");
  298. }
  299. return p;
  300. }
  301. /**
  302. * Detaches the field from its property id and removes it from this
  303. * FieldBinder.
  304. * <p>
  305. * Note that the field is not detached from its property data source if it
  306. * is no longer connected to the same property id it was bound to using this
  307. * FieldBinder.
  308. *
  309. * @param field
  310. * The field to detach
  311. * @throws BindException
  312. * If the field is not bound by this field binder or not bound
  313. * to the correct property id
  314. */
  315. public void unbind(Field<?> field) throws BindException {
  316. Object propertyId = fieldToPropertyId.get(field);
  317. if (propertyId == null) {
  318. throw new BindException(
  319. "The given field is not part of this FieldBinder");
  320. }
  321. TransactionalPropertyWrapper<?> wrapper = null;
  322. Property fieldDataSource = field.getPropertyDataSource();
  323. if (fieldDataSource instanceof TransactionalPropertyWrapper) {
  324. wrapper = (TransactionalPropertyWrapper<?>) fieldDataSource;
  325. fieldDataSource = ((TransactionalPropertyWrapper<?>) fieldDataSource)
  326. .getWrappedProperty();
  327. }
  328. if (getItemDataSource() != null
  329. && fieldDataSource == getItemProperty(propertyId)) {
  330. if (null != wrapper) {
  331. wrapper.detachFromProperty();
  332. }
  333. field.setPropertyDataSource(null);
  334. }
  335. fieldToPropertyId.remove(field);
  336. propertyIdToField.remove(propertyId);
  337. }
  338. /**
  339. * Configures a field with the settings set for this FieldBinder.
  340. * <p>
  341. * By default this updates the buffered, read only and enabled state of the
  342. * field. Also adds validators when applicable. Fields with read only data
  343. * source are always configured as read only.
  344. *
  345. * @param field
  346. * The field to update
  347. */
  348. protected void configureField(Field<?> field) {
  349. field.setBuffered(isBuffered());
  350. field.setEnabled(isEnabled());
  351. if (field.getPropertyDataSource().isReadOnly()) {
  352. field.setReadOnly(true);
  353. } else {
  354. field.setReadOnly(isReadOnly());
  355. }
  356. }
  357. /**
  358. * Gets the type of the property with the given property id.
  359. *
  360. * @param propertyId
  361. * The propertyId. Must be find
  362. * @return The type of the property
  363. */
  364. protected Class<?> getPropertyType(Object propertyId) throws BindException {
  365. if (getItemDataSource() == null) {
  366. throw new BindException(
  367. "Property type for '"
  368. + propertyId
  369. + "' could not be determined. No item data source has been set.");
  370. }
  371. Property<?> p = getItemDataSource().getItemProperty(propertyId);
  372. if (p == null) {
  373. throw new BindException(
  374. "Property type for '"
  375. + propertyId
  376. + "' could not be determined. No property with that id was found.");
  377. }
  378. return p.getType();
  379. }
  380. /**
  381. * Returns a collection of all property ids that have been bound to fields.
  382. * <p>
  383. * Note that this will return property ids even before the item has been
  384. * set. In that case it returns the property ids that will be bound once the
  385. * item is set.
  386. * </p>
  387. * <p>
  388. * No guarantee is given for the order of the property ids
  389. * </p>
  390. *
  391. * @return A collection of bound property ids
  392. */
  393. public Collection<Object> getBoundPropertyIds() {
  394. return Collections.unmodifiableCollection(propertyIdToField.keySet());
  395. }
  396. /**
  397. * Returns a collection of all property ids that exist in the item set using
  398. * {@link #setItemDataSource(Item)} but have not been bound to fields.
  399. * <p>
  400. * Will always return an empty collection before an item has been set using
  401. * {@link #setItemDataSource(Item)}.
  402. * </p>
  403. * <p>
  404. * No guarantee is given for the order of the property ids
  405. * </p>
  406. *
  407. * @return A collection of property ids that have not been bound to fields
  408. */
  409. public Collection<Object> getUnboundPropertyIds() {
  410. if (getItemDataSource() == null) {
  411. return new ArrayList<Object>();
  412. }
  413. List<Object> unboundPropertyIds = new ArrayList<Object>();
  414. unboundPropertyIds.addAll(getItemDataSource().getItemPropertyIds());
  415. unboundPropertyIds.removeAll(propertyIdToField.keySet());
  416. return unboundPropertyIds;
  417. }
  418. /**
  419. * Commits all changes done to the bound fields.
  420. * <p>
  421. * Calls all {@link CommitHandler}s before and after committing the field
  422. * changes to the item data source. The whole commit is aborted and state is
  423. * restored to what it was before commit was called if any
  424. * {@link CommitHandler} throws a CommitException or there is a problem
  425. * committing the fields
  426. *
  427. * @throws CommitException
  428. * If the commit was aborted
  429. */
  430. public void commit() throws CommitException {
  431. if (!isBuffered()) {
  432. // Not using buffered mode, nothing to do
  433. return;
  434. }
  435. startTransactions();
  436. try {
  437. firePreCommitEvent();
  438. Map<Field<?>, InvalidValueException> invalidValueExceptions = commitFields();
  439. if (invalidValueExceptions.isEmpty()) {
  440. firePostCommitEvent();
  441. commitTransactions();
  442. } else {
  443. throw new FieldGroupInvalidValueException(
  444. invalidValueExceptions);
  445. }
  446. } catch (Exception e) {
  447. rollbackTransactions();
  448. throw new CommitException("Commit failed", this, e);
  449. }
  450. }
  451. /**
  452. * Tries to commit all bound fields one by one and gathers any validation
  453. * exceptions in a map, which is returned to the caller
  454. *
  455. * @return a propertyId to validation exception map which is empty if all
  456. * commits succeeded
  457. */
  458. private Map<Field<?>, InvalidValueException> commitFields() {
  459. Map<Field<?>, InvalidValueException> invalidValueExceptions = new HashMap<Field<?>, InvalidValueException>();
  460. for (Field<?> f : fieldToPropertyId.keySet()) {
  461. try {
  462. f.commit();
  463. } catch (InvalidValueException e) {
  464. invalidValueExceptions.put(f, e);
  465. }
  466. }
  467. return invalidValueExceptions;
  468. }
  469. /**
  470. * Exception which wraps InvalidValueExceptions from all invalid fields in a
  471. * FieldGroup
  472. *
  473. * @since 7.4
  474. */
  475. public static class FieldGroupInvalidValueException extends
  476. InvalidValueException {
  477. private Map<Field<?>, InvalidValueException> invalidValueExceptions;
  478. /**
  479. * Constructs a new exception with the specified validation exceptions.
  480. *
  481. * @param invalidValueExceptions
  482. * a property id to exception map
  483. */
  484. public FieldGroupInvalidValueException(
  485. Map<Field<?>, InvalidValueException> invalidValueExceptions) {
  486. super(null, invalidValueExceptions.values().toArray(
  487. new InvalidValueException[invalidValueExceptions.size()]));
  488. this.invalidValueExceptions = invalidValueExceptions;
  489. }
  490. /**
  491. * Returns a map containing fields which failed validation and the
  492. * exceptions the corresponding validators threw.
  493. *
  494. * @return a map with all the invalid value exceptions
  495. */
  496. public Map<Field<?>, InvalidValueException> getInvalidFields() {
  497. return invalidValueExceptions;
  498. }
  499. }
  500. private void startTransactions() throws CommitException {
  501. for (Field<?> f : fieldToPropertyId.keySet()) {
  502. Property.Transactional<?> property = (Property.Transactional<?>) f
  503. .getPropertyDataSource();
  504. if (property == null) {
  505. throw new CommitException("Property \""
  506. + fieldToPropertyId.get(f)
  507. + "\" not bound to datasource.");
  508. }
  509. property.startTransaction();
  510. }
  511. }
  512. private void commitTransactions() {
  513. for (Field<?> f : fieldToPropertyId.keySet()) {
  514. ((Property.Transactional<?>) f.getPropertyDataSource()).commit();
  515. }
  516. }
  517. private void rollbackTransactions() {
  518. for (Field<?> f : fieldToPropertyId.keySet()) {
  519. try {
  520. ((Property.Transactional<?>) f.getPropertyDataSource())
  521. .rollback();
  522. } catch (Exception rollbackException) {
  523. // FIXME: What to do ?
  524. }
  525. }
  526. }
  527. /**
  528. * Sends a preCommit event to all registered commit handlers
  529. *
  530. * @throws CommitException
  531. * If the commit should be aborted
  532. */
  533. private void firePreCommitEvent() throws CommitException {
  534. CommitHandler[] handlers = commitHandlers
  535. .toArray(new CommitHandler[commitHandlers.size()]);
  536. for (CommitHandler handler : handlers) {
  537. handler.preCommit(new CommitEvent(this));
  538. }
  539. }
  540. /**
  541. * Sends a postCommit event to all registered commit handlers
  542. *
  543. * @throws CommitException
  544. * If the commit should be aborted
  545. */
  546. private void firePostCommitEvent() throws CommitException {
  547. CommitHandler[] handlers = commitHandlers
  548. .toArray(new CommitHandler[commitHandlers.size()]);
  549. for (CommitHandler handler : handlers) {
  550. handler.postCommit(new CommitEvent(this));
  551. }
  552. }
  553. /**
  554. * Discards all changes done to the bound fields.
  555. * <p>
  556. * Only has effect if buffered mode is used.
  557. *
  558. */
  559. public void discard() {
  560. for (Field<?> f : fieldToPropertyId.keySet()) {
  561. try {
  562. f.discard();
  563. } catch (Exception e) {
  564. // TODO: handle exception
  565. // What can we do if discard fails other than try to discard all
  566. // other fields?
  567. }
  568. }
  569. }
  570. /**
  571. * Returns the field that is bound to the given property id
  572. *
  573. * @param propertyId
  574. * The property id to use to lookup the field
  575. * @return The field that is bound to the property id or null if no field is
  576. * bound to that property id
  577. */
  578. public Field<?> getField(Object propertyId) {
  579. return propertyIdToField.get(propertyId);
  580. }
  581. /**
  582. * Returns the property id that is bound to the given field
  583. *
  584. * @param field
  585. * The field to use to lookup the property id
  586. * @return The property id that is bound to the field or null if the field
  587. * is not bound to any property id by this FieldBinder
  588. */
  589. public Object getPropertyId(Field<?> field) {
  590. return fieldToPropertyId.get(field);
  591. }
  592. /**
  593. * Adds a commit handler.
  594. * <p>
  595. * The commit handler is called before the field values are committed to the
  596. * item ( {@link CommitHandler#preCommit(CommitEvent)}) and after the item
  597. * has been updated ({@link CommitHandler#postCommit(CommitEvent)}). If a
  598. * {@link CommitHandler} throws a CommitException the whole commit is
  599. * aborted and the fields retain their old values.
  600. *
  601. * @param commitHandler
  602. * The commit handler to add
  603. */
  604. public void addCommitHandler(CommitHandler commitHandler) {
  605. commitHandlers.add(commitHandler);
  606. }
  607. /**
  608. * Removes the given commit handler.
  609. *
  610. * @see #addCommitHandler(CommitHandler)
  611. *
  612. * @param commitHandler
  613. * The commit handler to remove
  614. */
  615. public void removeCommitHandler(CommitHandler commitHandler) {
  616. commitHandlers.remove(commitHandler);
  617. }
  618. /**
  619. * Returns a list of all commit handlers for this {@link FieldGroup}.
  620. * <p>
  621. * Use {@link #addCommitHandler(CommitHandler)} and
  622. * {@link #removeCommitHandler(CommitHandler)} to register or unregister a
  623. * commit handler.
  624. *
  625. * @return A collection of commit handlers
  626. */
  627. protected Collection<CommitHandler> getCommitHandlers() {
  628. return Collections.unmodifiableCollection(commitHandlers);
  629. }
  630. /**
  631. * CommitHandlers are used by {@link FieldGroup#commit()} as part of the
  632. * commit transactions. CommitHandlers can perform custom operations as part
  633. * of the commit and cause the commit to be aborted by throwing a
  634. * {@link CommitException}.
  635. */
  636. public interface CommitHandler extends Serializable {
  637. /**
  638. * Called before changes are committed to the field and the item is
  639. * updated.
  640. * <p>
  641. * Throw a {@link CommitException} to abort the commit.
  642. *
  643. * @param commitEvent
  644. * An event containing information regarding the commit
  645. * @throws CommitException
  646. * if the commit should be aborted
  647. */
  648. public void preCommit(CommitEvent commitEvent) throws CommitException;
  649. /**
  650. * Called after changes are committed to the fields and the item is
  651. * updated.
  652. * <p>
  653. * Throw a {@link CommitException} to abort the commit.
  654. *
  655. * @param commitEvent
  656. * An event containing information regarding the commit
  657. * @throws CommitException
  658. * if the commit should be aborted
  659. */
  660. public void postCommit(CommitEvent commitEvent) throws CommitException;
  661. }
  662. /**
  663. * FIXME javadoc
  664. *
  665. */
  666. public static class CommitEvent implements Serializable {
  667. private FieldGroup fieldBinder;
  668. private CommitEvent(FieldGroup fieldBinder) {
  669. this.fieldBinder = fieldBinder;
  670. }
  671. /**
  672. * Returns the field binder that this commit relates to
  673. *
  674. * @return The FieldBinder that is being committed.
  675. */
  676. public FieldGroup getFieldBinder() {
  677. return fieldBinder;
  678. }
  679. }
  680. /**
  681. * Checks the validity of the bound fields.
  682. * <p>
  683. * Call the {@link Field#validate()} for the fields to get the individual
  684. * error messages.
  685. *
  686. * @return true if all bound fields are valid, false otherwise.
  687. */
  688. public boolean isValid() {
  689. try {
  690. for (Field<?> field : getFields()) {
  691. field.validate();
  692. }
  693. return true;
  694. } catch (InvalidValueException e) {
  695. return false;
  696. }
  697. }
  698. /**
  699. * Checks if any bound field has been modified.
  700. *
  701. * @return true if at least one field has been modified, false otherwise
  702. */
  703. public boolean isModified() {
  704. for (Field<?> field : getFields()) {
  705. if (field.isModified()) {
  706. return true;
  707. }
  708. }
  709. return false;
  710. }
  711. /**
  712. * Gets the field factory for the {@link FieldGroup}. The field factory is
  713. * only used when {@link FieldGroup} creates a new field.
  714. *
  715. * @return The field factory in use
  716. *
  717. */
  718. public FieldGroupFieldFactory getFieldFactory() {
  719. return fieldFactory;
  720. }
  721. /**
  722. * Sets the field factory for the {@link FieldGroup}. The field factory is
  723. * only used when {@link FieldGroup} creates a new field.
  724. *
  725. * @param fieldFactory
  726. * The field factory to use
  727. */
  728. public void setFieldFactory(FieldGroupFieldFactory fieldFactory) {
  729. this.fieldFactory = fieldFactory;
  730. }
  731. /**
  732. * Binds member fields found in the given object.
  733. * <p>
  734. * This method processes all (Java) member fields whose type extends
  735. * {@link Field} and that can be mapped to a property id. Property id
  736. * mapping is done based on the field name or on a @{@link PropertyId}
  737. * annotation on the field. All non-null fields for which a property id can
  738. * be determined are bound to the property id.
  739. * </p>
  740. * <p>
  741. * For example:
  742. *
  743. * <pre>
  744. * public class MyForm extends VerticalLayout {
  745. * private TextField firstName = new TextField("First name");
  746. * @PropertyId("last")
  747. * private TextField lastName = new TextField("Last name");
  748. * private TextField age = new TextField("Age"); ... }
  749. *
  750. * MyForm myForm = new MyForm();
  751. * ...
  752. * fieldGroup.bindMemberFields(myForm);
  753. * </pre>
  754. *
  755. * </p>
  756. * This binds the firstName TextField to a "firstName" property in the item,
  757. * lastName TextField to a "last" property and the age TextField to a "age"
  758. * property.
  759. *
  760. * @param objectWithMemberFields
  761. * The object that contains (Java) member fields to bind
  762. * @throws BindException
  763. * If there is a problem binding a field
  764. */
  765. public void bindMemberFields(Object objectWithMemberFields)
  766. throws BindException {
  767. buildAndBindMemberFields(objectWithMemberFields, false);
  768. }
  769. /**
  770. * Binds member fields found in the given object and builds member fields
  771. * that have not been initialized.
  772. * <p>
  773. * This method processes all (Java) member fields whose type extends
  774. * {@link Field} and that can be mapped to a property id. Property ids are
  775. * searched in the following order: @{@link PropertyId} annotations, exact
  776. * field name matches and the case-insensitive matching that ignores
  777. * underscores. Fields that are not initialized (null) are built using the
  778. * field factory. All non-null fields for which a property id can be
  779. * determined are bound to the property id.
  780. * </p>
  781. * <p>
  782. * For example:
  783. *
  784. * <pre>
  785. * public class MyForm extends VerticalLayout {
  786. * private TextField firstName = new TextField("First name");
  787. * @PropertyId("last")
  788. * private TextField lastName = new TextField("Last name");
  789. * private TextField age;
  790. *
  791. * MyForm myForm = new MyForm();
  792. * ...
  793. * fieldGroup.buildAndBindMemberFields(myForm);
  794. * </pre>
  795. *
  796. * </p>
  797. * <p>
  798. * This binds the firstName TextField to a "firstName" property in the item,
  799. * lastName TextField to a "last" property and builds an age TextField using
  800. * the field factory and then binds it to the "age" property.
  801. * </p>
  802. *
  803. * @param objectWithMemberFields
  804. * The object that contains (Java) member fields to build and
  805. * bind
  806. * @throws BindException
  807. * If there is a problem binding or building a field
  808. */
  809. public void buildAndBindMemberFields(Object objectWithMemberFields)
  810. throws BindException {
  811. buildAndBindMemberFields(objectWithMemberFields, true);
  812. }
  813. /**
  814. * Binds member fields found in the given object and optionally builds
  815. * member fields that have not been initialized.
  816. * <p>
  817. * This method processes all (Java) member fields whose type extends
  818. * {@link Field} and that can be mapped to a property id. Property ids are
  819. * searched in the following order: @{@link PropertyId} annotations, exact
  820. * field name matches and the case-insensitive matching that ignores
  821. * underscores. Fields that are not initialized (null) are built using the
  822. * field factory is buildFields is true. All non-null fields for which a
  823. * property id can be determined are bound to the property id.
  824. * </p>
  825. *
  826. * @param objectWithMemberFields
  827. * The object that contains (Java) member fields to build and
  828. * bind
  829. * @throws BindException
  830. * If there is a problem binding or building a field
  831. */
  832. protected void buildAndBindMemberFields(Object objectWithMemberFields,
  833. boolean buildFields) throws BindException {
  834. Class<?> objectClass = objectWithMemberFields.getClass();
  835. for (java.lang.reflect.Field memberField : getFieldsInDeclareOrder(objectClass)) {
  836. if (!Field.class.isAssignableFrom(memberField.getType())) {
  837. // Process next field
  838. continue;
  839. }
  840. PropertyId propertyIdAnnotation = memberField
  841. .getAnnotation(PropertyId.class);
  842. Class<? extends Field> fieldType = (Class<? extends Field>) memberField
  843. .getType();
  844. Object propertyId = null;
  845. if (propertyIdAnnotation != null) {
  846. // @PropertyId(propertyId) always overrides property id
  847. propertyId = propertyIdAnnotation.value();
  848. } else {
  849. try {
  850. propertyId = findPropertyId(memberField);
  851. } catch (SearchException e) {
  852. // Property id was not found, skip this field
  853. continue;
  854. }
  855. if (propertyId == null) {
  856. // Property id was not found, skip this field
  857. continue;
  858. }
  859. }
  860. // Ensure that the property id exists
  861. Class<?> propertyType;
  862. try {
  863. propertyType = getPropertyType(propertyId);
  864. } catch (BindException e) {
  865. // Property id was not found, skip this field
  866. continue;
  867. }
  868. Field<?> field;
  869. try {
  870. // Get the field from the object
  871. field = (Field<?>) ReflectTools.getJavaFieldValue(
  872. objectWithMemberFields, memberField, Field.class);
  873. } catch (Exception e) {
  874. // If we cannot determine the value, just skip the field and try
  875. // the next one
  876. continue;
  877. }
  878. if (field == null && buildFields) {
  879. Caption captionAnnotation = memberField
  880. .getAnnotation(Caption.class);
  881. String caption;
  882. if (captionAnnotation != null) {
  883. caption = captionAnnotation.value();
  884. } else {
  885. caption = DefaultFieldFactory
  886. .createCaptionByPropertyId(propertyId);
  887. }
  888. // Create the component (Field)
  889. field = build(caption, propertyType, fieldType);
  890. // Store it in the field
  891. try {
  892. ReflectTools.setJavaFieldValue(objectWithMemberFields,
  893. memberField, field);
  894. } catch (IllegalArgumentException e) {
  895. throw new BindException("Could not assign value to field '"
  896. + memberField.getName() + "'", e);
  897. } catch (IllegalAccessException e) {
  898. throw new BindException("Could not assign value to field '"
  899. + memberField.getName() + "'", e);
  900. } catch (InvocationTargetException e) {
  901. throw new BindException("Could not assign value to field '"
  902. + memberField.getName() + "'", e);
  903. }
  904. }
  905. if (field != null) {
  906. // Bind it to the property id
  907. bind(field, propertyId);
  908. }
  909. }
  910. }
  911. /**
  912. * Searches for a property id from the current itemDataSource that matches
  913. * the given memberField.
  914. * <p>
  915. * If perfect match is not found, uses a case insensitive search that also
  916. * ignores underscores. Returns null if no match is found. Throws a
  917. * SearchException if no item data source has been set.
  918. * </p>
  919. * <p>
  920. * The propertyId search logic used by
  921. * {@link #buildAndBindMemberFields(Object, boolean)
  922. * buildAndBindMemberFields} can easily be customized by overriding this
  923. * method. No other changes are needed.
  924. * </p>
  925. *
  926. * @param memberField
  927. * The field an object id is searched for
  928. * @return
  929. */
  930. protected Object findPropertyId(java.lang.reflect.Field memberField) {
  931. String fieldName = memberField.getName();
  932. if (getItemDataSource() == null) {
  933. throw new SearchException(
  934. "Property id type for field '"
  935. + fieldName
  936. + "' could not be determined. No item data source has been set.");
  937. }
  938. Item dataSource = getItemDataSource();
  939. if (dataSource.getItemProperty(fieldName) != null) {
  940. return fieldName;
  941. } else {
  942. String minifiedFieldName = minifyFieldName(fieldName);
  943. for (Object itemPropertyId : dataSource.getItemPropertyIds()) {
  944. if (itemPropertyId instanceof String) {
  945. String itemPropertyName = (String) itemPropertyId;
  946. if (minifiedFieldName
  947. .equals(minifyFieldName(itemPropertyName))) {
  948. return itemPropertyName;
  949. }
  950. }
  951. }
  952. }
  953. return null;
  954. }
  955. protected static String minifyFieldName(String fieldName) {
  956. return fieldName.toLowerCase().replace("_", "");
  957. }
  958. /**
  959. * Exception thrown by a FieldGroup when the commit operation fails.
  960. *
  961. * Provides information about validation errors through
  962. * {@link #getInvalidFields()} if the cause of the failure is that all bound
  963. * fields did not pass validation
  964. *
  965. */
  966. public static class CommitException extends Exception {
  967. private FieldGroup fieldGroup;
  968. public CommitException() {
  969. super();
  970. }
  971. public CommitException(String message, FieldGroup fieldGroup,
  972. Throwable cause) {
  973. super(message, cause);
  974. this.fieldGroup = fieldGroup;
  975. }
  976. public CommitException(String message, Throwable cause) {
  977. super(message, cause);
  978. }
  979. public CommitException(String message) {
  980. super(message);
  981. }
  982. public CommitException(Throwable cause) {
  983. super(cause);
  984. }
  985. /**
  986. * Returns a map containing the fields which failed validation and the
  987. * exceptions the corresponding validators threw.
  988. *
  989. * @since 7.4
  990. * @return a map with all the invalid value exceptions. Can be empty but
  991. * not null
  992. */
  993. public Map<Field<?>, InvalidValueException> getInvalidFields() {
  994. if (getCause() instanceof FieldGroupInvalidValueException) {
  995. return ((FieldGroupInvalidValueException) getCause())
  996. .getInvalidFields();
  997. }
  998. return new HashMap<Field<?>, InvalidValueException>();
  999. }
  1000. /**
  1001. * Returns the field group where the exception occurred
  1002. *
  1003. * @since 7.4
  1004. * @return the field group
  1005. */
  1006. public FieldGroup getFieldGroup() {
  1007. return fieldGroup;
  1008. }
  1009. }
  1010. public static class BindException extends RuntimeException {
  1011. public BindException(String message) {
  1012. super(message);
  1013. }
  1014. public BindException(String message, Throwable t) {
  1015. super(message, t);
  1016. }
  1017. }
  1018. public static class SearchException extends RuntimeException {
  1019. public SearchException(String message) {
  1020. super(message);
  1021. }
  1022. public SearchException(String message, Throwable t) {
  1023. super(message, t);
  1024. }
  1025. }
  1026. /**
  1027. * Builds a field and binds it to the given property id using the field
  1028. * binder.
  1029. *
  1030. * @param propertyId
  1031. * The property id to bind to. Must be present in the field
  1032. * finder.
  1033. * @throws BindException
  1034. * If there is a problem while building or binding
  1035. * @return The created and bound field
  1036. */
  1037. public Field<?> buildAndBind(Object propertyId) throws BindException {
  1038. String caption = DefaultFieldFactory
  1039. .createCaptionByPropertyId(propertyId);
  1040. return buildAndBind(caption, propertyId);
  1041. }
  1042. /**
  1043. * Builds a field using the given caption and binds it to the given property
  1044. * id using the field binder.
  1045. *
  1046. * @param caption
  1047. * The caption for the field
  1048. * @param propertyId
  1049. * The property id to bind to. Must be present in the field
  1050. * finder.
  1051. * @throws BindException
  1052. * If there is a problem while building or binding
  1053. * @return The created and bound field. Can be any type of {@link Field}.
  1054. */
  1055. public Field<?> buildAndBind(String caption, Object propertyId)
  1056. throws BindException {
  1057. return buildAndBind(caption, propertyId, Field.class);
  1058. }
  1059. /**
  1060. * Builds a field using the given caption and binds it to the given property
  1061. * id using the field binder. Ensures the new field is of the given type.
  1062. *
  1063. * @param caption
  1064. * The caption for the field
  1065. * @param propertyId
  1066. * The property id to bind to. Must be present in the field
  1067. * finder.
  1068. * @throws BindException
  1069. * If the field could not be created
  1070. * @return The created and bound field. Can be any type of {@link Field}.
  1071. */
  1072. public <T extends Field> T buildAndBind(String caption, Object propertyId,
  1073. Class<T> fieldType) throws BindException {
  1074. Class<?> type = getPropertyType(propertyId);
  1075. T field = build(caption, type, fieldType);
  1076. bind(field, propertyId);
  1077. return field;
  1078. }
  1079. /**
  1080. * Creates a field based on the given data type.
  1081. * <p>
  1082. * The data type is the type that we want to edit using the field. The field
  1083. * type is the type of field we want to create, can be {@link Field} if any
  1084. * Field is good.
  1085. * </p>
  1086. *
  1087. * @param caption
  1088. * The caption for the new field
  1089. * @param dataType
  1090. * The data model type that we want to edit using the field
  1091. * @param fieldType
  1092. * The type of field that we want to create
  1093. * @return A Field capable of editing the given type
  1094. * @throws BindException
  1095. * If the field could not be created
  1096. */
  1097. protected <T extends Field> T build(String caption, Class<?> dataType,
  1098. Class<T> fieldType) throws BindException {
  1099. T field = getFieldFactory().createField(dataType, fieldType);
  1100. if (field == null) {
  1101. throw new BindException("Unable to build a field of type "
  1102. + fieldType.getName() + " for editing "
  1103. + dataType.getName());
  1104. }
  1105. field.setCaption(caption);
  1106. return field;
  1107. }
  1108. /**
  1109. * Returns an array containing Field objects reflecting all the fields of
  1110. * the class or interface represented by this Class object. The elements in
  1111. * the array returned are sorted in declare order from sub class to super
  1112. * class.
  1113. *
  1114. * @param searchClass
  1115. * @return
  1116. */
  1117. protected static List<java.lang.reflect.Field> getFieldsInDeclareOrder(
  1118. Class searchClass) {
  1119. ArrayList<java.lang.reflect.Field> memberFieldInOrder = new ArrayList<java.lang.reflect.Field>();
  1120. while (searchClass != null) {
  1121. for (java.lang.reflect.Field memberField : searchClass
  1122. .getDeclaredFields()) {
  1123. memberFieldInOrder.add(memberField);
  1124. }
  1125. searchClass = searchClass.getSuperclass();
  1126. }
  1127. return memberFieldInOrder;
  1128. }
  1129. /**
  1130. * Clears the value of all fields.
  1131. *
  1132. * @since 7.4
  1133. */
  1134. public void clear() {
  1135. for (Field<?> f : getFields()) {
  1136. if (f instanceof AbstractField) {
  1137. ((AbstractField) f).clear();
  1138. }
  1139. }
  1140. }
  1141. }