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

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