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.

Binder.java 103KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670
  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.data;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Field;
  19. import java.lang.reflect.InvocationTargetException;
  20. import java.lang.reflect.Type;
  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.IdentityHashMap;
  27. import java.util.LinkedHashSet;
  28. import java.util.List;
  29. import java.util.Locale;
  30. import java.util.Map;
  31. import java.util.Objects;
  32. import java.util.Optional;
  33. import java.util.Set;
  34. import java.util.function.BiFunction;
  35. import java.util.stream.Collectors;
  36. import java.util.stream.Stream;
  37. import com.googlecode.gentyref.GenericTypeReflector;
  38. import com.vaadin.annotations.PropertyId;
  39. import com.vaadin.data.HasValue.ValueChangeEvent;
  40. import com.vaadin.data.HasValue.ValueChangeListener;
  41. import com.vaadin.data.converter.StringToIntegerConverter;
  42. import com.vaadin.data.validator.BeanValidator;
  43. import com.vaadin.event.EventRouter;
  44. import com.vaadin.server.AbstractErrorMessage.ContentMode;
  45. import com.vaadin.server.ErrorMessage;
  46. import com.vaadin.server.SerializableFunction;
  47. import com.vaadin.server.SerializablePredicate;
  48. import com.vaadin.server.Setter;
  49. import com.vaadin.server.UserError;
  50. import com.vaadin.shared.Registration;
  51. import com.vaadin.shared.ui.ErrorLevel;
  52. import com.vaadin.ui.AbstractComponent;
  53. import com.vaadin.ui.Component;
  54. import com.vaadin.ui.Label;
  55. import com.vaadin.ui.UI;
  56. import com.vaadin.util.ReflectTools;
  57. /**
  58. * Connects one or more {@code Field} components to properties of a backing data
  59. * type such as a bean type. With a binder, input components can be grouped
  60. * together into forms to easily create and update business objects with little
  61. * explicit logic needed to move data between the UI and the data layers of the
  62. * application.
  63. * <p>
  64. * A binder is a collection of <i>bindings</i>, each representing the mapping of
  65. * a single field, through converters and validators, to a backing property.
  66. * <p>
  67. * A binder instance can be bound to a single bean instance at a time, but can
  68. * be rebound as needed. This allows usage patterns like a <i>master-details</i>
  69. * view, where a select component is used to pick the bean to edit.
  70. * <p>
  71. * Bean level validators can be added using the
  72. * {@link #withValidator(Validator)} method and will be run on the bound bean
  73. * once it has been updated from the values of the bound fields. Bean level
  74. * validators are also run as part of {@link #writeBean(Object)} and
  75. * {@link #writeBeanIfValid(Object)} if all field level validators pass.
  76. * <p>
  77. * Note: For bean level validators, the bean must be updated before the
  78. * validators are run. If a bean level validator fails in
  79. * {@link #writeBean(Object)} or {@link #writeBeanIfValid(Object)}, the bean
  80. * will be reverted to the previous state before returning from the method. You
  81. * should ensure that the getters/setters in the bean do not have side effects.
  82. * <p>
  83. * Unless otherwise specified, {@code Binder} method arguments cannot be null.
  84. *
  85. * @author Vaadin Ltd.
  86. *
  87. * @param <BEAN>
  88. * the bean type
  89. *
  90. * @see BindingBuilder
  91. * @see Binding
  92. * @see HasValue
  93. *
  94. * @since 8.0
  95. */
  96. public class Binder<BEAN> implements Serializable {
  97. /**
  98. * Represents the binding between a field and a data property.
  99. *
  100. * @param <BEAN>
  101. * the bean type
  102. * @param <TARGET>
  103. * the target data type of the binding, matches the field type
  104. * unless a converter has been set
  105. *
  106. * @see Binder#forField(HasValue)
  107. */
  108. public interface Binding<BEAN, TARGET> extends Serializable {
  109. /**
  110. * Gets the field the binding uses.
  111. *
  112. * @return the field for the binding
  113. */
  114. public HasValue<?> getField();
  115. /**
  116. * Validates the field value and returns a {@code ValidationStatus}
  117. * instance representing the outcome of the validation. This method is a
  118. * short-hand for calling {@link #validate(boolean)} with
  119. * {@code fireEvent} {@code true}.
  120. *
  121. * @see #validate(boolean)
  122. * @see Binder#validate()
  123. * @see Validator#apply(Object, ValueContext)
  124. *
  125. * @return the validation result.
  126. */
  127. public default BindingValidationStatus<TARGET> validate() {
  128. return validate(true);
  129. }
  130. /**
  131. * Validates the field value and returns a {@code ValidationStatus}
  132. * instance representing the outcome of the validation.
  133. *
  134. * @see #validate()
  135. *
  136. * @param fireEvent
  137. * {@code true} to fire status event; {@code false} to not
  138. * @return the validation result.
  139. *
  140. * @since 8.2
  141. */
  142. public BindingValidationStatus<TARGET> validate(boolean fireEvent);
  143. /**
  144. * Gets the validation status handler for this Binding.
  145. *
  146. * @return the validation status handler for this binding
  147. *
  148. * @since 8.2
  149. */
  150. public BindingValidationStatusHandler getValidationStatusHandler();
  151. /**
  152. * Unbinds the binding from its respective {@code Binder} Removes any
  153. * {@code ValueChangeListener} {@code Registration} from associated
  154. * {@code HasValue}.
  155. *
  156. * @since 8.2
  157. */
  158. public void unbind();
  159. }
  160. /**
  161. * Creates a binding between a field and a data property.
  162. *
  163. * @param <BEAN>
  164. * the bean type
  165. * @param <TARGET>
  166. * the target data type of the binding, matches the field type
  167. * until a converter has been set
  168. *
  169. * @see Binder#forField(HasValue)
  170. */
  171. public interface BindingBuilder<BEAN, TARGET> extends Serializable {
  172. /**
  173. * Gets the field the binding is being built for.
  174. *
  175. * @return the field this binding is being built for
  176. */
  177. public HasValue<?> getField();
  178. /**
  179. * Completes this binding using the given getter and setter functions
  180. * representing a backing bean property. The functions are used to
  181. * update the field value from the property and to store the field value
  182. * to the property, respectively.
  183. * <p>
  184. * When a bean is bound with {@link Binder#setBean(BEAN)}, the field
  185. * value is set to the return value of the given getter. The property
  186. * value is then updated via the given setter whenever the field value
  187. * changes. The setter may be null; in that case the property value is
  188. * never updated and the binding is said to be <i>read-only</i>.
  189. * <p>
  190. * If the Binder is already bound to some bean, the newly bound field is
  191. * associated with the corresponding bean property as described above.
  192. * <p>
  193. * The getter and setter can be arbitrary functions, for instance
  194. * implementing user-defined conversion or validation. However, in the
  195. * most basic use case you can simply pass a pair of method references
  196. * to this method as follows:
  197. *
  198. * <pre>
  199. * class Person {
  200. * public String getName() { ... }
  201. * public void setName(String name) { ... }
  202. * }
  203. *
  204. * TextField nameField = new TextField();
  205. * binder.forField(nameField).bind(Person::getName, Person::setName);
  206. * </pre>
  207. *
  208. * @param getter
  209. * the function to get the value of the property to the
  210. * field, not null
  211. * @param setter
  212. * the function to write the field value to the property or
  213. * null if read-only
  214. * @return the newly created binding
  215. * @throws IllegalStateException
  216. * if {@code bind} has already been called on this binding
  217. */
  218. public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
  219. Setter<BEAN, TARGET> setter);
  220. /**
  221. * Completes this binding by connecting the field to the property with
  222. * the given name. The getter and setter of the property are looked up
  223. * using a {@link PropertySet}.
  224. * <p>
  225. * For a <code>Binder</code> created using the
  226. * {@link Binder#Binder(Class)} constructor, introspection will be used
  227. * to find a Java Bean property. If a JSR-303 bean validation
  228. * implementation is present on the classpath, a {@link BeanValidator}
  229. * is also added to the binding.
  230. * <p>
  231. * The property must have an accessible getter method. It need not have
  232. * an accessible setter; in that case the property value is never
  233. * updated and the binding is said to be <i>read-only</i>.
  234. *
  235. * @param propertyName
  236. * the name of the property to bind, not null
  237. * @return the newly created binding
  238. *
  239. * @throws IllegalArgumentException
  240. * if the property name is invalid
  241. * @throws IllegalArgumentException
  242. * if the property has no accessible getter
  243. * @throws IllegalStateException
  244. * if the binder is not configured with an appropriate
  245. * {@link PropertySet}
  246. *
  247. * @see Binder.BindingBuilder#bind(ValueProvider, Setter)
  248. */
  249. public Binding<BEAN, TARGET> bind(String propertyName);
  250. /**
  251. * Adds a validator to this binding. Validators are applied, in
  252. * registration order, when the field value is written to the backing
  253. * property. If any validator returns a failure, the property value is
  254. * not updated.
  255. *
  256. * @see #withValidator(SerializablePredicate, String)
  257. * @see #withValidator(SerializablePredicate, ErrorMessageProvider)
  258. *
  259. * @param validator
  260. * the validator to add, not null
  261. * @return this binding, for chaining
  262. * @throws IllegalStateException
  263. * if {@code bind} has already been called
  264. */
  265. public BindingBuilder<BEAN, TARGET> withValidator(
  266. Validator<? super TARGET> validator);
  267. /**
  268. * A convenience method to add a validator to this binding using the
  269. * {@link Validator#from(SerializablePredicate, String)} factory method.
  270. * <p>
  271. * Validators are applied, in registration order, when the field value
  272. * is written to the backing property. If any validator returns a
  273. * failure, the property value is not updated.
  274. *
  275. * @see #withValidator(Validator)
  276. * @see #withValidator(SerializablePredicate, String, ErrorLevel)
  277. * @see #withValidator(SerializablePredicate, ErrorMessageProvider)
  278. * @see Validator#from(SerializablePredicate, String)
  279. *
  280. * @param predicate
  281. * the predicate performing validation, not null
  282. * @param message
  283. * the error message to report in case validation failure
  284. * @return this binding, for chaining
  285. * @throws IllegalStateException
  286. * if {@code bind} has already been called
  287. */
  288. public default BindingBuilder<BEAN, TARGET> withValidator(
  289. SerializablePredicate<? super TARGET> predicate,
  290. String message) {
  291. return withValidator(Validator.from(predicate, message));
  292. }
  293. /**
  294. * A convenience method to add a validator to this binding using the
  295. * {@link Validator#from(SerializablePredicate, String, ErrorLevel)}
  296. * factory method.
  297. * <p>
  298. * Validators are applied, in registration order, when the field value
  299. * is written to the backing property. If any validator returns a
  300. * failure, the property value is not updated.
  301. *
  302. * @see #withValidator(Validator)
  303. * @see #withValidator(SerializablePredicate, String)
  304. * @see #withValidator(SerializablePredicate, ErrorMessageProvider,
  305. * ErrorLevel)
  306. * @see Validator#from(SerializablePredicate, String)
  307. *
  308. * @param predicate
  309. * the predicate performing validation, not null
  310. * @param message
  311. * the error message to report in case validation failure
  312. * @param errorLevel
  313. * the error level for failures from this validator, not null
  314. * @return this binding, for chaining
  315. * @throws IllegalStateException
  316. * if {@code bind} has already been called
  317. *
  318. * @since 8.2
  319. */
  320. public default BindingBuilder<BEAN, TARGET> withValidator(
  321. SerializablePredicate<? super TARGET> predicate, String message,
  322. ErrorLevel errorLevel) {
  323. return withValidator(
  324. Validator.from(predicate, message, errorLevel));
  325. }
  326. /**
  327. * A convenience method to add a validator to this binding using the
  328. * {@link Validator#from(SerializablePredicate, ErrorMessageProvider)}
  329. * factory method.
  330. * <p>
  331. * Validators are applied, in registration order, when the field value
  332. * is written to the backing property. If any validator returns a
  333. * failure, the property value is not updated.
  334. *
  335. * @see #withValidator(Validator)
  336. * @see #withValidator(SerializablePredicate, String)
  337. * @see #withValidator(SerializablePredicate, ErrorMessageProvider,
  338. * ErrorLevel)
  339. * @see Validator#from(SerializablePredicate, ErrorMessageProvider)
  340. *
  341. * @param predicate
  342. * the predicate performing validation, not null
  343. * @param errorMessageProvider
  344. * the provider to generate error messages, not null
  345. * @return this binding, for chaining
  346. * @throws IllegalStateException
  347. * if {@code bind} has already been called
  348. */
  349. public default BindingBuilder<BEAN, TARGET> withValidator(
  350. SerializablePredicate<? super TARGET> predicate,
  351. ErrorMessageProvider errorMessageProvider) {
  352. return withValidator(
  353. Validator.from(predicate, errorMessageProvider));
  354. }
  355. /**
  356. * A convenience method to add a validator to this binding using the
  357. * {@link Validator#from(SerializablePredicate, ErrorMessageProvider, ErrorLevel)}
  358. * factory method.
  359. * <p>
  360. * Validators are applied, in registration order, when the field value
  361. * is written to the backing property. If any validator returns a
  362. * failure, the property value is not updated.
  363. *
  364. * @see #withValidator(Validator)
  365. * @see #withValidator(SerializablePredicate, String, ErrorLevel)
  366. * @see #withValidator(SerializablePredicate, ErrorMessageProvider)
  367. * @see Validator#from(SerializablePredicate, ErrorMessageProvider,
  368. * ErrorLevel)
  369. *
  370. * @param predicate
  371. * the predicate performing validation, not null
  372. * @param errorMessageProvider
  373. * the provider to generate error messages, not null
  374. * @param errorLevel
  375. * the error level for failures from this validator, not null
  376. * @return this binding, for chaining
  377. * @throws IllegalStateException
  378. * if {@code bind} has already been called
  379. *
  380. * @since 8.2
  381. */
  382. public default BindingBuilder<BEAN, TARGET> withValidator(
  383. SerializablePredicate<? super TARGET> predicate,
  384. ErrorMessageProvider errorMessageProvider,
  385. ErrorLevel errorLevel) {
  386. return withValidator(Validator.from(predicate, errorMessageProvider,
  387. errorLevel));
  388. }
  389. /**
  390. * Maps the binding to another data type using the given
  391. * {@link Converter}.
  392. * <p>
  393. * A converter is capable of converting between a presentation type,
  394. * which must match the current target data type of the binding, and a
  395. * model type, which can be any data type and becomes the new target
  396. * type of the binding. When invoking
  397. * {@link #bind(ValueProvider, Setter)}, the target type of the binding
  398. * must match the getter/setter types.
  399. * <p>
  400. * For instance, a {@code TextField} can be bound to an integer-typed
  401. * property using an appropriate converter such as a
  402. * {@link StringToIntegerConverter}.
  403. *
  404. * @param <NEWTARGET>
  405. * the type to convert to
  406. * @param converter
  407. * the converter to use, not null
  408. * @return a new binding with the appropriate type
  409. * @throws IllegalStateException
  410. * if {@code bind} has already been called
  411. */
  412. public <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
  413. Converter<TARGET, NEWTARGET> converter);
  414. /**
  415. * Maps the binding to another data type using the mapping functions and
  416. * a possible exception as the error message.
  417. * <p>
  418. * The mapping functions are used to convert between a presentation
  419. * type, which must match the current target data type of the binding,
  420. * and a model type, which can be any data type and becomes the new
  421. * target type of the binding. When invoking
  422. * {@link #bind(ValueProvider, Setter)}, the target type of the binding
  423. * must match the getter/setter types.
  424. * <p>
  425. * For instance, a {@code TextField} can be bound to an integer-typed
  426. * property using appropriate functions such as:
  427. * <code>withConverter(Integer::valueOf, String::valueOf);</code>
  428. *
  429. * @param <NEWTARGET>
  430. * the type to convert to
  431. * @param toModel
  432. * the function which can convert from the old target type to
  433. * the new target type
  434. * @param toPresentation
  435. * the function which can convert from the new target type to
  436. * the old target type
  437. * @return a new binding with the appropriate type
  438. * @throws IllegalStateException
  439. * if {@code bind} has already been called
  440. */
  441. public default <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
  442. SerializableFunction<TARGET, NEWTARGET> toModel,
  443. SerializableFunction<NEWTARGET, TARGET> toPresentation) {
  444. return withConverter(Converter.from(toModel, toPresentation,
  445. exception -> exception.getMessage()));
  446. }
  447. /**
  448. * Maps the binding to another data type using the mapping functions and
  449. * the given error error message if a value cannot be converted to the
  450. * new target type.
  451. * <p>
  452. * The mapping functions are used to convert between a presentation
  453. * type, which must match the current target data type of the binding,
  454. * and a model type, which can be any data type and becomes the new
  455. * target type of the binding. When invoking
  456. * {@link #bind(ValueProvider, Setter)}, the target type of the binding
  457. * must match the getter/setter types.
  458. * <p>
  459. * For instance, a {@code TextField} can be bound to an integer-typed
  460. * property using appropriate functions such as:
  461. * <code>withConverter(Integer::valueOf, String::valueOf);</code>
  462. *
  463. * @param <NEWTARGET>
  464. * the type to convert to
  465. * @param toModel
  466. * the function which can convert from the old target type to
  467. * the new target type
  468. * @param toPresentation
  469. * the function which can convert from the new target type to
  470. * the old target type
  471. * @param errorMessage
  472. * the error message to use if conversion using
  473. * <code>toModel</code> fails
  474. * @return a new binding with the appropriate type
  475. * @throws IllegalStateException
  476. * if {@code bind} has already been called
  477. */
  478. public default <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
  479. SerializableFunction<TARGET, NEWTARGET> toModel,
  480. SerializableFunction<NEWTARGET, TARGET> toPresentation,
  481. String errorMessage) {
  482. return withConverter(Converter.from(toModel, toPresentation,
  483. exception -> errorMessage));
  484. }
  485. /**
  486. * Maps binding value {@code null} to given null representation and back
  487. * to {@code null} when converting back to model value.
  488. *
  489. * @param nullRepresentation
  490. * the value to use instead of {@code null}
  491. * @return a new binding with null representation handling.
  492. */
  493. public default BindingBuilder<BEAN, TARGET> withNullRepresentation(
  494. TARGET nullRepresentation) {
  495. return withConverter(
  496. fieldValue -> Objects.equals(fieldValue, nullRepresentation)
  497. ? null : fieldValue,
  498. modelValue -> Objects.isNull(modelValue)
  499. ? nullRepresentation : modelValue);
  500. }
  501. /**
  502. * Sets the given {@code label} to show an error message if validation
  503. * fails.
  504. * <p>
  505. * The validation state of each field is updated whenever the user
  506. * modifies the value of that field. The validation state is by default
  507. * shown using {@link AbstractComponent#setComponentError} which is used
  508. * by the layout that the field is shown in. Most built-in layouts will
  509. * show this as a red exclamation mark icon next to the component, so
  510. * that hovering or tapping the icon shows a tooltip with the message
  511. * text.
  512. * <p>
  513. * This method allows to customize the way a binder displays error
  514. * messages to get more flexibility than what
  515. * {@link AbstractComponent#setComponentError} provides (it replaces the
  516. * default behavior).
  517. * <p>
  518. * This is just a shorthand for
  519. * {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
  520. * method where the handler instance hides the {@code label} if there is
  521. * no error and shows it with validation error message if validation
  522. * fails. It means that it cannot be called after
  523. * {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
  524. * method call or
  525. * {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
  526. * after this method call.
  527. *
  528. * @see #withValidationStatusHandler(BindingValidationStatusHandler)
  529. * @see AbstractComponent#setComponentError(ErrorMessage)
  530. * @param label
  531. * label to show validation status for the field
  532. * @return this binding, for chaining
  533. */
  534. public default BindingBuilder<BEAN, TARGET> withStatusLabel(
  535. Label label) {
  536. return withValidationStatusHandler(status -> {
  537. label.setValue(status.getMessage().orElse(""));
  538. // Only show the label when validation has failed
  539. label.setVisible(status.isError());
  540. });
  541. }
  542. /**
  543. * Sets a {@link BindingValidationStatusHandler} to track validation
  544. * status changes.
  545. * <p>
  546. * The validation state of each field is updated whenever the user
  547. * modifies the value of that field. The validation state is by default
  548. * shown using {@link AbstractComponent#setComponentError} which is used
  549. * by the layout that the field is shown in. Most built-in layouts will
  550. * show this as a red exclamation mark icon next to the component, so
  551. * that hovering or tapping the icon shows a tooltip with the message
  552. * text.
  553. * <p>
  554. * This method allows to customize the way a binder displays error
  555. * messages to get more flexibility than what
  556. * {@link AbstractComponent#setComponentError} provides (it replaces the
  557. * default behavior).
  558. * <p>
  559. * The method may be called only once. It means there is no chain unlike
  560. * {@link #withValidator(Validator)} or
  561. * {@link #withConverter(Converter)}. Also it means that the shorthand
  562. * method {@link #withStatusLabel(Label)} also may not be called after
  563. * this method.
  564. *
  565. * @see #withStatusLabel(Label)
  566. * @see AbstractComponent#setComponentError(ErrorMessage)
  567. * @param handler
  568. * status change handler
  569. * @return this binding, for chaining
  570. */
  571. public BindingBuilder<BEAN, TARGET> withValidationStatusHandler(
  572. BindingValidationStatusHandler handler);
  573. /**
  574. * Sets the field to be required. This means two things:
  575. * <ol>
  576. * <li>the required indicator will be displayed for this field</li>
  577. * <li>the field value is validated for not being empty, i.e. that the
  578. * field's value is not equal to what {@link HasValue#getEmptyValue()}
  579. * returns</li>
  580. * </ol>
  581. * <p>
  582. * For localizing the error message, use
  583. * {@link #asRequired(ErrorMessageProvider)}.
  584. *
  585. * @see #asRequired(ErrorMessageProvider)
  586. * @see HasValue#setRequiredIndicatorVisible(boolean)
  587. * @see HasValue#isEmpty()
  588. * @param errorMessage
  589. * the error message to show for the invalid value
  590. * @return this binding, for chaining
  591. */
  592. public default BindingBuilder<BEAN, TARGET> asRequired(
  593. String errorMessage) {
  594. return asRequired(context -> errorMessage);
  595. }
  596. /**
  597. * Sets the field to be required. This means two things:
  598. * <ol>
  599. * <li>the required indicator will be displayed for this field</li>
  600. * <li>the field value is validated for not being empty, i.e. that the
  601. * field's value is not equal to what {@link HasValue#getEmptyValue()}
  602. * returns</li>
  603. * </ol>
  604. *
  605. * @see HasValue#setRequiredIndicatorVisible(boolean)
  606. * @see HasValue#isEmpty()
  607. * @param errorMessageProvider
  608. * the provider for localized validation error message
  609. * @return this binding, for chaining
  610. */
  611. public BindingBuilder<BEAN, TARGET> asRequired(
  612. ErrorMessageProvider errorMessageProvider);
  613. }
  614. /**
  615. * An internal implementation of {@code BindingBuilder}.
  616. *
  617. * @param <BEAN>
  618. * the bean type, must match the Binder bean type
  619. * @param <FIELDVALUE>
  620. * the value type of the field
  621. * @param <TARGET>
  622. * the target data type of the binding, matches the field type
  623. * until a converter has been set
  624. */
  625. protected static class BindingBuilderImpl<BEAN, FIELDVALUE, TARGET>
  626. implements BindingBuilder<BEAN, TARGET> {
  627. private Binder<BEAN> binder;
  628. private final HasValue<FIELDVALUE> field;
  629. private BindingValidationStatusHandler statusHandler;
  630. private boolean isStatusHandlerChanged;
  631. private boolean bound;
  632. /**
  633. * Contains all converters and validators chained together in the
  634. * correct order.
  635. */
  636. private Converter<FIELDVALUE, ?> converterValidatorChain;
  637. /**
  638. * Creates a new binding builder associated with the given field.
  639. * Initializes the builder with the given converter chain and status
  640. * change handler.
  641. *
  642. * @param binder
  643. * the binder this instance is connected to, not null
  644. * @param field
  645. * the field to bind, not null
  646. * @param converterValidatorChain
  647. * the converter/validator chain to use, not null
  648. * @param statusHandler
  649. * the handler to track validation status, not null
  650. */
  651. protected BindingBuilderImpl(Binder<BEAN> binder,
  652. HasValue<FIELDVALUE> field,
  653. Converter<FIELDVALUE, TARGET> converterValidatorChain,
  654. BindingValidationStatusHandler statusHandler) {
  655. this.field = field;
  656. this.binder = binder;
  657. this.converterValidatorChain = converterValidatorChain;
  658. this.statusHandler = statusHandler;
  659. }
  660. @Override
  661. public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
  662. Setter<BEAN, TARGET> setter) {
  663. checkUnbound();
  664. Objects.requireNonNull(getter, "getter cannot be null");
  665. BindingImpl<BEAN, FIELDVALUE, TARGET> binding = new BindingImpl<>(
  666. this, getter, setter);
  667. getBinder().bindings.add(binding);
  668. if (getBinder().getBean() != null) {
  669. binding.initFieldValue(getBinder().getBean());
  670. }
  671. getBinder().fireStatusChangeEvent(false);
  672. bound = true;
  673. getBinder().incompleteBindings.remove(getField());
  674. return binding;
  675. }
  676. @Override
  677. @SuppressWarnings({ "unchecked", "rawtypes" })
  678. public Binding<BEAN, TARGET> bind(String propertyName) {
  679. Objects.requireNonNull(propertyName,
  680. "Property name cannot be null");
  681. checkUnbound();
  682. PropertyDefinition<BEAN, ?> definition = getBinder().propertySet
  683. .getProperty(propertyName)
  684. .orElseThrow(() -> new IllegalArgumentException(
  685. "Could not resolve property name " + propertyName
  686. + " from " + getBinder().propertySet));
  687. ValueProvider<BEAN, ?> getter = definition.getGetter();
  688. Setter<BEAN, ?> setter = definition.getSetter()
  689. .orElse((bean, value) -> {
  690. // Setter ignores value
  691. });
  692. BindingBuilder<BEAN, ?> finalBinding = withConverter(
  693. createConverter(definition.getType()), false);
  694. finalBinding = getBinder().configureBinding(finalBinding,
  695. definition);
  696. try {
  697. Binding binding = ((BindingBuilder) finalBinding).bind(getter,
  698. setter);
  699. getBinder().boundProperties.put(propertyName, binding);
  700. return binding;
  701. } finally {
  702. getBinder().incompleteMemberFieldBindings.remove(getField());
  703. }
  704. }
  705. @SuppressWarnings("unchecked")
  706. private Converter<TARGET, Object> createConverter(Class<?> getterType) {
  707. return Converter.from(fieldValue -> getterType.cast(fieldValue),
  708. propertyValue -> (TARGET) propertyValue, exception -> {
  709. throw new RuntimeException(exception);
  710. });
  711. }
  712. @Override
  713. public BindingBuilder<BEAN, TARGET> withValidator(
  714. Validator<? super TARGET> validator) {
  715. checkUnbound();
  716. Objects.requireNonNull(validator, "validator cannot be null");
  717. converterValidatorChain = ((Converter<FIELDVALUE, TARGET>) converterValidatorChain)
  718. .chain(new ValidatorAsConverter<>(validator));
  719. return this;
  720. }
  721. @Override
  722. public <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
  723. Converter<TARGET, NEWTARGET> converter) {
  724. return withConverter(converter, true);
  725. }
  726. @Override
  727. public BindingBuilder<BEAN, TARGET> withValidationStatusHandler(
  728. BindingValidationStatusHandler handler) {
  729. checkUnbound();
  730. Objects.requireNonNull(handler, "handler cannot be null");
  731. if (isStatusHandlerChanged) {
  732. throw new IllegalStateException("A "
  733. + BindingValidationStatusHandler.class.getSimpleName()
  734. + " has already been set");
  735. }
  736. isStatusHandlerChanged = true;
  737. statusHandler = handler;
  738. return this;
  739. }
  740. @Override
  741. public BindingBuilder<BEAN, TARGET> asRequired(
  742. ErrorMessageProvider errorMessageProvider) {
  743. checkUnbound();
  744. field.setRequiredIndicatorVisible(true);
  745. return withValidator(
  746. value -> !Objects.equals(value, field.getEmptyValue()),
  747. errorMessageProvider);
  748. }
  749. /**
  750. * Implements {@link #withConverter(Converter)} method with additional
  751. * possibility to disable (reset) default null representation converter.
  752. * <p>
  753. * The method {@link #withConverter(Converter)} calls this method with
  754. * {@code true} provided as the second argument value.
  755. *
  756. * @see #withConverter(Converter)
  757. *
  758. * @param converter
  759. * the converter to use, not null
  760. * @param resetNullRepresentation
  761. * if {@code true} then default null representation will be
  762. * deactivated (if not yet), otherwise it won't be removed
  763. * @return a new binding with the appropriate type
  764. * @param <NEWTARGET>
  765. * the type to convert to
  766. * @throws IllegalStateException
  767. * if {@code bind} has already been called
  768. */
  769. protected <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
  770. Converter<TARGET, NEWTARGET> converter,
  771. boolean resetNullRepresentation) {
  772. checkUnbound();
  773. Objects.requireNonNull(converter, "converter cannot be null");
  774. if (resetNullRepresentation) {
  775. getBinder().initialConverters.get(field).setIdentity();
  776. }
  777. converterValidatorChain = ((Converter<FIELDVALUE, TARGET>) converterValidatorChain)
  778. .chain(converter);
  779. return (BindingBuilder<BEAN, NEWTARGET>) this;
  780. }
  781. /**
  782. * Returns the {@code Binder} connected to this {@code Binding}
  783. * instance.
  784. *
  785. * @return the binder
  786. */
  787. protected Binder<BEAN> getBinder() {
  788. return binder;
  789. }
  790. /**
  791. * Throws if this binding is already completed and cannot be modified
  792. * anymore.
  793. *
  794. * @throws IllegalStateException
  795. * if this binding is already bound
  796. */
  797. protected void checkUnbound() {
  798. if (bound) {
  799. throw new IllegalStateException(
  800. "cannot modify binding: already bound to a property");
  801. }
  802. }
  803. @Override
  804. public HasValue<FIELDVALUE> getField() {
  805. return field;
  806. }
  807. }
  808. /**
  809. * An internal implementation of {@code Binding}.
  810. *
  811. * @param <BEAN>
  812. * the bean type, must match the Binder bean type
  813. * @param <FIELDVALUE>
  814. * the value type of the field
  815. * @param <TARGET>
  816. * the target data type of the binding, matches the field type
  817. * unless a converter has been set
  818. */
  819. protected static class BindingImpl<BEAN, FIELDVALUE, TARGET>
  820. implements Binding<BEAN, TARGET> {
  821. private Binder<BEAN> binder;
  822. private HasValue<FIELDVALUE> field;
  823. private final BindingValidationStatusHandler statusHandler;
  824. private final SerializableFunction<BEAN, TARGET> getter;
  825. private final Setter<BEAN, TARGET> setter;
  826. // Not final since we temporarily remove listener while changing values
  827. private Registration onValueChange;
  828. /**
  829. * Contains all converters and validators chained together in the
  830. * correct order.
  831. */
  832. private final Converter<FIELDVALUE, TARGET> converterValidatorChain;
  833. public BindingImpl(BindingBuilderImpl<BEAN, FIELDVALUE, TARGET> builder,
  834. SerializableFunction<BEAN, TARGET> getter,
  835. Setter<BEAN, TARGET> setter) {
  836. this.binder = builder.getBinder();
  837. this.field = builder.field;
  838. this.statusHandler = builder.statusHandler;
  839. converterValidatorChain = ((Converter<FIELDVALUE, TARGET>) builder.converterValidatorChain);
  840. onValueChange = getField()
  841. .addValueChangeListener(this::handleFieldValueChange);
  842. this.getter = getter;
  843. this.setter = setter;
  844. }
  845. @Override
  846. public HasValue<FIELDVALUE> getField() {
  847. return field;
  848. }
  849. /**
  850. * Finds an appropriate locale to be used in conversion and validation.
  851. *
  852. * @return the found locale, not null
  853. */
  854. protected Locale findLocale() {
  855. Locale l = null;
  856. if (getField() instanceof Component) {
  857. l = ((Component) getField()).getLocale();
  858. }
  859. if (l == null && UI.getCurrent() != null) {
  860. l = UI.getCurrent().getLocale();
  861. }
  862. if (l == null) {
  863. l = Locale.getDefault();
  864. }
  865. return l;
  866. }
  867. @Override
  868. public BindingValidationStatus<TARGET> validate(boolean fireEvent) {
  869. Objects.requireNonNull(binder,
  870. "This Binding is no longer attached to a Binder");
  871. BindingValidationStatus<TARGET> status = doValidation();
  872. if (fireEvent) {
  873. getBinder().getValidationStatusHandler()
  874. .statusChange(new BinderValidationStatus<>(getBinder(),
  875. Arrays.asList(status),
  876. Collections.emptyList()));
  877. getBinder().fireStatusChangeEvent(status.isError());
  878. }
  879. return status;
  880. }
  881. /**
  882. * Removes this binding from its binder and unregisters the
  883. * {@code ValueChangeListener} from any bound {@code HasValue}.
  884. *
  885. * @since 8.2
  886. */
  887. @Override
  888. public void unbind() {
  889. if (onValueChange != null) {
  890. onValueChange.remove();
  891. onValueChange = null;
  892. }
  893. binder.removeBindingInternal(this);
  894. binder = null;
  895. field = null;
  896. }
  897. /**
  898. * Returns the field value run through all converters and validators,
  899. * but doesn't pass the {@link BindingValidationStatus} to any status
  900. * handler.
  901. *
  902. * @return the result of the conversion
  903. */
  904. private Result<TARGET> doConversion() {
  905. FIELDVALUE fieldValue = field.getValue();
  906. return converterValidatorChain.convertToModel(fieldValue,
  907. createValueContext());
  908. }
  909. private BindingValidationStatus<TARGET> toValidationStatus(
  910. Result<TARGET> result) {
  911. return new BindingValidationStatus<>(result, this);
  912. }
  913. /**
  914. * Returns the field value run through all converters and validators,
  915. * but doesn't pass the {@link BindingValidationStatus} to any status
  916. * handler.
  917. *
  918. * @return the validation status
  919. */
  920. private BindingValidationStatus<TARGET> doValidation() {
  921. return toValidationStatus(doConversion());
  922. }
  923. /**
  924. * Creates a value context from the current state of the binding and its
  925. * field.
  926. *
  927. * @return the value context
  928. */
  929. protected ValueContext createValueContext() {
  930. if (field instanceof Component) {
  931. return new ValueContext((Component) field, field);
  932. }
  933. return new ValueContext(null, field, findLocale());
  934. }
  935. /**
  936. * Sets the field value by invoking the getter function on the given
  937. * bean. The default listener attached to the field will be removed for
  938. * the duration of this update.
  939. *
  940. * @param bean
  941. * the bean to fetch the property value from
  942. */
  943. private void initFieldValue(BEAN bean) {
  944. assert bean != null;
  945. assert onValueChange != null;
  946. onValueChange.remove();
  947. try {
  948. getField().setValue(convertDataToFieldType(bean));
  949. } finally {
  950. onValueChange = getField()
  951. .addValueChangeListener(this::handleFieldValueChange);
  952. }
  953. }
  954. private FIELDVALUE convertDataToFieldType(BEAN bean) {
  955. return converterValidatorChain.convertToPresentation(
  956. getter.apply(bean), createValueContext());
  957. }
  958. /**
  959. * Handles the value change triggered by the bound field.
  960. *
  961. * @param event
  962. */
  963. private void handleFieldValueChange(
  964. ValueChangeEvent<FIELDVALUE> event) {
  965. // Inform binder of changes; if setBean: writeIfValid
  966. getBinder().handleFieldValueChange(this);
  967. getBinder().fireValueChangeEvent(event);
  968. }
  969. /**
  970. * Write the field value by invoking the setter function on the given
  971. * bean, if the value passes all registered validators.
  972. *
  973. * @param bean
  974. * the bean to set the property value to
  975. */
  976. private BindingValidationStatus<TARGET> writeFieldValue(BEAN bean) {
  977. assert bean != null;
  978. Result<TARGET> result = doConversion();
  979. if (setter != null) {
  980. result.ifOk(value -> setter.accept(bean, value));
  981. }
  982. return toValidationStatus(result);
  983. }
  984. /**
  985. * Returns the {@code Binder} connected to this {@code Binding}
  986. * instance.
  987. *
  988. * @return the binder
  989. */
  990. protected Binder<BEAN> getBinder() {
  991. return binder;
  992. }
  993. @Override
  994. public BindingValidationStatusHandler getValidationStatusHandler() {
  995. return statusHandler;
  996. }
  997. }
  998. /**
  999. * Wraps a validator as a converter.
  1000. * <p>
  1001. * The type of the validator must be of the same type as this converter or a
  1002. * super type of it.
  1003. *
  1004. * @param <T>
  1005. * the type of the converter
  1006. */
  1007. private static class ValidatorAsConverter<T> implements Converter<T, T> {
  1008. private final Validator<? super T> validator;
  1009. /**
  1010. * Creates a new converter wrapping the given validator.
  1011. *
  1012. * @param validator
  1013. * the validator to wrap
  1014. */
  1015. public ValidatorAsConverter(Validator<? super T> validator) {
  1016. this.validator = validator;
  1017. }
  1018. @Override
  1019. public Result<T> convertToModel(T value, ValueContext context) {
  1020. ValidationResult validationResult = validator.apply(value, context);
  1021. return new ValidationResultWrap<>(value, validationResult);
  1022. }
  1023. @Override
  1024. public T convertToPresentation(T value, ValueContext context) {
  1025. return value;
  1026. }
  1027. }
  1028. /**
  1029. * Converter decorator-strategy pattern to use initially provided "delegate"
  1030. * converter to execute its logic until the {@code setIdentity()} method is
  1031. * called. Once the method is called the class changes its behavior to the
  1032. * same as {@link Converter#identity()} behavior.
  1033. */
  1034. private static class ConverterDelegate<FIELDVALUE>
  1035. implements Converter<FIELDVALUE, FIELDVALUE> {
  1036. private Converter<FIELDVALUE, FIELDVALUE> delegate;
  1037. private ConverterDelegate(Converter<FIELDVALUE, FIELDVALUE> converter) {
  1038. delegate = converter;
  1039. }
  1040. @Override
  1041. public Result<FIELDVALUE> convertToModel(FIELDVALUE value,
  1042. ValueContext context) {
  1043. if (delegate == null) {
  1044. return Result.ok(value);
  1045. } else {
  1046. return delegate.convertToModel(value, context);
  1047. }
  1048. }
  1049. @Override
  1050. public FIELDVALUE convertToPresentation(FIELDVALUE value,
  1051. ValueContext context) {
  1052. if (delegate == null) {
  1053. return value;
  1054. } else {
  1055. return delegate.convertToPresentation(value, context);
  1056. }
  1057. }
  1058. void setIdentity() {
  1059. delegate = null;
  1060. }
  1061. }
  1062. private final PropertySet<BEAN> propertySet;
  1063. /**
  1064. * Property names that have been used for creating a binding.
  1065. */
  1066. private final Map<String, Binding<BEAN, ?>> boundProperties = new HashMap<>();
  1067. private final Map<HasValue<?>, BindingBuilder<BEAN, ?>> incompleteMemberFieldBindings = new IdentityHashMap<>();
  1068. private BEAN bean;
  1069. private final Collection<Binding<BEAN, ?>> bindings = new ArrayList<>();
  1070. private final Map<HasValue<?>, BindingBuilder<BEAN, ?>> incompleteBindings = new IdentityHashMap<>();
  1071. private final List<Validator<? super BEAN>> validators = new ArrayList<>();
  1072. private final Map<HasValue<?>, ConverterDelegate<?>> initialConverters = new IdentityHashMap<>();
  1073. private EventRouter eventRouter;
  1074. private Label statusLabel;
  1075. private BinderValidationStatusHandler<BEAN> statusHandler;
  1076. private Set<Binding<BEAN, ?>> changedBindings = new LinkedHashSet<>();
  1077. /**
  1078. * Creates a binder using a custom {@link PropertySet} implementation for
  1079. * finding and resolving property names for
  1080. * {@link #bindInstanceFields(Object)}, {@link #bind(HasValue, String)} and
  1081. * {@link BindingBuilder#bind(String)}.
  1082. *
  1083. * @param propertySet
  1084. * the property set implementation to use, not <code>null</code>.
  1085. */
  1086. protected Binder(PropertySet<BEAN> propertySet) {
  1087. Objects.requireNonNull(propertySet, "propertySet cannot be null");
  1088. this.propertySet = propertySet;
  1089. }
  1090. /**
  1091. * Informs the Binder that a value in Binding was changed. This method will
  1092. * trigger validating and writing of the whole bean if using
  1093. * {@link #setBean(Object)}. If using {@link #readBean(Object)} only the
  1094. * field validation is run.
  1095. *
  1096. * @param binding
  1097. * the binding whose value has been changed
  1098. * @since 8.2
  1099. */
  1100. protected void handleFieldValueChange(Binding<BEAN, ?> binding) {
  1101. changedBindings.add(binding);
  1102. if (getBean() != null) {
  1103. doWriteIfValid(getBean(), changedBindings);
  1104. } else {
  1105. binding.validate();
  1106. }
  1107. }
  1108. /**
  1109. * Creates a new binder that uses reflection based on the provided bean type
  1110. * to resolve bean properties.
  1111. *
  1112. * @param beanType
  1113. * the bean type to use, not <code>null</code>
  1114. */
  1115. public Binder(Class<BEAN> beanType) {
  1116. this(BeanPropertySet.get(beanType));
  1117. }
  1118. /**
  1119. * Creates a new binder without support for creating bindings based on
  1120. * property names. Use an alternative constructor, such as
  1121. * {@link Binder#Binder(Class)}, to create a binder that support creating
  1122. * bindings based on instance fields through
  1123. * {@link #bindInstanceFields(Object)}, or based on a property name through
  1124. * {@link #bind(HasValue, String)} or {@link BindingBuilder#bind(String)}.
  1125. */
  1126. public Binder() {
  1127. this(new PropertySet<BEAN>() {
  1128. @Override
  1129. public Stream<PropertyDefinition<BEAN, ?>> getProperties() {
  1130. throw new IllegalStateException(
  1131. "This Binder instance was created using the default constructor. "
  1132. + "To be able to use property names and bind to instance fields, create the binder using the Binder(Class<BEAN> beanType) constructor instead.");
  1133. }
  1134. @Override
  1135. public Optional<PropertyDefinition<BEAN, ?>> getProperty(
  1136. String name) {
  1137. throw new IllegalStateException(
  1138. "This Binder instance was created using the default constructor. "
  1139. + "To be able to use property names and bind to instance fields, create the binder using the Binder(Class<BEAN> beanType) constructor instead.");
  1140. }
  1141. });
  1142. }
  1143. /**
  1144. * Creates a binder using a custom {@link PropertySet} implementation for
  1145. * finding and resolving property names for
  1146. * {@link #bindInstanceFields(Object)}, {@link #bind(HasValue, String)} and
  1147. * {@link BindingBuilder#bind(String)}.
  1148. * <p>
  1149. * This functionality is provided as static method instead of as a public
  1150. * constructor in order to make it possible to use a custom property set
  1151. * without creating a subclass while still leaving the public constructors
  1152. * focused on the common use cases.
  1153. *
  1154. * @see Binder#Binder()
  1155. * @see Binder#Binder(Class)
  1156. *
  1157. * @param propertySet
  1158. * the property set implementation to use, not <code>null</code>.
  1159. * @return a new binder using the provided property set, not
  1160. * <code>null</code>
  1161. */
  1162. public static <BEAN> Binder<BEAN> withPropertySet(
  1163. PropertySet<BEAN> propertySet) {
  1164. return new Binder<>(propertySet);
  1165. }
  1166. /**
  1167. * Returns the bean that has been bound with {@link #bind}, or null if a
  1168. * bean is not currently bound.
  1169. *
  1170. * @return the currently bound bean if any
  1171. */
  1172. public BEAN getBean() {
  1173. return bean;
  1174. }
  1175. /**
  1176. * Creates a new binding for the given field. The returned builder may be
  1177. * further configured before invoking
  1178. * {@link BindingBuilder#bind(ValueProvider, Setter)} which completes the
  1179. * binding. Until {@code Binding.bind} is called, the binding has no effect.
  1180. * <p>
  1181. * <strong>Note:</strong> Not all {@link HasValue} implementations support
  1182. * passing {@code null} as the value. For these the Binder will
  1183. * automatically change {@code null} to a null representation provided by
  1184. * {@link HasValue#getEmptyValue()}. This conversion is one-way only, if you
  1185. * want to have a two-way mapping back to {@code null}, use
  1186. * {@link BindingBuilder#withNullRepresentation(Object)}.
  1187. *
  1188. * @param <FIELDVALUE>
  1189. * the value type of the field
  1190. * @param field
  1191. * the field to be bound, not null
  1192. * @return the new binding
  1193. *
  1194. * @see #bind(HasValue, ValueProvider, Setter)
  1195. */
  1196. public <FIELDVALUE> BindingBuilder<BEAN, FIELDVALUE> forField(
  1197. HasValue<FIELDVALUE> field) {
  1198. Objects.requireNonNull(field, "field cannot be null");
  1199. // clear previous errors for this field and any bean level validation
  1200. clearError(field);
  1201. getStatusLabel().ifPresent(label -> label.setValue(""));
  1202. return createBinding(field, createNullRepresentationAdapter(field),
  1203. this::handleValidationStatus)
  1204. .withValidator(field.getDefaultValidator());
  1205. }
  1206. /**
  1207. * Creates a new binding for the given field. The returned builder may be
  1208. * further configured before invoking {@link #bindInstanceFields(Object)}.
  1209. * Unlike with the {@link #forField(HasValue)} method, no explicit call to
  1210. * {@link BindingBuilder#bind(String)} is needed to complete this binding in
  1211. * the case that the name of the field matches a field name found in the
  1212. * bean.
  1213. *
  1214. * @param <FIELDVALUE>
  1215. * the value type of the field
  1216. * @param field
  1217. * the field to be bound, not null
  1218. * @return the new binding builder
  1219. *
  1220. * @see #forField(HasValue)
  1221. * @see #bindInstanceFields(Object)
  1222. */
  1223. public <FIELDVALUE> BindingBuilder<BEAN, FIELDVALUE> forMemberField(
  1224. HasValue<FIELDVALUE> field) {
  1225. incompleteMemberFieldBindings.put(field, null);
  1226. return forField(field);
  1227. }
  1228. /**
  1229. * Binds a field to a bean property represented by the given getter and
  1230. * setter pair. The functions are used to update the field value from the
  1231. * property and to store the field value to the property, respectively.
  1232. * <p>
  1233. * Use the {@link #forField(HasValue)} overload instead if you want to
  1234. * further configure the new binding.
  1235. * <p>
  1236. * <strong>Note:</strong> Not all {@link HasValue} implementations support
  1237. * passing {@code null} as the value. For these the Binder will
  1238. * automatically change {@code null} to a null representation provided by
  1239. * {@link HasValue#getEmptyValue()}. This conversion is one-way only, if you
  1240. * want to have a two-way mapping back to {@code null}, use
  1241. * {@link #forField(HasValue)} and
  1242. * {@link BindingBuilder#withNullRepresentation(Object)}.
  1243. * <p>
  1244. * When a bean is bound with {@link Binder#setBean(BEAN)}, the field value
  1245. * is set to the return value of the given getter. The property value is
  1246. * then updated via the given setter whenever the field value changes. The
  1247. * setter may be null; in that case the property value is never updated and
  1248. * the binding is said to be <i>read-only</i>.
  1249. * <p>
  1250. * If the Binder is already bound to some bean, the newly bound field is
  1251. * associated with the corresponding bean property as described above.
  1252. * <p>
  1253. * The getter and setter can be arbitrary functions, for instance
  1254. * implementing user-defined conversion or validation. However, in the most
  1255. * basic use case you can simply pass a pair of method references to this
  1256. * method as follows:
  1257. *
  1258. * <pre>
  1259. * class Person {
  1260. * public String getName() { ... }
  1261. * public void setName(String name) { ... }
  1262. * }
  1263. *
  1264. * TextField nameField = new TextField();
  1265. * binder.bind(nameField, Person::getName, Person::setName);
  1266. * </pre>
  1267. *
  1268. * @param <FIELDVALUE>
  1269. * the value type of the field
  1270. * @param field
  1271. * the field to bind, not null
  1272. * @param getter
  1273. * the function to get the value of the property to the field,
  1274. * not null
  1275. * @param setter
  1276. * the function to write the field value to the property or null
  1277. * if read-only
  1278. * @return the newly created binding
  1279. */
  1280. public <FIELDVALUE> Binding<BEAN, FIELDVALUE> bind(
  1281. HasValue<FIELDVALUE> field, ValueProvider<BEAN, FIELDVALUE> getter,
  1282. Setter<BEAN, FIELDVALUE> setter) {
  1283. return forField(field).bind(getter, setter);
  1284. }
  1285. /**
  1286. * Binds the given field to the property with the given name. The getter and
  1287. * setter of the property are looked up using a {@link PropertySet}.
  1288. * <p>
  1289. * For a <code>Binder</code> created using the {@link Binder#Binder(Class)}
  1290. * constructor, introspection will be used to find a Java Bean property. If
  1291. * a JSR-303 bean validation implementation is present on the classpath, a
  1292. * {@link BeanValidator} is also added to the binding.
  1293. * <p>
  1294. * The property must have an accessible getter method. It need not have an
  1295. * accessible setter; in that case the property value is never updated and
  1296. * the binding is said to be <i>read-only</i>.
  1297. *
  1298. * @param <FIELDVALUE>
  1299. * the value type of the field to bind
  1300. * @param field
  1301. * the field to bind, not null
  1302. * @param propertyName
  1303. * the name of the property to bind, not null
  1304. * @return the newly created binding
  1305. *
  1306. * @throws IllegalArgumentException
  1307. * if the property name is invalid
  1308. * @throws IllegalArgumentException
  1309. * if the property has no accessible getter
  1310. * @throws IllegalStateException
  1311. * if the binder is not configured with an appropriate
  1312. * {@link PropertySet}
  1313. *
  1314. * @see #bind(HasValue, ValueProvider, Setter)
  1315. */
  1316. public <FIELDVALUE> Binding<BEAN, FIELDVALUE> bind(
  1317. HasValue<FIELDVALUE> field, String propertyName) {
  1318. return forField(field).bind(propertyName);
  1319. }
  1320. /**
  1321. * Binds the given bean to all the fields added to this Binder. A
  1322. * {@code null} value removes a currently bound bean.
  1323. * <p>
  1324. * When a bean is bound, the field values are updated by invoking their
  1325. * corresponding getter functions. Any changes to field values are reflected
  1326. * back to their corresponding property values of the bean as long as the
  1327. * bean is bound.
  1328. * <p>
  1329. * Any change made in the fields also runs validation for the field
  1330. * {@link Binding} and bean level validation for this binder (bean level
  1331. * validators are added using {@link Binder#withValidator(Validator)}.
  1332. *
  1333. * @see #readBean(Object)
  1334. * @see #writeBean(Object)
  1335. * @see #writeBeanIfValid(Object)
  1336. *
  1337. * @param bean
  1338. * the bean to edit, or {@code null} to remove a currently bound
  1339. * bean and clear bound fields
  1340. */
  1341. public void setBean(BEAN bean) {
  1342. checkBindingsCompleted("setBean");
  1343. if (bean == null) {
  1344. if (this.bean != null) {
  1345. doRemoveBean(true);
  1346. clearFields();
  1347. }
  1348. } else {
  1349. doRemoveBean(false);
  1350. this.bean = bean;
  1351. getBindings().forEach(b -> b.initFieldValue(bean));
  1352. // if there has been field value change listeners that trigger
  1353. // validation, need to make sure the validation errors are cleared
  1354. getValidationStatusHandler().statusChange(
  1355. BinderValidationStatus.createUnresolvedStatus(this));
  1356. fireStatusChangeEvent(false);
  1357. }
  1358. }
  1359. /**
  1360. * Removes the currently set bean and clears bound fields. If there is no
  1361. * bound bean, does nothing.
  1362. * <p>
  1363. * This is a shorthand for {@link #setBean(Object)} with {@code null} bean.
  1364. */
  1365. public void removeBean() {
  1366. setBean(null);
  1367. }
  1368. /**
  1369. * Reads the bound property values from the given bean to the corresponding
  1370. * fields.
  1371. * <p>
  1372. * The bean is not otherwise associated with this binder; in particular its
  1373. * property values are not bound to the field value changes. To achieve
  1374. * that, use {@link #setBean(BEAN)}.
  1375. *
  1376. * @see #setBean(Object)
  1377. * @see #writeBeanIfValid(Object)
  1378. * @see #writeBean(Object)
  1379. *
  1380. * @param bean
  1381. * the bean whose property values to read or {@code null} to
  1382. * clear bound fields
  1383. */
  1384. public void readBean(BEAN bean) {
  1385. checkBindingsCompleted("readBean");
  1386. if (bean == null) {
  1387. clearFields();
  1388. } else {
  1389. changedBindings.clear();
  1390. getBindings().forEach(binding -> binding.initFieldValue(bean));
  1391. getValidationStatusHandler().statusChange(
  1392. BinderValidationStatus.createUnresolvedStatus(this));
  1393. fireStatusChangeEvent(false);
  1394. }
  1395. }
  1396. /**
  1397. * Writes changes from the bound fields to the given bean if all validators
  1398. * (binding and bean level) pass.
  1399. * <p>
  1400. * If any field binding validator fails, no values are written and a
  1401. * {@code ValidationException} is thrown.
  1402. * <p>
  1403. * If all field level validators pass, the given bean is updated and bean
  1404. * level validators are run on the updated bean. If any bean level validator
  1405. * fails, the bean updates are reverted and a {@code ValidationException} is
  1406. * thrown.
  1407. *
  1408. * @see #writeBeanIfValid(Object)
  1409. * @see #readBean(Object)
  1410. * @see #setBean(Object)
  1411. *
  1412. * @param bean
  1413. * the object to which to write the field values, not
  1414. * {@code null}
  1415. * @throws ValidationException
  1416. * if some of the bound field values fail to validate
  1417. */
  1418. public void writeBean(BEAN bean) throws ValidationException {
  1419. BinderValidationStatus<BEAN> status = doWriteIfValid(bean,
  1420. new ArrayList<>(bindings));
  1421. if (status.hasErrors()) {
  1422. throw new ValidationException(status.getFieldValidationErrors(),
  1423. status.getBeanValidationErrors());
  1424. }
  1425. }
  1426. /**
  1427. * Writes changes from the bound fields to the given bean if all validators
  1428. * (binding and bean level) pass.
  1429. * <p>
  1430. * If any field binding validator fails, no values are written and
  1431. * <code>false</code> is returned.
  1432. * <p>
  1433. * If all field level validators pass, the given bean is updated and bean
  1434. * level validators are run on the updated bean. If any bean level validator
  1435. * fails, the bean updates are reverted and <code>false</code> is returned.
  1436. *
  1437. * @see #writeBean(Object)
  1438. * @see #readBean(Object)
  1439. * @see #setBean(Object)
  1440. *
  1441. * @param bean
  1442. * the object to which to write the field values, not
  1443. * {@code null}
  1444. * @return {@code true} if there was no validation errors and the bean was
  1445. * updated, {@code false} otherwise
  1446. */
  1447. public boolean writeBeanIfValid(BEAN bean) {
  1448. return doWriteIfValid(bean, new ArrayList<>(bindings)).isOk();
  1449. }
  1450. /**
  1451. * Writes the field values into the given bean if all field level validators
  1452. * pass. Runs bean level validators on the bean after writing.
  1453. * <p>
  1454. * <strong>Note:</strong> The collection of bindings is cleared on
  1455. * successful save.
  1456. *
  1457. * @param bean
  1458. * the bean to write field values into
  1459. * @param bindings
  1460. * the set of bindings to write to the bean
  1461. * @return a list of field validation errors if such occur, otherwise a list
  1462. * of bean validation errors.
  1463. */
  1464. @SuppressWarnings({ "unchecked" })
  1465. private BinderValidationStatus<BEAN> doWriteIfValid(BEAN bean,
  1466. Collection<Binding<BEAN, ?>> bindings) {
  1467. Objects.requireNonNull(bean, "bean cannot be null");
  1468. List<ValidationResult> binderResults = Collections.emptyList();
  1469. // First run fields level validation, if no validation errors then
  1470. // update bean
  1471. List<BindingValidationStatus<?>> bindingResults = bindings.stream()
  1472. .map(b -> b.validate(false)).collect(Collectors.toList());
  1473. if (bindingResults.stream()
  1474. .noneMatch(BindingValidationStatus::isError)) {
  1475. // Store old bean values so we can restore them if validators fail
  1476. Map<Binding<BEAN, ?>, Object> oldValues = getBeanState(bean,
  1477. bindings);
  1478. bindings.forEach(binding -> ((BindingImpl<BEAN, ?, ?>) binding)
  1479. .writeFieldValue(bean));
  1480. // Now run bean level validation against the updated bean
  1481. binderResults = validateBean(bean);
  1482. if (binderResults.stream().anyMatch(ValidationResult::isError)) {
  1483. // Bean validator failed, revert values
  1484. restoreBeanState(bean, oldValues);
  1485. } else if (bean.equals(getBean())) {
  1486. /*
  1487. * Changes have been successfully saved. The set is only cleared
  1488. * when the changes are stored in the currently set bean.
  1489. */
  1490. bindings.clear();
  1491. } else if (getBean() == null) {
  1492. /*
  1493. * When using readBean and writeBean there is no knowledge of
  1494. * which bean the changes come from or are stored in. Binder is
  1495. * no longer "changed" when saved succesfully to any bean.
  1496. */
  1497. changedBindings.clear();
  1498. }
  1499. }
  1500. // Generate status object and fire events.
  1501. BinderValidationStatus<BEAN> status = new BinderValidationStatus<>(this,
  1502. bindingResults, binderResults);
  1503. getValidationStatusHandler().statusChange(status);
  1504. fireStatusChangeEvent(!status.isOk());
  1505. return status;
  1506. }
  1507. /**
  1508. * Restores the state of the bean from the given values.
  1509. *
  1510. * @param bean
  1511. * the bean
  1512. * @param oldValues
  1513. * the old values
  1514. *
  1515. * @since 8.2
  1516. */
  1517. @SuppressWarnings({ "unchecked", "rawtypes" })
  1518. protected void restoreBeanState(BEAN bean,
  1519. Map<Binding<BEAN, ?>, Object> oldValues) {
  1520. getBindings().stream().filter(oldValues::containsKey)
  1521. .forEach(binding -> {
  1522. Setter setter = binding.setter;
  1523. if (setter != null) {
  1524. setter.accept(bean, oldValues.get(binding));
  1525. }
  1526. });
  1527. }
  1528. /**
  1529. * Stores the state of the given bean.
  1530. *
  1531. * @param bean
  1532. * the bean to store the state of
  1533. * @param bindings
  1534. * the bindings to store
  1535. *
  1536. * @return map from binding to value
  1537. *
  1538. * @since 8.2
  1539. */
  1540. @SuppressWarnings({ "unchecked", "rawtypes" })
  1541. protected Map<Binding<BEAN, ?>, Object> getBeanState(BEAN bean,
  1542. Collection<Binding<BEAN, ?>> bindings) {
  1543. Map<Binding<BEAN, ?>, Object> oldValues = new HashMap<>();
  1544. bindings.stream().map(binding -> (BindingImpl) binding)
  1545. .filter(binding -> binding.setter != null)
  1546. .forEach(binding -> oldValues.put(binding,
  1547. binding.getter.apply(bean)));
  1548. return oldValues;
  1549. }
  1550. /**
  1551. * Adds an bean level validator.
  1552. * <p>
  1553. * Bean level validators are applied on the bean instance after the bean is
  1554. * updated. If the validators fail, the bean instance is reverted to its
  1555. * previous state.
  1556. *
  1557. * @see #writeBean(Object)
  1558. * @see #writeBeanIfValid(Object)
  1559. * @see #withValidator(SerializablePredicate, String)
  1560. * @see #withValidator(SerializablePredicate, ErrorMessageProvider)
  1561. *
  1562. * @param validator
  1563. * the validator to add, not null
  1564. * @return this binder, for chaining
  1565. */
  1566. public Binder<BEAN> withValidator(Validator<? super BEAN> validator) {
  1567. Objects.requireNonNull(validator, "validator cannot be null");
  1568. validators.add(validator);
  1569. return this;
  1570. }
  1571. /**
  1572. * A convenience method to add a validator to this binder using the
  1573. * {@link Validator#from(SerializablePredicate, String)} factory method.
  1574. * <p>
  1575. * Bean level validators are applied on the bean instance after the bean is
  1576. * updated. If the validators fail, the bean instance is reverted to its
  1577. * previous state.
  1578. *
  1579. * @see #writeBean(Object)
  1580. * @see #writeBeanIfValid(Object)
  1581. * @see #withValidator(Validator)
  1582. * @see #withValidator(SerializablePredicate, ErrorMessageProvider)
  1583. *
  1584. * @param predicate
  1585. * the predicate performing validation, not null
  1586. * @param message
  1587. * the error message to report in case validation failure
  1588. * @return this binder, for chaining
  1589. */
  1590. public Binder<BEAN> withValidator(SerializablePredicate<BEAN> predicate,
  1591. String message) {
  1592. return withValidator(Validator.from(predicate, message));
  1593. }
  1594. /**
  1595. * A convenience method to add a validator to this binder using the
  1596. * {@link Validator#from(SerializablePredicate, ErrorMessageProvider)}
  1597. * factory method.
  1598. * <p>
  1599. * Bean level validators are applied on the bean instance after the bean is
  1600. * updated. If the validators fail, the bean instance is reverted to its
  1601. * previous state.
  1602. *
  1603. * @see #writeBean(Object)
  1604. * @see #writeBeanIfValid(Object)
  1605. * @see #withValidator(Validator)
  1606. * @see #withValidator(SerializablePredicate, String)
  1607. *
  1608. * @param predicate
  1609. * the predicate performing validation, not null
  1610. * @param errorMessageProvider
  1611. * the provider to generate error messages, not null
  1612. * @return this binder, for chaining
  1613. */
  1614. public Binder<BEAN> withValidator(SerializablePredicate<BEAN> predicate,
  1615. ErrorMessageProvider errorMessageProvider) {
  1616. return withValidator(Validator.from(predicate, errorMessageProvider));
  1617. }
  1618. /**
  1619. * Clear all the bound fields for this binder.
  1620. */
  1621. private void clearFields() {
  1622. bindings.forEach(binding -> {
  1623. binding.getField().clear();
  1624. clearError(binding.getField());
  1625. });
  1626. if (hasChanges()) {
  1627. fireStatusChangeEvent(false);
  1628. }
  1629. changedBindings.clear();
  1630. }
  1631. /**
  1632. * Validates the values of all bound fields and returns the validation
  1633. * status.
  1634. * <p>
  1635. * If all field level validators pass, and {@link #setBean(Object)} has been
  1636. * used to bind to a bean, bean level validators are run for that bean. Bean
  1637. * level validators are ignored if there is no bound bean or if any field
  1638. * level validator fails.
  1639. * <p>
  1640. * <strong>Note:</strong> This method will attempt to temporarily apply all
  1641. * current changes to the bean and run full bean validation for it. The
  1642. * changes are reverted after bean validation.
  1643. *
  1644. * @return validation status for the binder
  1645. */
  1646. public BinderValidationStatus<BEAN> validate() {
  1647. return validate(true);
  1648. }
  1649. /**
  1650. * Validates the values of all bound fields and returns the validation
  1651. * status. This method can skip firing the event, based on the given
  1652. * {@code boolean}.
  1653. *
  1654. * @param fireEvent
  1655. * {@code true} to fire validation status events; {@code false}
  1656. * to not
  1657. * @return validation status for the binder
  1658. *
  1659. * @since 8.2
  1660. */
  1661. protected BinderValidationStatus<BEAN> validate(boolean fireEvent) {
  1662. if (getBean() == null && !validators.isEmpty()) {
  1663. throw new IllegalStateException("Cannot validate binder: "
  1664. + "bean level validators have been configured "
  1665. + "but no bean is currently set");
  1666. }
  1667. List<BindingValidationStatus<?>> bindingStatuses = validateBindings();
  1668. BinderValidationStatus<BEAN> validationStatus;
  1669. if (validators.isEmpty() || bindingStatuses.stream()
  1670. .anyMatch(BindingValidationStatus::isError)) {
  1671. validationStatus = new BinderValidationStatus<>(this,
  1672. bindingStatuses, Collections.emptyList());
  1673. } else {
  1674. Map<Binding<BEAN, ?>, Object> beanState = getBeanState(getBean(),
  1675. changedBindings);
  1676. changedBindings
  1677. .forEach(binding -> ((BindingImpl<BEAN, ?, ?>) binding)
  1678. .writeFieldValue(getBean()));
  1679. validationStatus = new BinderValidationStatus<>(this,
  1680. bindingStatuses, validateBean(getBean()));
  1681. restoreBeanState(getBean(), beanState);
  1682. }
  1683. if (fireEvent) {
  1684. getValidationStatusHandler().statusChange(validationStatus);
  1685. fireStatusChangeEvent(validationStatus.hasErrors());
  1686. }
  1687. return validationStatus;
  1688. }
  1689. /**
  1690. * Runs all currently configured field level validators, as well as all bean
  1691. * level validators if a bean is currently set with
  1692. * {@link #setBean(Object)}, and returns whether any of the validators
  1693. * failed.
  1694. * <p>
  1695. * <b>Note:</b> Calling this method will not trigger status change events,
  1696. * unlike {@link #validate()} and will not modify the UI. To also update
  1697. * error indicators on fields, use {@code validate().isOk()}.
  1698. * <p>
  1699. * <strong>Note:</strong> This method will attempt to temporarily apply all
  1700. * current changes to the bean and run full bean validation for it. The
  1701. * changes are reverted after bean validation.
  1702. *
  1703. * @see #validate()
  1704. *
  1705. * @return whether this binder is in a valid state
  1706. * @throws IllegalStateException
  1707. * if bean level validators have been configured and no bean is
  1708. * currently set
  1709. */
  1710. public boolean isValid() {
  1711. return validate(false).isOk();
  1712. }
  1713. /**
  1714. * Validates the bindings and returns the result of the validation as a list
  1715. * of validation statuses.
  1716. * <p>
  1717. * Does not run bean validators.
  1718. *
  1719. * @see #validateBean(Object)
  1720. *
  1721. * @return an immutable list of validation results for bindings
  1722. */
  1723. private List<BindingValidationStatus<?>> validateBindings() {
  1724. return getBindings().stream().map(BindingImpl::doValidation)
  1725. .collect(Collectors.toList());
  1726. }
  1727. /**
  1728. * Validates the {@code bean} using validators added using
  1729. * {@link #withValidator(Validator)} and returns the result of the
  1730. * validation as a list of validation results.
  1731. * <p>
  1732. *
  1733. * @see #withValidator(Validator)
  1734. *
  1735. * @param bean
  1736. * the bean to validate
  1737. * @return a list of validation errors or an empty list if validation
  1738. * succeeded
  1739. */
  1740. private List<ValidationResult> validateBean(BEAN bean) {
  1741. Objects.requireNonNull(bean, "bean cannot be null");
  1742. List<ValidationResult> results = Collections.unmodifiableList(validators
  1743. .stream()
  1744. .map(validator -> validator.apply(bean, new ValueContext()))
  1745. .collect(Collectors.toList()));
  1746. return results;
  1747. }
  1748. /**
  1749. * Sets the label to show the binder level validation errors not related to
  1750. * any specific field.
  1751. * <p>
  1752. * Only the one validation error message is shown in this label at a time.
  1753. * <p>
  1754. * This is a convenience method for
  1755. * {@link #setValidationStatusHandler(BinderValidationStatusHandler)}, which
  1756. * means that this method cannot be used after the handler has been set.
  1757. * Also the handler cannot be set after this label has been set.
  1758. *
  1759. * @param statusLabel
  1760. * the status label to set
  1761. * @see #setValidationStatusHandler(BinderValidationStatusHandler)
  1762. * @see BindingBuilder#withStatusLabel(Label)
  1763. */
  1764. public void setStatusLabel(Label statusLabel) {
  1765. if (statusHandler != null) {
  1766. throw new IllegalStateException("Cannot set status label if a "
  1767. + BinderValidationStatusHandler.class.getSimpleName()
  1768. + " has already been set.");
  1769. }
  1770. this.statusLabel = statusLabel;
  1771. }
  1772. /**
  1773. * Gets the status label or an empty optional if none has been set.
  1774. *
  1775. * @return the optional status label
  1776. * @see #setStatusLabel(Label)
  1777. */
  1778. public Optional<Label> getStatusLabel() {
  1779. return Optional.ofNullable(statusLabel);
  1780. }
  1781. /**
  1782. * Sets the status handler to track form status changes.
  1783. * <p>
  1784. * Setting this handler will override the default behavior, which is to let
  1785. * fields show their validation status messages and show binder level
  1786. * validation errors or OK status in the label set with
  1787. * {@link #setStatusLabel(Label)}.
  1788. * <p>
  1789. * This handler cannot be set after the status label has been set with
  1790. * {@link #setStatusLabel(Label)}, or {@link #setStatusLabel(Label)} cannot
  1791. * be used after this handler has been set.
  1792. *
  1793. * @param statusHandler
  1794. * the status handler to set, not <code>null</code>
  1795. * @throws NullPointerException
  1796. * for <code>null</code> status handler
  1797. * @see #setStatusLabel(Label)
  1798. * @see BindingBuilder#withValidationStatusHandler(BindingValidationStatusHandler)
  1799. */
  1800. public void setValidationStatusHandler(
  1801. BinderValidationStatusHandler<BEAN> statusHandler) {
  1802. Objects.requireNonNull(statusHandler, "Cannot set a null "
  1803. + BinderValidationStatusHandler.class.getSimpleName());
  1804. if (statusLabel != null) {
  1805. throw new IllegalStateException("Cannot set "
  1806. + BinderValidationStatusHandler.class.getSimpleName()
  1807. + " if a status label has already been set.");
  1808. }
  1809. this.statusHandler = statusHandler;
  1810. }
  1811. /**
  1812. * Gets the status handler of this form.
  1813. * <p>
  1814. * If none has been set with
  1815. * {@link #setValidationStatusHandler(BinderValidationStatusHandler)}, the
  1816. * default implementation is returned.
  1817. *
  1818. * @return the status handler used, never <code>null</code>
  1819. * @see #setValidationStatusHandler(BinderValidationStatusHandler)
  1820. */
  1821. public BinderValidationStatusHandler<BEAN> getValidationStatusHandler() {
  1822. return Optional.ofNullable(statusHandler)
  1823. .orElse(this::handleBinderValidationStatus);
  1824. }
  1825. /**
  1826. * Adds status change listener to the binder.
  1827. * <p>
  1828. * The {@link Binder} status is changed whenever any of the following
  1829. * happens:
  1830. * <ul>
  1831. * <li>if it's bound and any of its bound field or select has been changed
  1832. * <li>{@link #writeBean(Object)} or {@link #writeBeanIfValid(Object)} is
  1833. * called
  1834. * <li>{@link #readBean(Object)} is called
  1835. * <li>{@link #setBean(Object)} is called
  1836. * <li>{@link #removeBean()} is called
  1837. * <li>{@link BindingBuilder#bind(ValueProvider, Setter)} is called
  1838. * <li>{@link Binder#validate()} or {@link Binding#validate()} is called
  1839. * </ul>
  1840. *
  1841. * @see #readBean(Object)
  1842. * @see #writeBean(Object)
  1843. * @see #writeBeanIfValid(Object)
  1844. * @see #setBean(Object)
  1845. * @see #removeBean()
  1846. * @see #forField(HasValue)
  1847. * @see #validate()
  1848. * @see Binding#validate()
  1849. *
  1850. * @param listener
  1851. * status change listener to add, not null
  1852. * @return a registration for the listener
  1853. */
  1854. public Registration addStatusChangeListener(StatusChangeListener listener) {
  1855. return getEventRouter().addListener(StatusChangeEvent.class, listener,
  1856. ReflectTools.getMethod(StatusChangeListener.class));
  1857. }
  1858. /**
  1859. * Adds field value change listener to all the fields in the binder.
  1860. * <p>
  1861. * Added listener is notified every time whenever any bound field value is
  1862. * changed. The same functionality can be achieved by adding a
  1863. * {@link ValueChangeListener} to all fields in the {@link Binder}.
  1864. * <p>
  1865. * The listener is added to all fields regardless of whether the method is
  1866. * invoked before or after field is bound.
  1867. *
  1868. * @see ValueChangeEvent
  1869. * @see ValueChangeListener
  1870. *
  1871. * @param listener
  1872. * a field value change listener
  1873. * @return a registration for the listener
  1874. */
  1875. public Registration addValueChangeListener(
  1876. ValueChangeListener<?> listener) {
  1877. return getEventRouter().addListener(ValueChangeEvent.class, listener,
  1878. ReflectTools.getMethod(ValueChangeListener.class));
  1879. }
  1880. /**
  1881. * Creates a new binding with the given field.
  1882. *
  1883. * @param <FIELDVALUE>
  1884. * the value type of the field
  1885. * @param <TARGET>
  1886. * the target data type
  1887. * @param field
  1888. * the field to bind, not null
  1889. * @param converter
  1890. * the converter for converting between FIELDVALUE and TARGET
  1891. * types, not null
  1892. * @param handler
  1893. * the handler to notify of status changes, not null
  1894. * @return the new incomplete binding
  1895. */
  1896. protected <FIELDVALUE, TARGET> BindingBuilder<BEAN, TARGET> createBinding(
  1897. HasValue<FIELDVALUE> field, Converter<FIELDVALUE, TARGET> converter,
  1898. BindingValidationStatusHandler handler) {
  1899. BindingBuilder<BEAN, TARGET> newBinding = doCreateBinding(field,
  1900. converter, handler);
  1901. if (incompleteMemberFieldBindings.containsKey(field)) {
  1902. incompleteMemberFieldBindings.put(field, newBinding);
  1903. }
  1904. incompleteBindings.put(field, newBinding);
  1905. return newBinding;
  1906. }
  1907. protected <FIELDVALUE, TARGET> BindingBuilder<BEAN, TARGET> doCreateBinding(
  1908. HasValue<FIELDVALUE> field, Converter<FIELDVALUE, TARGET> converter,
  1909. BindingValidationStatusHandler handler) {
  1910. return new BindingBuilderImpl<>(this, field, converter, handler);
  1911. }
  1912. /**
  1913. * Clears the error condition of the given field, if any. The default
  1914. * implementation clears the
  1915. * {@link AbstractComponent#setComponentError(ErrorMessage) component error}
  1916. * of the field if it is a Component, otherwise does nothing.
  1917. *
  1918. * @param field
  1919. * the field with an invalid value
  1920. */
  1921. protected void clearError(HasValue<?> field) {
  1922. if (field instanceof AbstractComponent) {
  1923. ((AbstractComponent) field).setComponentError(null);
  1924. }
  1925. }
  1926. /**
  1927. * Handles a validation error emitted when trying to write the value of the
  1928. * given field. The default implementation sets the
  1929. * {@link AbstractComponent#setComponentError(ErrorMessage) component error}
  1930. * of the field if it is a Component, otherwise does nothing.
  1931. *
  1932. * @param field
  1933. * the field with the invalid value
  1934. * @param result
  1935. * the validation error result
  1936. *
  1937. * @since 8.2
  1938. */
  1939. protected void handleError(HasValue<?> field, ValidationResult result) {
  1940. result.getErrorLevel().ifPresent(level -> {
  1941. if (field instanceof AbstractComponent) {
  1942. ((AbstractComponent) field).setComponentError(new UserError(
  1943. result.getErrorMessage(), ContentMode.TEXT, level));
  1944. }
  1945. });
  1946. }
  1947. /**
  1948. * Default {@link BindingValidationStatusHandler} functional method
  1949. * implementation.
  1950. *
  1951. * @param status
  1952. * the validation status
  1953. */
  1954. protected void handleValidationStatus(BindingValidationStatus<?> status) {
  1955. HasValue<?> source = status.getField();
  1956. clearError(source);
  1957. if (status.isError()) {
  1958. Optional<ValidationResult> firstError = status
  1959. .getValidationResults().stream()
  1960. .filter(ValidationResult::isError).findFirst();
  1961. if (firstError.isPresent()) {
  1962. // Failed with a Validation error
  1963. handleError(source, firstError.get());
  1964. } else {
  1965. // Conversion error
  1966. status.getResult()
  1967. .ifPresent(result -> handleError(source, result));
  1968. }
  1969. } else {
  1970. // Show first non-error ValidationResult message.
  1971. status.getValidationResults().stream()
  1972. .filter(result -> result.getErrorLevel().isPresent())
  1973. .findFirst()
  1974. .ifPresent(result -> handleError(source, result));
  1975. }
  1976. }
  1977. /**
  1978. * Returns the bindings for this binder.
  1979. *
  1980. * @return a list of the bindings
  1981. */
  1982. protected Collection<BindingImpl<BEAN, ?, ?>> getBindings() {
  1983. return bindings.stream().map(b -> ((BindingImpl<BEAN, ?, ?>) b))
  1984. .collect(Collectors.toList());
  1985. }
  1986. /**
  1987. * The default binder level status handler.
  1988. * <p>
  1989. * Passes all field related results to the Binding status handlers. All
  1990. * other status changes are displayed in the status label, if one has been
  1991. * set with {@link #setStatusLabel(Label)}.
  1992. *
  1993. * @param binderStatus
  1994. * status of validation results from binding and/or bean level
  1995. * validators
  1996. */
  1997. protected void handleBinderValidationStatus(
  1998. BinderValidationStatus<BEAN> binderStatus) {
  1999. // let field events go to binding status handlers
  2000. binderStatus.notifyBindingValidationStatusHandlers();
  2001. // show first possible error or OK status in the label if set
  2002. if (getStatusLabel().isPresent()) {
  2003. String statusMessage = binderStatus.getBeanValidationErrors()
  2004. .stream().findFirst().map(ValidationResult::getErrorMessage)
  2005. .orElse("");
  2006. getStatusLabel().get().setValue(statusMessage);
  2007. }
  2008. }
  2009. /**
  2010. * Check whether any of the bound fields' have uncommitted changes since
  2011. * last explicit call to {@link #readBean(Object)}, {@link #removeBean()},
  2012. * {@link #writeBean(Object)} or {@link #writeBeanIfValid(Object)}.
  2013. * Unsuccessful write operations will not affect this value.
  2014. * <p>
  2015. * Note that if you use {@link #setBean(Object)} method, Binder tries to
  2016. * commit changes as soon as all validators have passed. Thus, when using
  2017. * this method with it seldom makes sense and almost always returns false.
  2018. *
  2019. * Return values for each case are compiled into the following table:
  2020. *
  2021. * <p>
  2022. *
  2023. * <table>
  2024. * <tr>
  2025. * <td></td>
  2026. * <td>After readBean, setBean or removeBean</td>
  2027. * <td>After valid user changes</td>
  2028. * <td>After invalid user changes</td>
  2029. * <td>After successful writeBean or writeBeanIfValid</td>
  2030. * <td>After unsuccessful writeBean or writeBeanIfValid</td>
  2031. * </tr>
  2032. * <tr>
  2033. * <td>A bean is currently bound</td>
  2034. * <td>{@code false}</td>
  2035. * <td>{@code false}</td>
  2036. * <td>{@code true}</td>
  2037. * <td>{@code false}</td>
  2038. * <td>no change</td>
  2039. * </tr>
  2040. * <tr>
  2041. * <td>No bean is currently bound</td>
  2042. * <td>{@code false}</td>
  2043. * <td>{@code true}</td>
  2044. * <td>{@code true}</td>
  2045. * <td>{@code false}</td>
  2046. * <td>no change</td>
  2047. * </tr>
  2048. * </table>
  2049. *
  2050. * @return whether any bound field's value has changed since last call to
  2051. * setBean, readBean, writeBean or writeBeanIfValid
  2052. */
  2053. public boolean hasChanges() {
  2054. return !changedBindings.isEmpty();
  2055. }
  2056. /**
  2057. * Sets the read only state to the given value for all currently bound
  2058. * fields.
  2059. * <p>
  2060. * This is just a shorthand for calling setReadOnly for all currently bound
  2061. * fields. It means that fields bound after this method call won't be set
  2062. * read-only.
  2063. *
  2064. * @param fieldsReadOnly
  2065. * true to set the fields to read only, false to set them to read
  2066. * write
  2067. */
  2068. public void setReadOnly(boolean fieldsReadOnly) {
  2069. getBindings().stream().map(BindingImpl::getField)
  2070. .forEach(field -> field.setReadOnly(fieldsReadOnly));
  2071. }
  2072. /**
  2073. * Returns the event router for this binder.
  2074. *
  2075. * @return the event router, not null
  2076. */
  2077. protected EventRouter getEventRouter() {
  2078. if (eventRouter == null) {
  2079. eventRouter = new EventRouter();
  2080. }
  2081. return eventRouter;
  2082. }
  2083. /**
  2084. * Configures the {@code binding} with the property definition
  2085. * {@code definition} before it's being bound.
  2086. *
  2087. * @param binding
  2088. * a binding to configure
  2089. * @param definition
  2090. * a property definition information
  2091. * @return the new configured binding
  2092. */
  2093. protected BindingBuilder<BEAN, ?> configureBinding(
  2094. BindingBuilder<BEAN, ?> binding,
  2095. PropertyDefinition<BEAN, ?> definition) {
  2096. return binding;
  2097. }
  2098. private void doRemoveBean(boolean fireStatusEvent) {
  2099. changedBindings.clear();
  2100. if (bean != null) {
  2101. bean = null;
  2102. }
  2103. getValidationStatusHandler().statusChange(
  2104. BinderValidationStatus.createUnresolvedStatus(this));
  2105. if (fireStatusEvent) {
  2106. fireStatusChangeEvent(false);
  2107. }
  2108. }
  2109. private void fireStatusChangeEvent(boolean hasValidationErrors) {
  2110. getEventRouter()
  2111. .fireEvent(new StatusChangeEvent(this, hasValidationErrors));
  2112. }
  2113. private <FIELDVALUE> Converter<FIELDVALUE, FIELDVALUE> createNullRepresentationAdapter(
  2114. HasValue<FIELDVALUE> field) {
  2115. Converter<FIELDVALUE, FIELDVALUE> nullRepresentationConverter = Converter
  2116. .from(fieldValue -> fieldValue,
  2117. modelValue -> Objects.isNull(modelValue)
  2118. ? field.getEmptyValue() : modelValue,
  2119. exception -> exception.getMessage());
  2120. ConverterDelegate<FIELDVALUE> converter = new ConverterDelegate<>(
  2121. nullRepresentationConverter);
  2122. initialConverters.put(field, converter);
  2123. return converter;
  2124. }
  2125. /**
  2126. * Throws if this binder has incomplete bindings.
  2127. *
  2128. * @param methodName
  2129. * name of the method where this call is originated from
  2130. * @throws IllegalStateException
  2131. * if this binder has incomplete bindings
  2132. */
  2133. private void checkBindingsCompleted(String methodName) {
  2134. if (!incompleteMemberFieldBindings.isEmpty()) {
  2135. throw new IllegalStateException(
  2136. "All bindings created with forMemberField must "
  2137. + "be completed with bindInstanceFields before calling "
  2138. + methodName);
  2139. }
  2140. if (!incompleteBindings.isEmpty()) {
  2141. throw new IllegalStateException(
  2142. "All bindings created with forField must be completed before calling "
  2143. + methodName);
  2144. }
  2145. }
  2146. /**
  2147. * Binds member fields found in the given object.
  2148. * <p>
  2149. * This method processes all (Java) member fields whose type extends
  2150. * {@link HasValue} and that can be mapped to a property id. Property name
  2151. * mapping is done based on the field name or on a @{@link PropertyId}
  2152. * annotation on the field. All non-null unbound fields for which a property
  2153. * name can be determined are bound to the property name using
  2154. * {@link BindingBuilder#bind(String)}.
  2155. * <p>
  2156. * For example:
  2157. *
  2158. * <pre>
  2159. * public class MyForm extends VerticalLayout {
  2160. * private TextField firstName = new TextField("First name");
  2161. * &#64;PropertyId("last")
  2162. * private TextField lastName = new TextField("Last name");
  2163. *
  2164. * MyForm myForm = new MyForm();
  2165. * ...
  2166. * binder.bindInstanceFields(myForm);
  2167. * </pre>
  2168. *
  2169. * This binds the firstName TextField to a "firstName" property in the item,
  2170. * lastName TextField to a "last" property.
  2171. * <p>
  2172. * It's not always possible to bind a field to a property because their
  2173. * types are incompatible. E.g. custom converter is required to bind
  2174. * {@code HasValue<String>} and {@code Integer} property (that would be a
  2175. * case of "age" property). In such case {@link IllegalStateException} will
  2176. * be thrown unless the field has been configured manually before calling
  2177. * the {@link #bindInstanceFields(Object)} method.
  2178. * <p>
  2179. * It's always possible to do custom binding for any field: the
  2180. * {@link #bindInstanceFields(Object)} method doesn't override existing
  2181. * bindings.
  2182. *
  2183. * @param objectWithMemberFields
  2184. * The object that contains (Java) member fields to bind
  2185. * @throws IllegalStateException
  2186. * if there are incompatible HasValue&lt;T&gt; and property
  2187. * types
  2188. */
  2189. public void bindInstanceFields(Object objectWithMemberFields) {
  2190. Class<?> objectClass = objectWithMemberFields.getClass();
  2191. Integer numberOfBoundFields = getFieldsInDeclareOrder(objectClass)
  2192. .stream()
  2193. .filter(memberField -> HasValue.class
  2194. .isAssignableFrom(memberField.getType()))
  2195. .filter(memberField -> !isFieldBound(memberField,
  2196. objectWithMemberFields))
  2197. .map(memberField -> handleProperty(memberField,
  2198. objectWithMemberFields,
  2199. (property, type) -> bindProperty(objectWithMemberFields,
  2200. memberField, property, type)))
  2201. .reduce(0, this::accumulate, Integer::sum);
  2202. if (numberOfBoundFields == 0 && bindings.isEmpty()
  2203. && incompleteBindings.isEmpty()) {
  2204. // Throwing here for incomplete bindings would be wrong as they
  2205. // may be completed after this call. If they are not, setBean and
  2206. // other methods will throw for those cases
  2207. throw new IllegalStateException("There are no instance fields "
  2208. + "found for automatic binding");
  2209. }
  2210. }
  2211. private boolean isFieldBound(Field memberField,
  2212. Object objectWithMemberFields) {
  2213. try {
  2214. HasValue field = (HasValue) getMemberFieldValue(memberField,
  2215. objectWithMemberFields);
  2216. return bindings.stream()
  2217. .anyMatch(binding -> binding.getField() == field);
  2218. } catch (Exception e) {
  2219. return false;
  2220. }
  2221. }
  2222. private int accumulate(int count, boolean value) {
  2223. return value ? count + 1 : count;
  2224. }
  2225. private BindingBuilder<BEAN, ?> getIncompleteMemberFieldBinding(
  2226. Field memberField, Object objectWithMemberFields) {
  2227. return incompleteMemberFieldBindings
  2228. .get(getMemberFieldValue(memberField, objectWithMemberFields));
  2229. }
  2230. private Object getMemberFieldValue(Field memberField,
  2231. Object objectWithMemberFields) {
  2232. memberField.setAccessible(true);
  2233. try {
  2234. return memberField.get(objectWithMemberFields);
  2235. } catch (IllegalArgumentException | IllegalAccessException e) {
  2236. throw new RuntimeException(e);
  2237. } finally {
  2238. memberField.setAccessible(false);
  2239. }
  2240. }
  2241. /**
  2242. * Binds {@code property} with {@code propertyType} to the field in the
  2243. * {@code objectWithMemberFields} instance using {@code memberField} as a
  2244. * reference to a member.
  2245. *
  2246. * @param objectWithMemberFields
  2247. * the object that contains (Java) member fields to build and
  2248. * bind
  2249. * @param memberField
  2250. * reference to a member field to bind
  2251. * @param property
  2252. * property name to bind
  2253. * @param propertyType
  2254. * type of the property
  2255. * @return {@code true} if property is successfully bound
  2256. */
  2257. private boolean bindProperty(Object objectWithMemberFields,
  2258. Field memberField, String property, Class<?> propertyType) {
  2259. Type valueType = GenericTypeReflector.getTypeParameter(
  2260. memberField.getGenericType(),
  2261. HasValue.class.getTypeParameters()[0]);
  2262. if (valueType == null) {
  2263. throw new IllegalStateException(String.format(
  2264. "Unable to detect value type for the member '%s' in the "
  2265. + "class '%s'.",
  2266. memberField.getName(),
  2267. objectWithMemberFields.getClass().getName()));
  2268. }
  2269. if (propertyType.equals(GenericTypeReflector.erase(valueType))) {
  2270. HasValue<?> field;
  2271. // Get the field from the object
  2272. try {
  2273. field = (HasValue<?>) ReflectTools.getJavaFieldValue(
  2274. objectWithMemberFields, memberField, HasValue.class);
  2275. } catch (IllegalArgumentException | IllegalAccessException
  2276. | InvocationTargetException e) {
  2277. // If we cannot determine the value, just skip the field
  2278. return false;
  2279. }
  2280. if (field == null) {
  2281. field = makeFieldInstance(
  2282. (Class<? extends HasValue<?>>) memberField.getType());
  2283. initializeField(objectWithMemberFields, memberField, field);
  2284. }
  2285. forField(field).bind(property);
  2286. return true;
  2287. } else {
  2288. throw new IllegalStateException(String.format(
  2289. "Property type '%s' doesn't "
  2290. + "match the field type '%s'. "
  2291. + "Binding should be configured manually using converter.",
  2292. propertyType.getName(), valueType.getTypeName()));
  2293. }
  2294. }
  2295. /**
  2296. * Makes an instance of the field type {@code fieldClass}.
  2297. * <p>
  2298. * The resulting field instance is used to bind a property to it using the
  2299. * {@link #bindInstanceFields(Object)} method.
  2300. * <p>
  2301. * The default implementation relies on the default constructor of the
  2302. * class. If there is no suitable default constructor or you want to
  2303. * configure the instantiated class then override this method and provide
  2304. * your own implementation.
  2305. *
  2306. * @see #bindInstanceFields(Object)
  2307. * @param fieldClass
  2308. * type of the field
  2309. * @return a {@code fieldClass} instance object
  2310. */
  2311. private HasValue<?> makeFieldInstance(
  2312. Class<? extends HasValue<?>> fieldClass) {
  2313. try {
  2314. return ReflectTools.createInstance(fieldClass);
  2315. } catch (IllegalArgumentException e) {
  2316. // Rethrow as the exception type declared for bindInstanceFields
  2317. throw new IllegalStateException(e);
  2318. }
  2319. }
  2320. /**
  2321. * Returns an array containing {@link Field} objects reflecting all the
  2322. * fields of the class or interface represented by this Class object. The
  2323. * elements in the array returned are sorted in declare order from sub class
  2324. * to super class.
  2325. *
  2326. * @param searchClass
  2327. * class to introspect
  2328. * @return list of all fields in the class considering hierarchy
  2329. */
  2330. private List<Field> getFieldsInDeclareOrder(Class<?> searchClass) {
  2331. List<Field> memberFieldInOrder = new ArrayList<>();
  2332. while (searchClass != null) {
  2333. memberFieldInOrder
  2334. .addAll(Arrays.asList(searchClass.getDeclaredFields()));
  2335. searchClass = searchClass.getSuperclass();
  2336. }
  2337. return memberFieldInOrder;
  2338. }
  2339. private void initializeField(Object objectWithMemberFields,
  2340. Field memberField, HasValue<?> value) {
  2341. try {
  2342. ReflectTools.setJavaFieldValue(objectWithMemberFields, memberField,
  2343. value);
  2344. } catch (IllegalArgumentException | IllegalAccessException
  2345. | InvocationTargetException e) {
  2346. throw new IllegalStateException(
  2347. String.format("Could not assign value to field '%s'",
  2348. memberField.getName()),
  2349. e);
  2350. }
  2351. }
  2352. private boolean handleProperty(Field field, Object objectWithMemberFields,
  2353. BiFunction<String, Class<?>, Boolean> propertyHandler) {
  2354. Optional<PropertyDefinition<BEAN, ?>> descriptor = getPropertyDescriptor(
  2355. field);
  2356. if (!descriptor.isPresent()) {
  2357. return false;
  2358. }
  2359. String propertyName = descriptor.get().getName();
  2360. if (boundProperties.containsKey(propertyName)) {
  2361. return false;
  2362. }
  2363. BindingBuilder<BEAN, ?> tentativeBinding = getIncompleteMemberFieldBinding(
  2364. field, objectWithMemberFields);
  2365. if (tentativeBinding != null) {
  2366. tentativeBinding.bind(propertyName);
  2367. return false;
  2368. }
  2369. Boolean isPropertyBound = propertyHandler.apply(propertyName,
  2370. descriptor.get().getType());
  2371. assert boundProperties.containsKey(propertyName);
  2372. return isPropertyBound;
  2373. }
  2374. /**
  2375. * Gets the binding for a property name. Bindings are available by property
  2376. * name if bound using {@link #bind(HasValue, String)},
  2377. * {@link BindingBuilder#bind(String)} or indirectly using
  2378. * {@link #bindInstanceFields(Object)}.
  2379. *
  2380. * @param propertyName
  2381. * the property name of the binding to get
  2382. * @return the binding corresponding to the property name, or an empty
  2383. * optional if there is no binding with that property name
  2384. */
  2385. public Optional<Binding<BEAN, ?>> getBinding(String propertyName) {
  2386. return Optional.ofNullable(boundProperties.get(propertyName));
  2387. }
  2388. private Optional<PropertyDefinition<BEAN, ?>> getPropertyDescriptor(
  2389. Field field) {
  2390. PropertyId propertyIdAnnotation = field.getAnnotation(PropertyId.class);
  2391. String propertyId;
  2392. if (propertyIdAnnotation != null) {
  2393. // @PropertyId(propertyId) always overrides property id
  2394. propertyId = propertyIdAnnotation.value();
  2395. } else {
  2396. propertyId = field.getName();
  2397. }
  2398. String minifiedFieldName = minifyFieldName(propertyId);
  2399. return propertySet.getProperties().map(PropertyDefinition::getName)
  2400. .filter(name -> minifyFieldName(name).equals(minifiedFieldName))
  2401. .findFirst().flatMap(propertySet::getProperty);
  2402. }
  2403. private String minifyFieldName(String fieldName) {
  2404. return fieldName.toLowerCase(Locale.ENGLISH).replace("_", "");
  2405. }
  2406. private <V> void fireValueChangeEvent(ValueChangeEvent<V> event) {
  2407. getEventRouter().fireEvent(event);
  2408. }
  2409. /**
  2410. * Returns the fields this binder has been bound to.
  2411. *
  2412. * @return the fields with bindings
  2413. * @since 8.1
  2414. */
  2415. public Stream<HasValue<?>> getFields() {
  2416. return bindings.stream().map(Binding::getField);
  2417. }
  2418. /**
  2419. * Finds and removes all Bindings for the given field.
  2420. *
  2421. * @param field
  2422. * the field to remove from bindings
  2423. *
  2424. * @since 8.2
  2425. */
  2426. public void removeBinding(HasValue<?> field) {
  2427. Objects.requireNonNull(field, "Field can not be null");
  2428. Set<BindingImpl<BEAN, ?, ?>> toRemove = getBindings().stream()
  2429. .filter(binding -> field.equals(binding.getField()))
  2430. .collect(Collectors.toSet());
  2431. toRemove.forEach(Binding::unbind);
  2432. }
  2433. /**
  2434. * Removes the given Binding from this Binder.
  2435. *
  2436. * @param binding
  2437. * the binding to remove
  2438. *
  2439. * @since 8.2
  2440. */
  2441. public void removeBinding(Binding<BEAN, ?> binding) {
  2442. Objects.requireNonNull(binding, "Binding can not be null");
  2443. binding.unbind();
  2444. }
  2445. /**
  2446. * Removes (internally) the {@code Binding} from the bound properties map
  2447. * (if present) and from the list of {@code Binding}s. Note that this DOES
  2448. * NOT remove the {@code ValueChangeListener} that the {@code Binding} might
  2449. * have registered with any {@code HasValue}s or decouple the {@code Binder}
  2450. * from within the {@code Binding}. To do that, use
  2451. *
  2452. * {@link Binding#unbind()}
  2453. *
  2454. * This method should just be used for internal cleanup.
  2455. *
  2456. * @param binding
  2457. * The {@code Binding} to remove from the binding map
  2458. *
  2459. * @since 8.2
  2460. */
  2461. protected void removeBindingInternal(Binding<BEAN, ?> binding) {
  2462. if (bindings.remove(binding)) {
  2463. boundProperties.entrySet()
  2464. .removeIf(entry -> entry.getValue().equals(binding));
  2465. }
  2466. }
  2467. /**
  2468. * Finds and removes the Binding for the given property name.
  2469. *
  2470. * @param propertyName
  2471. * the propertyName to remove from bindings
  2472. *
  2473. * @since 8.2
  2474. */
  2475. public void removeBinding(String propertyName) {
  2476. Objects.requireNonNull(propertyName, "Property name can not be null");
  2477. Optional.ofNullable(boundProperties.get(propertyName))
  2478. .ifPresent(Binding::unbind);
  2479. }
  2480. }