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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
|
/*
* Copyright 2000-2016 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.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
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.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.vaadin.data.util.converter.Converter;
import com.vaadin.data.util.converter.StringToIntegerConverter;
import com.vaadin.data.util.converter.ValueContext;
import com.vaadin.event.EventRouter;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.UserError;
import com.vaadin.shared.Registration;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.AbstractMultiSelect;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
/**
* 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 #save(Object)} and
* {@link #saveIfValid(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 #save(Object)}
* or {@link #saveIfValid(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 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 <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
*
* @see Binder#forField(HasValue)
*/
public interface Binding<BEAN, FIELDVALUE, TARGET> extends Serializable {
/**
* 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#bind(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>
*
* @param getter
* the function to get the value of the property to the
* field, not null
* @param setter
* the function to save the field value to the property or
* null if read-only
* @throws IllegalStateException
* if {@code bind} has already been called on this binding
*/
public void bind(Function<BEAN, TARGET> getter,
BiConsumer<BEAN, TARGET> setter);
/**
* Adds a validator to this binding. Validators are applied, in
* registration order, when the field value is saved to the backing
* property. If any validator returns a failure, the property value is
* not updated.
*
* @param validator
* the validator to add, not null
* @return this binding, for chaining
* @throws IllegalStateException
* if {@code bind} has already been called
*/
public Binding<BEAN, FIELDVALUE, TARGET> withValidator(
Validator<? super TARGET> validator);
/**
* A convenience method to add a validator to this binding using the
* {@link Validator#from(Predicate, String)} factory method.
* <p>
* Validators are applied, in registration order, when the field value
* is saved to the backing property. If any validator returns a failure,
* the property value is not updated.
*
* @see #withValidator(Validator)
* @see Validator#from(Predicate, 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 Binding<BEAN, FIELDVALUE, TARGET> withValidator(
Predicate<? super TARGET> predicate, String message) {
return withValidator(Validator.from(predicate, message));
}
/**
* 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(Function, BiConsumer)}, 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> Binding<BEAN, FIELDVALUE, 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(Function, BiConsumer)}, 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> Binding<BEAN, FIELDVALUE, NEWTARGET> withConverter(
Function<TARGET, NEWTARGET> toModel,
Function<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(Function, BiConsumer)}, 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> Binding<BEAN, FIELDVALUE, NEWTARGET> withConverter(
Function<TARGET, NEWTARGET> toModel,
Function<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 Binding<BEAN, FIELDVALUE, TARGET> withNullRepresentation(
TARGET nullRepresentation) {
return withConverter(
fieldValue -> Objects.equals(fieldValue, nullRepresentation)
? null : fieldValue,
modelValue -> Objects.isNull(modelValue)
? nullRepresentation : modelValue);
}
/**
* Gets the field the binding uses.
*
* @return the field for the binding
*/
public HasValue<FIELDVALUE> getField();
/**
* 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(ValidationStatusHandler)} 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(ValidationStatusHandler)} method
* call or {@link #withValidationStatusHandler(ValidationStatusHandler)}
* after this method call.
*
* @see #withValidationStatusHandler(ValidationStatusHandler)
* @see AbstractComponent#setComponentError(ErrorMessage)
* @param label
* label to show validation status for the field
* @return this binding, for chaining
*/
public default Binding<BEAN, FIELDVALUE, 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 ValidationStatusHandler} 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 Binding<BEAN, FIELDVALUE, TARGET> withValidationStatusHandler(
ValidationStatusHandler handler);
/**
* Validates the field value and returns a {@code ValidationStatus}
* instance representing the outcome of the validation.
*
* @see Binder#validate()
* @see Validator#apply(Object)
*
* @return the validation result.
*/
public ValidationStatus<TARGET> validate();
}
/**
* An internal implementation of {@code Binding}.
*
* @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 BindingImpl<BEAN, FIELDVALUE, TARGET>
implements Binding<BEAN, FIELDVALUE, TARGET> {
private final Binder<BEAN> binder;
private final HasValue<FIELDVALUE> field;
private Registration onValueChange;
private ValidationStatusHandler statusHandler;
private boolean isStatusHandlerChanged;
private Function<BEAN, TARGET> getter;
private BiConsumer<BEAN, TARGET> setter;
/**
* Contains all converters and validators chained together in the
* correct order.
*/
private Converter<FIELDVALUE, TARGET> converterValidatorChain;
/**
* Creates a new binding associated with the given field. Initializes
* the binding 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 BindingImpl(Binder<BEAN> binder, HasValue<FIELDVALUE> field,
Converter<FIELDVALUE, TARGET> converterValidatorChain,
ValidationStatusHandler statusHandler) {
this.field = field;
this.binder = binder;
this.converterValidatorChain = converterValidatorChain;
this.statusHandler = statusHandler;
}
@Override
public void bind(Function<BEAN, TARGET> getter,
BiConsumer<BEAN, TARGET> setter) {
checkUnbound();
Objects.requireNonNull(getter, "getter cannot be null");
this.getter = getter;
this.setter = setter;
getBinder().bindings.add(this);
getBinder().getBean().ifPresent(this::bind);
getBinder().fireStatusChangeEvent(false);
}
@Override
public Binding<BEAN, FIELDVALUE, TARGET> withValidator(
Validator<? super TARGET> validator) {
checkUnbound();
Objects.requireNonNull(validator, "validator cannot be null");
converterValidatorChain = converterValidatorChain
.chain(new ValidatorAsConverter<>(validator));
return this;
}
@Override
public <NEWTARGET> Binding<BEAN, FIELDVALUE, NEWTARGET> withConverter(
Converter<TARGET, NEWTARGET> converter) {
checkUnbound();
Objects.requireNonNull(converter, "converter cannot be null");
return getBinder().createBinding(getField(),
converterValidatorChain.chain(converter), statusHandler);
}
@Override
public Binding<BEAN, FIELDVALUE, TARGET> withValidationStatusHandler(
ValidationStatusHandler handler) {
checkUnbound();
Objects.requireNonNull(handler, "handler cannot be null");
if (isStatusHandlerChanged) {
throw new IllegalStateException(
"A " + ValidationStatusHandler.class.getSimpleName()
+ " has already been set");
}
isStatusHandlerChanged = true;
statusHandler = handler;
return this;
}
@Override
public HasValue<FIELDVALUE> getField() {
return field;
}
/**
* Returns the {@code Binder} connected to this {@code Binding}
* instance.
*
* @return the binder
*/
protected Binder<BEAN> getBinder() {
return binder;
}
/**
* Throws if this binding is already completed and cannot be modified
* anymore.
*
* @throws IllegalStateException
* if this binding is already bound
*/
protected void checkUnbound() {
if (getter != null) {
throw new IllegalStateException(
"cannot modify binding: already bound to a property");
}
}
/**
* Finds an appropriate locale to be used in conversion and validation.
*
* @return the found locale, not null
*/
protected Locale findLocale() {
Locale l = null;
if (getField() instanceof Component) {
l = ((Component) getField()).getLocale();
}
if (l == null && UI.getCurrent() != null) {
l = UI.getCurrent().getLocale();
}
if (l == null) {
l = Locale.getDefault();
}
return l;
}
private void bind(BEAN bean) {
setFieldValue(bean);
onValueChange = getField()
.addValueChangeListener(e -> handleFieldValueChange(bean));
}
@Override
public ValidationStatus<TARGET> validate() {
ValidationStatus<TARGET> status = doValidation();
getBinder().getValidationStatusHandler()
.accept(new BinderValidationStatus<>(getBinder(),
Arrays.asList(status), Collections.emptyList()));
getBinder().fireStatusChangeEvent(status.isError());
return status;
}
/**
* Returns the field value run through all converters and validators,
* but doesn't pass the {@link ValidationStatus} to any status handler.
*
* @return the validation status
*/
private ValidationStatus<TARGET> doValidation() {
FIELDVALUE fieldValue = field.getValue();
Result<TARGET> dataValue = converterValidatorChain
.convertToModel(fieldValue, createValueContext());
return new ValidationStatus<>(this, dataValue);
}
/**
* Creates a value context from the current state of the binding and its
* field.
*
* @return the value context
*/
protected ValueContext createValueContext() {
if (field instanceof Component) {
return new ValueContext((Component) field);
}
return new ValueContext(findLocale());
}
private void unbind() {
onValueChange.remove();
}
/**
* Sets the field value by invoking the getter function on the given
* bean.
*
* @param bean
* the bean to fetch the property value from
*/
private void setFieldValue(BEAN bean) {
assert bean != null;
getField().setValue(convertDataToFieldType(bean));
}
private FIELDVALUE convertDataToFieldType(BEAN bean) {
return converterValidatorChain.convertToPresentation(
getter.apply(bean), createValueContext());
}
/**
* Handles the value change triggered by the bound field.
*
* @param bean
* the new value
*/
private void handleFieldValueChange(BEAN bean) {
getBinder().setHasChanges(true);
// store field value if valid
ValidationStatus<TARGET> fieldValidationStatus = storeFieldValue(
bean);
List<Result<?>> binderValidationResults;
// if all field level validations pass, run bean level validation
if (!getBinder().bindings.stream().map(BindingImpl::doValidation)
.anyMatch(ValidationStatus::isError)) {
binderValidationResults = getBinder().validateBean(bean);
} else {
binderValidationResults = Collections.emptyList();
}
BinderValidationStatus<BEAN> status = new BinderValidationStatus<>(
binder, Arrays.asList(fieldValidationStatus),
binderValidationResults);
getBinder().getValidationStatusHandler().accept(status);
getBinder().fireStatusChangeEvent(status.hasErrors());
}
/**
* Saves the field value by invoking the setter function on the given
* bean, if the value passes all registered validators.
*
* @param bean
* the bean to set the property value to
*/
private ValidationStatus<TARGET> storeFieldValue(BEAN bean) {
assert bean != null;
ValidationStatus<TARGET> validationStatus = doValidation();
if (setter != null) {
validationStatus.getResult().ifPresent(result -> result
.ifOk(value -> setter.accept(bean, value)));
}
return validationStatus;
}
private void notifyStatusHandler(ValidationStatus<?> status) {
statusHandler.accept(status);
}
}
/**
* Wraps a validator as a converter.
* <p>
* The type of the validator must be of the same type as this converter or a
* super type of it.
*
* @param <T>
* the type of the converter
*/
private static class ValidatorAsConverter<T> implements Converter<T, T> {
private Validator<? super T> validator;
/**
* Creates a new converter wrapping the given validator.
*
* @param validator
* the validator to wrap
*/
public ValidatorAsConverter(Validator<? super T> validator) {
this.validator = validator;
}
@Override
public Result<T> convertToModel(T value, ValueContext context) {
Result<? super T> validationResult = validator.apply(value);
if (validationResult.isError()) {
return Result.error(validationResult.getMessage().get());
} else {
return Result.ok(value);
}
}
@Override
public T convertToPresentation(T value, ValueContext context) {
return value;
}
}
private BEAN bean;
private final Set<BindingImpl<BEAN, ?, ?>> bindings = new LinkedHashSet<>();
private final List<Validator<? super BEAN>> validators = new ArrayList<>();
private EventRouter eventRouter;
private Label statusLabel;
private BinderValidationStatusHandler statusHandler;
private boolean hasChanges = false;
/**
* Returns an {@code Optional} of the bean that has been bound with
* {@link #bind}, or an empty optional if a bean is not currently bound.
*
* @return the currently bound bean if any
*/
public Optional<BEAN> getBean() {
return Optional.ofNullable(bean);
}
/**
* Creates a new binding for the given field. The returned binding may be
* further configured before invoking
* {@link Binding#bind(Function, BiConsumer) Binding.bind} which completes
* the binding. Until {@code Binding.bind} is called, the binding has no
* effect.
* <p>
* <strong>Note:</strong> Not all {@link HasValue} implementations support
* passing {@code null} as the value. For these the Binder will
* automatically change {@code null} to a null representation provided by
* {@link HasValue#getEmptyValue()}. This conversion is one-way only, if you
* want to have a two-way mapping back to {@code null}, use
* {@link Binding#withNullRepresentation(Object))}.
*
* @param <FIELDVALUE>
* the value type of the field
* @param field
* the field to be bound, not null
* @return the new binding
*
* @see #bind(HasValue, Function, BiConsumer)
*/
public <FIELDVALUE> Binding<BEAN, FIELDVALUE, FIELDVALUE> forField(
HasValue<FIELDVALUE> field) {
Objects.requireNonNull(field, "field cannot be null");
// clear previous errors for this field and any bean level validation
clearError(field);
getStatusLabel().ifPresent(label -> label.setValue(""));
return createBinding(field, Converter.from(fieldValue -> fieldValue,
modelValue -> Objects.isNull(modelValue) ? field.getEmptyValue()
: modelValue,
exception -> exception.getMessage()),
this::handleValidationStatus);
}
/**
* Binds a field to a bean property represented by the given getter and
* setter pair. The functions are used to update the field value from the
* property and to store the field value to the property, respectively.
* <p>
* Use the {@link #forField(HasValue)} overload instead if you want to
* further configure the new binding.
* <p>
* <strong>Note:</strong> Not all {@link HasValue} implementations support
* passing {@code null} as the value. For these the Binder will
* automatically change {@code null} to a null representation provided by
* {@link HasValue#getEmptyValue()}. This conversion is one-way only, if you
* want to have a two-way mapping back to {@code null}, use
* {@link #forField(HasValue)} and
* {@link Binding#withNullRepresentation(Object))}.
* <p>
* When a bean is bound with {@link Binder#bind(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.bind(nameField, Person::getName, Person::setName);
* </pre>
*
* @param <FIELDVALUE>
* the value type of the field
* @param field
* the field to bind, not null
* @param getter
* the function to get the value of the property to the field,
* not null
* @param setter
* the function to save the field value to the property or null
* if read-only
*/
public <FIELDVALUE> void bind(HasValue<FIELDVALUE> field,
Function<BEAN, FIELDVALUE> getter,
BiConsumer<BEAN, FIELDVALUE> setter) {
forField(field).bind(getter, setter);
}
/**
* Binds the given bean to all the fields added to this Binder. To remove
* the binding, call {@link #unbind()}.
* <p>
* When a bean is bound, the field values are updated by invoking their
* corresponding getter functions. Any changes to field values are reflected
* back to their corresponding property values of the bean as long as the
* bean is bound.
* <p>
* Any change made in the fields also runs validation for the field
* {@link Binding} and bean level validation for this binder (bean level
* validators are added using {@link Binder#withValidator(Validator)}.
*
* @see #load(Object)
* @see #save(Object)
* @see #saveIfValid(Object)
*
* @param bean
* the bean to edit, not null
*/
public void bind(BEAN bean) {
Objects.requireNonNull(bean, "bean cannot be null");
doUnbind(false);
this.bean = bean;
bindings.forEach(b -> b.bind(bean));
// if there has been field value change listeners that trigger
// validation, need to make sure the validation errors are cleared
getValidationStatusHandler()
.accept(BinderValidationStatus.createUnresolvedStatus(this));
fireStatusChangeEvent(false);
}
/**
* Unbinds the currently bound bean if any. If there is no bound bean, does
* nothing.
*/
public void unbind() {
doUnbind(true);
}
/**
* Reads the bound property values from the given bean to the corresponding
* fields.
* <p>
* The bean is not otherwise associated with this binder; in particular its
* property values are not bound to the field value changes. To achieve
* that, use {@link #bind(BEAN)}.
*
* @see #bind(Object)
* @see #saveIfValid(Object)
* @see #save(Object)
*
* @param bean
* the bean whose property values to read, not null
*/
public void load(BEAN bean) {
Objects.requireNonNull(bean, "bean cannot be null");
setHasChanges(false);
bindings.forEach(binding -> binding.setFieldValue(bean));
getValidationStatusHandler()
.accept(BinderValidationStatus.createUnresolvedStatus(this));
fireStatusChangeEvent(false);
}
/**
* Saves changes from the bound fields to the given bean if all validators
* (binding and bean level) pass.
* <p>
* If any field binding validator fails, no values are saved and a
* {@code ValidationException} is thrown.
* <p>
* If all field level validators pass, the given bean is updated and bean
* level validators are run on the updated bean. If any bean level validator
* fails, the bean updates are reverted and a {@code ValidationException} is
* thrown.
*
* @see #saveIfValid(Object)
* @see #load(Object)
* @see #bind(Object)
*
* @param bean
* the object to which to save the field values, not null
* @throws ValidationException
* if some of the bound field values fail to validate
*/
public void save(BEAN bean) throws ValidationException {
BinderValidationStatus<BEAN> status = doSaveIfValid(bean);
if (status.hasErrors()) {
throw new ValidationException(status.getFieldValidationErrors(),
status.getBeanValidationErrors());
}
}
/**
* Saves changes from the bound fields to the given bean if all validators
* (binding and bean level) pass.
* <p>
* If any field binding validator fails, no values are saved and
* <code>false</code> is returned.
* <p>
* If all field level validators pass, the given bean is updated and bean
* level validators are run on the updated bean. If any bean level validator
* fails, the bean updates are reverted and <code>false</code> is returned.
*
* @see #save(Object)
* @see #load(Object)
* @see #bind(Object)
*
* @param bean
* the object to which to save the field values, not null
* @return {@code true} if there was no validation errors and the bean was
* updated, {@code false} otherwise
*/
public boolean saveIfValid(BEAN bean) {
return doSaveIfValid(bean).isOk();
}
/**
* Saves the field values into the given bean if all field level validators
* pass. Runs bean level validators on the bean after saving.
*
* @param bean
* the bean to save field values into
* @return a list of field validation errors if such occur, otherwise a list
* of bean validation errors.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private BinderValidationStatus<BEAN> doSaveIfValid(BEAN bean) {
Objects.requireNonNull(bean, "bean cannot be null");
// First run fields level validation
List<ValidationStatus<?>> bindingStatuses = validateBindings();
// If no validation errors then update bean
if (bindingStatuses.stream().filter(ValidationStatus::isError).findAny()
.isPresent()) {
fireStatusChangeEvent(true);
return new BinderValidationStatus<>(this, bindingStatuses,
Collections.emptyList());
}
// Save old bean values so we can restore them if validators fail
Map<Binding<BEAN, ?, ?>, Object> oldValues = new HashMap<>();
bindings.forEach(
binding -> oldValues.put(binding, binding.getter.apply(bean)));
bindings.forEach(binding -> binding.storeFieldValue(bean));
// Now run bean level validation against the updated bean
List<Result<?>> binderResults = validateBean(bean);
boolean hasErrors = binderResults.stream().filter(Result::isError)
.findAny().isPresent();
if (hasErrors) {
// Bean validator failed, revert values
bindings.forEach((BindingImpl binding) -> binding.setter
.accept(bean, oldValues.get(binding)));
} else {
// Save successful, reset hasChanges to false
setHasChanges(false);
}
fireStatusChangeEvent(hasErrors);
return new BinderValidationStatus<>(this, bindingStatuses,
binderResults);
}
/**
* Adds an bean level validator.
* <p>
* Bean level validators are applied on the bean instance after the bean is
* updated. If the validators fail, the bean instance is reverted to its
* previous state.
*
* @see #save(Object)
* @see #saveIfValid(Object)
*
* @param validator
* the validator to add, not null
* @return this binder, for chaining
*/
public Binder<BEAN> withValidator(Validator<? super BEAN> validator) {
Objects.requireNonNull(validator, "validator cannot be null");
validators.add(validator);
return this;
}
/**
* Validates the values of all bound fields and returns the validation
* status.
* <p>
* If all field level validators pass, and {@link #bind(Object)} has been
* used to bind to a bean, bean level validators are run for that bean. Bean
* level validators are ignored if there is no bound bean or if any field
* level validator fails.
* <p>
*
* @return validation status for the binder
*/
public BinderValidationStatus<BEAN> validate() {
List<ValidationStatus<?>> bindingStatuses = validateBindings();
BinderValidationStatus<BEAN> validationStatus;
if (bindingStatuses.stream().filter(ValidationStatus::isError).findAny()
.isPresent() || bean == null) {
validationStatus = new BinderValidationStatus<>(this,
bindingStatuses, Collections.emptyList());
} else {
validationStatus = new BinderValidationStatus<>(this,
bindingStatuses, validateBean(bean));
}
getValidationStatusHandler().accept(validationStatus);
fireStatusChangeEvent(validationStatus.hasErrors());
return validationStatus;
}
/**
* Validates the bindings and returns the result of the validation as a list
* of validation statuses.
* <p>
* Does not run bean validators.
*
* @see #validateBean(Object)
*
* @return an immutable list of validation results for bindings
*/
private List<ValidationStatus<?>> validateBindings() {
List<ValidationStatus<?>> results = new ArrayList<>();
for (BindingImpl<?, ?, ?> binding : bindings) {
results.add(binding.doValidation());
}
return results;
}
/**
* Validates the {@code bean} using validators added using
* {@link #withValidator(Validator)} and returns the result of the
* validation as a list of validation results.
* <p>
*
* @see #withValidator(Validator)
*
* @param bean
* the bean to validate
* @return a list of validation errors or an empty list if validation
* succeeded
*/
private List<Result<?>> validateBean(BEAN bean) {
Objects.requireNonNull(bean, "bean cannot be null");
List<Result<?>> results = Collections.unmodifiableList(
validators.stream().map(validator -> validator.apply(bean))
.collect(Collectors.toList()));
return results;
}
/**
* Sets the label to show the binder level validation errors not related to
* any specific field.
* <p>
* Only the one validation error message is shown in this label at a time.
* <p>
* This is a convenience method for
* {@link #setValidationStatusHandler(BinderStatusHandler)}, which means
* that this method cannot be used after the handler has been set. Also the
* handler cannot be set after this label has been set.
*
* @param statusLabel
* the status label to set
* @see #setValidationStatusHandler(BinderStatusHandler)
* @see Binding#withStatusLabel(Label)
*/
public void setStatusLabel(Label statusLabel) {
if (statusHandler != null) {
throw new IllegalStateException("Cannot set status label if a "
+ BinderValidationStatusHandler.class.getSimpleName()
+ " has already been set.");
}
this.statusLabel = statusLabel;
}
/**
* Gets the status label or an empty optional if none has been set.
*
* @return the optional status label
* @see #setStatusLabel(Label)
*/
public Optional<Label> getStatusLabel() {
return Optional.ofNullable(statusLabel);
}
/**
* Sets the status handler to track form status changes.
* <p>
* Setting this handler will override the default behavior, which is to let
* fields show their validation status messages and show binder level
* validation errors or OK status in the label set with
* {@link #setStatusLabel(Label)}.
* <p>
* This handler cannot be set after the status label has been set with
* {@link #setStatusLabel(Label)}, or {@link #setStatusLabel(Label)} cannot
* be used after this handler has been set.
*
* @param statusHandler
* the status handler to set, not <code>null</code>
* @throws NullPointerException
* for <code>null</code> status handler
* @see #setStatusLabel(Label)
* @see Binding#withValidationStatusHandler(ValidationStatusHandler)
*/
public void setValidationStatusHandler(
BinderValidationStatusHandler statusHandler) {
Objects.requireNonNull(statusHandler, "Cannot set a null "
+ BinderValidationStatusHandler.class.getSimpleName());
if (statusLabel != null) {
throw new IllegalStateException("Cannot set "
+ BinderValidationStatusHandler.class.getSimpleName()
+ " if a status label has already been set.");
}
this.statusHandler = statusHandler;
}
/**
* Gets the status handler of this form.
* <p>
* If none has been set with
* {@link #setValidationStatusHandler(BinderStatusHandler)}, the default
* implementation is returned.
*
* @return the status handler used, never <code>null</code>
* @see #setValidationStatusHandler(BinderStatusHandler)
*/
public BinderValidationStatusHandler getValidationStatusHandler() {
return Optional.ofNullable(statusHandler)
.orElse(this::handleBinderValidationStatus);
}
/**
* Adds status change listener to the binder.
* <p>
* The {@link Binder} status is changed whenever any of the following
* happens:
* <ul>
* <li>if it's bound and any of its bound field or select has been changed
* <li>{@link #save(Object)} or {@link #saveIfValid(Object)} is called
* <li>{@link #load(Object)} is called
* <li>{@link #bind(Object)} is called
* <li>{@link #unbind(Object)} is called
* <li>{@link Binding#bind(Function, BiConsumer)} is called
* <li>{@link Binder#validate()} or {@link Binding#validate()} is called
* </ul>
*
* @see #load(Object)
* @see #save(Object)
* @see #saveIfValid(Object)
* @see #bind(Object)
* @see #unbind()
* @see #forField(HasValue)
* @see #forSelect(AbstractMultiSelect)
* @See {@link #validate()}
* @see Binding#validate()
* @see Binding#bind(Object)
*
* @param listener
* status change listener to add, not null
* @return a registration for the listener
*/
public Registration addStatusChangeListener(StatusChangeListener listener) {
getEventRouter().addListener(StatusChangeEvent.class, listener,
StatusChangeListener.class.getDeclaredMethods()[0]);
return () -> getEventRouter().removeListener(StatusChangeEvent.class,
listener);
}
/**
* Creates a new binding with the given field.
*
* @param <FIELDVALUE>
* the value type of the field
* @param <TARGET>
* the target data type
* @param field
* the field to bind, not null
* @param converter
* the converter for converting between FIELDVALUE and TARGET
* types, not null
* @param handler
* the handler to notify of status changes, not null
* @return the new incomplete binding
*/
protected <FIELDVALUE, TARGET> BindingImpl<BEAN, FIELDVALUE, TARGET> createBinding(
HasValue<FIELDVALUE> field, Converter<FIELDVALUE, TARGET> converter,
ValidationStatusHandler handler) {
return new BindingImpl<>(this, field, converter, handler);
}
/**
* Clears the error condition of the given field, if any. The default
* implementation clears the
* {@link AbstractComponent#setComponentError(ErrorMessage) component error}
* of the field if it is a Component, otherwise does nothing.
*
* @param field
* the field with an invalid value
*/
protected void clearError(HasValue<?> field) {
if (field instanceof AbstractComponent) {
((AbstractComponent) field).setComponentError(null);
}
}
/**
* Handles a validation error emitted when trying to save the value of the
* given field. The default implementation sets the
* {@link AbstractComponent#setComponentError(ErrorMessage) component error}
* of the field if it is a Component, otherwise does nothing.
*
* @param field
* the field with the invalid value
* @param error
* the error message to set
*/
protected void handleError(HasValue<?> field, String error) {
if (field instanceof AbstractComponent) {
((AbstractComponent) field).setComponentError(new UserError(error));
}
}
/**
* Default {@link ValidationStatusHandler} functional method implementation.
*
* @param status
* the validation status
*/
protected void handleValidationStatus(ValidationStatus<?> status) {
HasValue<?> source = status.getField();
clearError(source);
if (status.isError()) {
handleError(source, status.getMessage().get());
}
}
/**
* Returns the bindings for this binder.
*
* @return a set of the bindings
*/
protected Set<BindingImpl<BEAN, ?, ?>> getBindings() {
return bindings;
}
/**
* The default binder level status handler.
* <p>
* Passes all field related results to the Binding status handlers. All
* other status changes are displayed in the status label, if one has been
* set with {@link #setStatusLabel(Label)}.
*
* @param binderStatus
* status of validation results from binding and/or bean level
* validators
*/
protected void handleBinderValidationStatus(
BinderValidationStatus<?> binderStatus) {
// let field events go to binding status handlers
binderStatus.getFieldValidationStatuses()
.forEach(status -> ((BindingImpl<?, ?, ?>) status.getBinding())
.notifyStatusHandler(status));
// show first possible error or OK status in the label if set
if (getStatusLabel().isPresent()) {
String statusMessage = binderStatus.getBeanValidationErrors()
.stream().findFirst().flatMap(Result::getMessage)
.orElse("");
getStatusLabel().get().setValue(statusMessage);
}
}
/**
* Sets whether the values of the fields this binder is bound to have
* changed since the last explicit call to either bind, save or load.
*
* @param hasChanges
* whether this binder should be marked to have changes
*/
private void setHasChanges(boolean hasChanges) {
this.hasChanges = hasChanges;
}
/**
* Check whether any of the bound fields' values have changed since last
* explicit call to bind, save or load. Unsuccessful save operations will
* not affect this value.
*
* @return whether any bound field's value has changed since last call to
* bind, save or load
*/
public boolean hasChanges() {
return hasChanges;
}
/**
* Returns the event router for this binder.
*
* @return the event router, not null
*/
protected EventRouter getEventRouter() {
if (eventRouter == null) {
eventRouter = new EventRouter();
}
return eventRouter;
}
private void doUnbind(boolean fireStatusEvent) {
setHasChanges(false);
if (bean != null) {
bean = null;
bindings.forEach(BindingImpl::unbind);
}
getValidationStatusHandler()
.accept(BinderValidationStatus.createUnresolvedStatus(this));
if (fireStatusEvent) {
fireStatusChangeEvent(false);
}
}
private void fireStatusChangeEvent(boolean hasValidationErrors) {
getEventRouter()
.fireEvent(new StatusChangeEvent(this, hasValidationErrors));
}
}
|