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

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