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

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