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

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