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

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