/
Binder.java
3201 lines (2967 loc) · 122 KB
/
Binder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2000-2022 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.data;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.googlecode.gentyref.GenericTypeReflector;
import com.vaadin.annotations.PropertyId;
import com.vaadin.data.HasValue.ValueChangeEvent;
import com.vaadin.data.HasValue.ValueChangeListener;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.data.validator.BeanValidator;
import com.vaadin.event.EventRouter;
import com.vaadin.server.AbstractErrorMessage.ContentMode;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.SerializableFunction;
import com.vaadin.server.SerializablePredicate;
import com.vaadin.server.Setter;
import com.vaadin.server.UserError;
import com.vaadin.shared.Registration;
import com.vaadin.shared.ui.ErrorLevel;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.util.ReflectTools;
/**
* Connects one or more {@code Field} components to properties of a backing data
* type such as a bean type. With a binder, input components can be grouped
* together into forms to easily create and update business objects with little
* explicit logic needed to move data between the UI and the data layers of the
* application.
* <p>
* A binder is a collection of <i>bindings</i>, each representing the mapping of
* a single field, through converters and validators, to a backing property.
* <p>
* A binder instance can be bound to a single bean instance at a time, but can
* be rebound as needed. This allows usage patterns like a <i>master-details</i>
* view, where a select component is used to pick the bean to edit.
* <p>
* Bean level validators can be added using the
* {@link #withValidator(Validator)} method and will be run on the bound bean
* once it has been updated from the values of the bound fields. Bean level
* validators are also run as part of {@link #writeBean(Object)} and
* {@link #writeBeanIfValid(Object)} if all field level validators pass.
* <p>
* Note: For bean level validators, the bean must be updated before the
* validators are run. If a bean level validator fails in
* {@link #writeBean(Object)} or {@link #writeBeanIfValid(Object)}, the bean
* will be reverted to the previous state before returning from the method. You
* should ensure that the getters/setters in the bean do not have side effects.
* <p>
* Unless otherwise specified, {@code Binder} method arguments cannot be null.
*
* @author Vaadin Ltd.
*
* @param <BEAN>
* the bean type
*
* @see BindingBuilder
* @see Binding
* @see HasValue
*
* @since 8.0
*/
public class Binder<BEAN> implements Serializable {
/**
* Represents the binding between a field and a data property.
*
* @param <BEAN>
* the bean type
* @param <TARGET>
* the target data type of the binding, matches the field type
* unless a converter has been set
*
* @see Binder#forField(HasValue)
*/
public interface Binding<BEAN, TARGET> extends Serializable {
/**
* Gets the field the binding uses.
*
* @return the field for the binding
*/
public HasValue<?> getField();
/**
* Validates the field value and returns a {@code ValidationStatus}
* instance representing the outcome of the validation. This method is a
* short-hand for calling {@link #validate(boolean)} with
* {@code fireEvent} {@code true}.
*
* @see #validate(boolean)
* @see Binder#validate()
* @see Validator#apply(Object, ValueContext)
*
* @return the validation result.
*/
public default BindingValidationStatus<TARGET> validate() {
return validate(true);
}
/**
* Validates the field value and returns a {@code ValidationStatus}
* instance representing the outcome of the validation.
*
* <strong>Note:</strong> Calling this method will not trigger the value
* update in the bean automatically. This method will attempt to
* temporarily apply all current changes to the bean and run full bean
* validation for it. The changes are reverted after bean validation.
*
* @see #validate()
* @see Binder#validate()
*
* @param fireEvent
* {@code true} to fire status event; {@code false} to not
* @return the validation result.
*
* @since 8.2
*/
public BindingValidationStatus<TARGET> validate(boolean fireEvent);
/**
* Gets the validation status handler for this Binding.
*
* @return the validation status handler for this binding
*
* @since 8.2
*/
public BindingValidationStatusHandler getValidationStatusHandler();
/**
* Unbinds the binding from its respective {@code Binder} Removes any
* {@code ValueChangeListener} {@code Registration} from associated
* {@code HasValue}.
*
* @since 8.2
*/
public void unbind();
/**
* Reads the value from given item and stores it to the bound field.
*
* @param bean
* the bean to read from
*
* @since 8.2
*/
public void read(BEAN bean);
/**
* Sets the read-only status on for this Binding. Setting a Binding
* read-only will mark the field read-only and not write any values from
* the fields to the bean.
* <p>
* This helper method is the preferred way to control the read-only
* state of the bound field.
*
* @param readOnly
* {@code true} to set binding read-only; {@code false} to
* enable writes
* @since 8.4
* @throws IllegalStateException
* if trying to make binding read-write and the setter is
* {@code null}
*/
public void setReadOnly(boolean readOnly);
/**
* Gets the current read-only status for this Binding.
*
* @see #setReadOnly(boolean)
*
* @return {@code true} if read-only; {@code false} if not
* @since 8.4
*/
public boolean isReadOnly();
/**
* Gets the getter associated with this Binding.
*
* @return the getter
* @since 8.4
*/
public ValueProvider<BEAN, TARGET> getGetter();
/**
* Gets the setter associated with this Binding.
*
* @return the setter
* @since 8.4
*/
public Setter<BEAN, TARGET> getSetter();
/**
* Enable or disable asRequired validator. The validator is enabled by
* default.
*
* @see #asRequired(String)
* @see #asRequired(ErrorMessageProvider)
*
* @param asRequiredEnabled
* {@code false} if asRequired validator should be disabled,
* {@code true} otherwise (default)
*
* @since 8.10
*/
public void setAsRequiredEnabled(boolean asRequiredEnabled);
/**
* Returns whether asRequired validator is currently enabled or not.
*
* @see #asRequired(String)
* @see #asRequired(ErrorMessageProvider)
*
* @return {@code false} if asRequired validator is disabled
* {@code true} otherwise (default)
*
* @since 8.10
*/
public boolean isAsRequiredEnabled();
/**
* Define whether validators are disabled or enabled for this
* specific binding.
*
* @param validatorsDisabled A boolean value
*
* @since 8.11
*/
public void setValidatorsDisabled(boolean validatorsDisabled);
/**
* Returns if validators are currently disabled or not
*
* @return A boolean value
*
* @since 8.11
*/
public boolean isValidatorsDisabled();
/**
* Define whether the value should be converted back to the presentation
* in the field when a converter is used in binding.
*
* @param convertBackToPresentation
* A boolean value
*
* @since 8.13
*/
public void setConvertBackToPresentation(
boolean convertBackToPresentation);
/**
* Returns whether the value is converted back to the presentation in
* the field when a converter is used in binding.
*
* @return A boolean value
*
* @since 8.13
*/
public boolean isConvertBackToPresentation();
}
/**
* Creates a binding between a field and a data property.
*
* @param <BEAN>
* the bean type
* @param <TARGET>
* the target data type of the binding, matches the field type
* until a converter has been set
*
* @see Binder#forField(HasValue)
*/
public interface BindingBuilder<BEAN, TARGET> extends Serializable {
/**
* Gets the field the binding is being built for.
*
* @return the field this binding is being built for
*/
public HasValue<?> getField();
/**
* Completes this binding using the given getter and setter functions
* representing a backing bean property. The functions are used to
* update the field value from the property and to store the field value
* to the property, respectively.
* <p>
* When a bean is bound with {@link Binder#setBean(BEAN)}, the field
* value is set to the return value of the given getter. The property
* value is then updated via the given setter whenever the field value
* changes. The setter may be null; in that case the property value is
* never updated and the binding is said to be <i>read-only</i>.
* <p>
* If the Binder is already bound to some bean, the newly bound field is
* associated with the corresponding bean property as described above.
* <p>
* The getter and setter can be arbitrary functions, for instance
* implementing user-defined conversion or validation. However, in the
* most basic use case you can simply pass a pair of method references
* to this method as follows:
*
* <pre>
* class Person {
* public String getName() { ... }
* public void setName(String name) { ... }
* }
*
* TextField nameField = new TextField();
* binder.forField(nameField).bind(Person::getName, Person::setName);
* </pre>
*
* <p>
* <strong>Note:</strong> when a {@code null} setter is given the field
* will be marked as read-only by invoking
* {@link HasValue#setReadOnly(boolean)}.
*
* @param getter
* the function to get the value of the property to the
* field, not null
* @param setter
* the function to write the field value to the property or
* null if read-only
* @return the newly created binding
* @throws IllegalStateException
* if {@code bind} has already been called on this binding
*/
public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
Setter<BEAN, TARGET> setter);
/**
* Completes this binding by connecting the field to the property with
* the given name. The getter and setter of the property are looked up
* using a {@link PropertySet}.
* <p>
* For a <code>Binder</code> created using the
* {@link Binder#Binder(Class)} constructor, introspection will be used
* to find a Java Bean property. If a JSR-303 bean validation
* implementation is present on the classpath, a {@link BeanValidator}
* is also added to the binding.
* <p>
* The property must have an accessible getter method. It need not have
* an accessible setter; in that case the property value is never
* updated and the binding is said to be <i>read-only</i>.
*
* <p>
* <strong>Note:</strong> when the binding is <i>read-only</i> the field
* will be marked as read-only by invoking
* {@link HasValue#setReadOnly(boolean)}.
*
* @param propertyName
* the name of the property to bind, not null
* @return the newly created binding
*
* @throws IllegalArgumentException
* if the property name is invalid
* @throws IllegalArgumentException
* if the property has no accessible getter
* @throws IllegalStateException
* if the binder is not configured with an appropriate
* {@link PropertySet}
*
* @see Binder.BindingBuilder#bind(ValueProvider, Setter)
*/
public Binding<BEAN, TARGET> bind(String propertyName);
/**
* Adds a validator to this binding. Validators are applied, in
* registration order, when the field value is written to the backing
* property. If any validator returns a failure, the property value is
* not updated.
*
* @see #withValidator(SerializablePredicate, String)
* @see #withValidator(SerializablePredicate, ErrorMessageProvider)
*
* @param validator
* the validator to add, not null
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public BindingBuilder<BEAN, TARGET> withValidator(
Validator<? super TARGET> validator);
/**
* A convenience method to add a validator to this binding using the
* {@link Validator#from(SerializablePredicate, String)} factory method.
* <p>
* Validators are applied, in registration order, when the field value
* is written to the backing property. If any validator returns a
* failure, the property value is not updated.
*
* @see #withValidator(Validator)
* @see #withValidator(SerializablePredicate, String, ErrorLevel)
* @see #withValidator(SerializablePredicate, ErrorMessageProvider)
* @see Validator#from(SerializablePredicate, String)
*
* @param predicate
* the predicate performing validation, not null
* @param message
* the error message to report in case validation failure
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public default BindingBuilder<BEAN, TARGET> withValidator(
SerializablePredicate<? super TARGET> predicate,
String message) {
return withValidator(Validator.from(predicate, message));
}
/**
* A convenience method to add a validator to this binding using the
* {@link Validator#from(SerializablePredicate, String, ErrorLevel)}
* factory method.
* <p>
* Validators are applied, in registration order, when the field value
* is written to the backing property. If any validator returns a
* failure, the property value is not updated.
*
* @see #withValidator(Validator)
* @see #withValidator(SerializablePredicate, String)
* @see #withValidator(SerializablePredicate, ErrorMessageProvider,
* ErrorLevel)
* @see Validator#from(SerializablePredicate, String)
*
* @param predicate
* the predicate performing validation, not null
* @param message
* the error message to report in case validation failure
* @param errorLevel
* the error level for failures from this validator, not null
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*
* @since 8.2
*/
public default BindingBuilder<BEAN, TARGET> withValidator(
SerializablePredicate<? super TARGET> predicate, String message,
ErrorLevel errorLevel) {
return withValidator(
Validator.from(predicate, message, errorLevel));
}
/**
* A convenience method to add a validator to this binding using the
* {@link Validator#from(SerializablePredicate, ErrorMessageProvider)}
* factory method.
* <p>
* Validators are applied, in registration order, when the field value
* is written to the backing property. If any validator returns a
* failure, the property value is not updated.
*
* @see #withValidator(Validator)
* @see #withValidator(SerializablePredicate, String)
* @see #withValidator(SerializablePredicate, ErrorMessageProvider,
* ErrorLevel)
* @see Validator#from(SerializablePredicate, ErrorMessageProvider)
*
* @param predicate
* the predicate performing validation, not null
* @param errorMessageProvider
* the provider to generate error messages, not null
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public default BindingBuilder<BEAN, TARGET> withValidator(
SerializablePredicate<? super TARGET> predicate,
ErrorMessageProvider errorMessageProvider) {
return withValidator(
Validator.from(predicate, errorMessageProvider));
}
/**
* A convenience method to add a validator to this binding using the
* {@link Validator#from(SerializablePredicate, ErrorMessageProvider, ErrorLevel)}
* factory method.
* <p>
* Validators are applied, in registration order, when the field value
* is written to the backing property. If any validator returns a
* failure, the property value is not updated.
*
* @see #withValidator(Validator)
* @see #withValidator(SerializablePredicate, String, ErrorLevel)
* @see #withValidator(SerializablePredicate, ErrorMessageProvider)
* @see Validator#from(SerializablePredicate, ErrorMessageProvider,
* ErrorLevel)
*
* @param predicate
* the predicate performing validation, not null
* @param errorMessageProvider
* the provider to generate error messages, not null
* @param errorLevel
* the error level for failures from this validator, not null
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*
* @since 8.2
*/
public default BindingBuilder<BEAN, TARGET> withValidator(
SerializablePredicate<? super TARGET> predicate,
ErrorMessageProvider errorMessageProvider,
ErrorLevel errorLevel) {
return withValidator(Validator.from(predicate, errorMessageProvider,
errorLevel));
}
/**
* Maps the binding to another data type using the given
* {@link Converter}.
* <p>
* A converter is capable of converting between a presentation type,
* which must match the current target data type of the binding, and a
* model type, which can be any data type and becomes the new target
* type of the binding. When invoking
* {@link #bind(ValueProvider, Setter)}, the target type of the binding
* must match the getter/setter types.
* <p>
* For instance, a {@code TextField} can be bound to an integer-typed
* property using an appropriate converter such as a
* {@link StringToIntegerConverter}.
*
* @param <NEWTARGET>
* the type to convert to
* @param converter
* the converter to use, not null
* @return a new binding with the appropriate type
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
Converter<TARGET, NEWTARGET> converter);
/**
* Maps the binding to another data type using the mapping functions and
* a possible exception as the error message.
* <p>
* The mapping functions are used to convert between a presentation
* type, which must match the current target data type of the binding,
* and a model type, which can be any data type and becomes the new
* target type of the binding. When invoking
* {@link #bind(ValueProvider, Setter)}, the target type of the binding
* must match the getter/setter types.
* <p>
* For instance, a {@code TextField} can be bound to an integer-typed
* property using appropriate functions such as:
* <code>withConverter(Integer::valueOf, String::valueOf);</code>
*
* @param <NEWTARGET>
* the type to convert to
* @param toModel
* the function which can convert from the old target type to
* the new target type
* @param toPresentation
* the function which can convert from the new target type to
* the old target type
* @return a new binding with the appropriate type
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public default <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
SerializableFunction<TARGET, NEWTARGET> toModel,
SerializableFunction<NEWTARGET, TARGET> toPresentation) {
return withConverter(Converter.from(toModel, toPresentation,
exception -> exception.getMessage()));
}
/**
* Maps the binding to another data type using the mapping functions and
* the given error error message if a value cannot be converted to the
* new target type.
* <p>
* The mapping functions are used to convert between a presentation
* type, which must match the current target data type of the binding,
* and a model type, which can be any data type and becomes the new
* target type of the binding. When invoking
* {@link #bind(ValueProvider, Setter)}, the target type of the binding
* must match the getter/setter types.
* <p>
* For instance, a {@code TextField} can be bound to an integer-typed
* property using appropriate functions such as:
* <code>withConverter(Integer::valueOf, String::valueOf);</code>
*
* @param <NEWTARGET>
* the type to convert to
* @param toModel
* the function which can convert from the old target type to
* the new target type
* @param toPresentation
* the function which can convert from the new target type to
* the old target type
* @param errorMessage
* the error message to use if conversion using
* <code>toModel</code> fails
* @return a new binding with the appropriate type
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public default <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
SerializableFunction<TARGET, NEWTARGET> toModel,
SerializableFunction<NEWTARGET, TARGET> toPresentation,
String errorMessage) {
return withConverter(Converter.from(toModel, toPresentation,
exception -> errorMessage));
}
/**
* Maps binding value {@code null} to given null representation and back
* to {@code null} when converting back to model value.
*
* @param nullRepresentation
* the value to use instead of {@code null}
* @return a new binding with null representation handling.
*/
public default BindingBuilder<BEAN, TARGET> withNullRepresentation(
TARGET nullRepresentation) {
return withConverter(
fieldValue -> Objects.equals(fieldValue, nullRepresentation)
? null
: fieldValue,
modelValue -> Objects.isNull(modelValue)
? nullRepresentation
: modelValue);
}
/**
* Sets the given {@code label} to show an error message if validation
* fails.
* <p>
* The validation state of each field is updated whenever the user
* modifies the value of that field. The validation state is by default
* shown using {@link AbstractComponent#setComponentError} which is used
* by the layout that the field is shown in. Most built-in layouts will
* show this as a red exclamation mark icon next to the component, so
* that hovering or tapping the icon shows a tooltip with the message
* text.
* <p>
* This method allows to customize the way a binder displays error
* messages to get more flexibility than what
* {@link AbstractComponent#setComponentError} provides (it replaces the
* default behavior).
* <p>
* This is just a shorthand for
* {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
* method where the handler instance hides the {@code label} if there is
* no error and shows it with validation error message if validation
* fails. It means that it cannot be called after
* {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
* method call or
* {@link #withValidationStatusHandler(BindingValidationStatusHandler)}
* after this method call.
*
* @see #withValidationStatusHandler(BindingValidationStatusHandler)
* @see AbstractComponent#setComponentError(ErrorMessage)
* @param label
* label to show validation status for the field
* @return this binding, for chaining
*/
public default BindingBuilder<BEAN, TARGET> withStatusLabel(
Label label) {
return withValidationStatusHandler(status -> {
label.setValue(status.getMessage().orElse(""));
// Only show the label when validation has failed
label.setVisible(status.isError());
});
}
/**
* Sets a {@link BindingValidationStatusHandler} to track validation
* status changes.
* <p>
* The validation state of each field is updated whenever the user
* modifies the value of that field. The validation state is by default
* shown using {@link AbstractComponent#setComponentError} which is used
* by the layout that the field is shown in. Most built-in layouts will
* show this as a red exclamation mark icon next to the component, so
* that hovering or tapping the icon shows a tooltip with the message
* text.
* <p>
* This method allows to customize the way a binder displays error
* messages to get more flexibility than what
* {@link AbstractComponent#setComponentError} provides (it replaces the
* default behavior).
* <p>
* The method may be called only once. It means there is no chain unlike
* {@link #withValidator(Validator)} or
* {@link #withConverter(Converter)}. Also it means that the shorthand
* method {@link #withStatusLabel(Label)} also may not be called after
* this method.
*
* @see #withStatusLabel(Label)
* @see AbstractComponent#setComponentError(ErrorMessage)
* @param handler
* status change handler
* @return this binding, for chaining
*/
public BindingBuilder<BEAN, TARGET> withValidationStatusHandler(
BindingValidationStatusHandler handler);
/**
* Sets the field to be required. This means two things:
* <ol>
* <li>the required indicator will be displayed for this field</li>
* <li>the field value is validated for not being empty, i.e. that the
* field's value is not equal to what {@link HasValue#getEmptyValue()}
* returns</li>
* </ol>
* <p>
* For localizing the error message, use
* {@link #asRequired(ErrorMessageProvider)}.
*
* @see #asRequired(ErrorMessageProvider)
* @see HasValue#setRequiredIndicatorVisible(boolean)
* @see HasValue#isEmpty()
* @param errorMessage
* the error message to show for the invalid value
* @return this binding, for chaining
*/
public default BindingBuilder<BEAN, TARGET> asRequired(
String errorMessage) {
return asRequired(context -> errorMessage);
}
/**
* Sets the field to be required. This means two things:
* <ol>
* <li>the required indicator will be displayed for this field</li>
* <li>the field value is validated for not being empty, i.e. that the
* field's value is not equal to what {@link HasValue#getEmptyValue()}
* returns</li>
* </ol>
* <p>
* For setting an error message, use {@link #asRequired(String)}.
* <p>
* For localizing the error message, use
* {@link #asRequired(ErrorMessageProvider)}.
*
* @see #asRequired(String)
* @see #asRequired(ErrorMessageProvider)
* @see HasValue#setRequiredIndicatorVisible(boolean)
* @see HasValue#isEmpty()
* @return this binding, for chaining
* @since 8.2
*/
public default BindingBuilder<BEAN, TARGET> asRequired() {
return asRequired(context -> "");
}
/**
* Sets the field to be required. This means two things:
* <ol>
* <li>the required indicator will be displayed for this field</li>
* <li>the field value is validated for not being empty, i.e. that the
* field's value is not equal to what {@link HasValue#getEmptyValue()}
* returns</li>
* </ol>
*
* @see HasValue#setRequiredIndicatorVisible(boolean)
* @see HasValue#isEmpty()
* @param errorMessageProvider
* the provider for localized validation error message
* @return this binding, for chaining
*/
public BindingBuilder<BEAN, TARGET> asRequired(
ErrorMessageProvider errorMessageProvider);
/**
* Sets the field to be required and delegates the required check to a
* custom validator. This means two things:
* <ol>
* <li>the required indicator will be displayed for this field</li>
* <li>the field value is validated by {@code requiredValidator}</li>
* </ol>
*
* @see HasValue#setRequiredIndicatorVisible(boolean)
* @param requiredValidator
* validator responsible for the required check
* @return this binding, for chaining
* @since 8.4
*/
public BindingBuilder<BEAN, TARGET> asRequired(
Validator<TARGET> requiredValidator);
}
/**
* An internal implementation of {@code BindingBuilder}.
*
* @param <BEAN>
* the bean type, must match the Binder bean type
* @param <FIELDVALUE>
* the value type of the field
* @param <TARGET>
* the target data type of the binding, matches the field type
* until a converter has been set
*/
protected static class BindingBuilderImpl<BEAN, FIELDVALUE, TARGET>
implements BindingBuilder<BEAN, TARGET> {
private Binder<BEAN> binder;
private final HasValue<FIELDVALUE> field;
private BindingValidationStatusHandler statusHandler;
private boolean isStatusHandlerChanged;
private Binding<BEAN, TARGET> binding;
private boolean bound;
/**
* Contains all converters and validators chained together in the
* correct order.
*/
private Converter<FIELDVALUE, ?> converterValidatorChain;
private boolean asRequiredSet;
/**
* Creates a new binding builder associated with the given field.
* Initializes the builder with the given converter chain and status
* change handler.
*
* @param binder
* the binder this instance is connected to, not null
* @param field
* the field to bind, not null
* @param converterValidatorChain
* the converter/validator chain to use, not null
* @param statusHandler
* the handler to track validation status, not null
*/
protected BindingBuilderImpl(Binder<BEAN> binder,
HasValue<FIELDVALUE> field,
Converter<FIELDVALUE, TARGET> converterValidatorChain,
BindingValidationStatusHandler statusHandler) {
this.field = field;
this.binder = binder;
this.converterValidatorChain = converterValidatorChain;
this.statusHandler = statusHandler;
}
@Override
public Binding<BEAN, TARGET> bind(ValueProvider<BEAN, TARGET> getter,
Setter<BEAN, TARGET> setter) {
checkUnbound();
Objects.requireNonNull(getter, "getter cannot be null");
BindingImpl<BEAN, FIELDVALUE, TARGET> binding = new BindingImpl<>(
this, getter, setter);
getBinder().bindings.add(binding);
if (getBinder().getBean() != null) {
binding.initFieldValue(getBinder().getBean(), true);
}
if (setter == null) {
binding.getField().setReadOnly(true);
}
getBinder().fireStatusChangeEvent(false);
bound = true;
getBinder().incompleteBindings.remove(getField());
this.binding = binding;
return binding;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Binding<BEAN, TARGET> bind(String propertyName) {
Objects.requireNonNull(propertyName,
"Property name cannot be null");
checkUnbound();
PropertyDefinition<BEAN, ?> definition = getBinder().propertySet
.getProperty(propertyName)
.orElseThrow(() -> new IllegalArgumentException(
"Could not resolve property name " + propertyName
+ " from " + getBinder().propertySet));
ValueProvider<BEAN, ?> getter = definition.getGetter();
Setter<BEAN, ?> setter = definition.getSetter().orElse(null);
if (setter == null) {
getLogger().fine(() -> propertyName
+ " does not have an accessible setter");
}
BindingBuilder<BEAN, ?> finalBinding = withConverter(
createConverter(definition.getType()), false);
finalBinding = getBinder().configureBinding(finalBinding,
definition);
try {
Binding binding = ((BindingBuilder) finalBinding).bind(getter,
setter);
getBinder().boundProperties.put(propertyName, binding);
this.binding = binding;
return binding;
} finally {
getBinder().incompleteMemberFieldBindings.remove(getField());
}
}
@SuppressWarnings("unchecked")
private Converter<TARGET, Object> createConverter(Class<?> getterType) {
return Converter.from(fieldValue -> getterType.cast(fieldValue),
propertyValue -> (TARGET) propertyValue, exception -> {
throw new RuntimeException(exception);
});
}
@Override
public BindingBuilder<BEAN, TARGET> withValidator(
Validator<? super TARGET> validator) {
checkUnbound();
Objects.requireNonNull(validator, "validator cannot be null");
Validator<? super TARGET> wrappedValidator = ((value, context) -> {
if (getBinder().isValidatorsDisabled() ||
(binding != null && binding.isValidatorsDisabled())) {
return ValidationResult.ok();
} else {
return validator.apply(value, context);
}
});
converterValidatorChain = ((Converter<FIELDVALUE, TARGET>) converterValidatorChain)
.chain(new ValidatorAsConverter<>(wrappedValidator));
return this;
}
@Override
public <NEWTARGET> BindingBuilder<BEAN, NEWTARGET> withConverter(
Converter<TARGET, NEWTARGET> converter) {
return withConverter(converter, true);
}
@Override
public BindingBuilder<BEAN, TARGET> withValidationStatusHandler(
BindingValidationStatusHandler handler) {
checkUnbound();
Objects.requireNonNull(handler, "handler cannot be null");
if (isStatusHandlerChanged) {
throw new IllegalStateException("A "
+ BindingValidationStatusHandler.class.getSimpleName()
+ " has already been set");
}
isStatusHandlerChanged = true;
statusHandler = handler;
return this;
}
@Override
public BindingBuilder<BEAN, TARGET> asRequired(
ErrorMessageProvider errorMessageProvider) {
return asRequired(Validator.from(
value -> !Objects.equals(value, field.getEmptyValue()),
errorMessageProvider));
}
@Override
public BindingBuilder<BEAN, TARGET> asRequired(