Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Binder.java 109KB

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