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

Binder.java 120KB

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