You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Binder.java 122KB

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