Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

FieldGroup.java 43KB

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