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

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