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
|
package com.vaadin.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import com.vaadin.data.Binder.Binding;
import com.vaadin.data.Binder.BindingBuilder;
import com.vaadin.data.BindingValidationStatus.Status;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.server.AbstractErrorMessage;
import com.vaadin.ui.Button;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Slider;
import com.vaadin.ui.TextField;
/**
* Book of Vaadin tests.
*
* @author Vaadin Ltd
*
*/
@SuppressWarnings("unused")
public class BinderBookOfVaadinTest {
private static class BookPerson {
private String lastName;
private String email, phone, title;
private int yearOfBirth, salaryLevel;
public BookPerson(int yearOfBirth, int salaryLevel) {
this.yearOfBirth = yearOfBirth;
this.salaryLevel = salaryLevel;
}
public BookPerson(BookPerson origin) {
this(origin.yearOfBirth, origin.salaryLevel);
lastName = origin.lastName;
email = origin.email;
phone = origin.phone;
title = origin.title;
}
public BookPerson(String name, int yearOfBirth) {
lastName = name;
this.yearOfBirth = yearOfBirth;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getYearOfBirth() {
return yearOfBirth;
}
public void setYearOfBirth(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
public int getSalaryLevel() {
return salaryLevel;
}
public void setSalaryLevel(int salaryLevel) {
this.salaryLevel = salaryLevel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public static class Trip {
private LocalDate returnDate;
public LocalDate getReturnDate() {
return returnDate;
}
public void setReturnDate(LocalDate returnDate) {
this.returnDate = returnDate;
}
}
private Binder<BookPerson> binder;
private TextField field;
private TextField phoneField;
private TextField emailField;
@Before
public void setUp() {
binder = new Binder<>();
field = new TextField();
phoneField = new TextField();
emailField = new TextField();
// make sure the test is not locale dependent
field.setLocale(Locale.US);
phoneField.setLocale(Locale.US);
emailField.setLocale(Locale.US);
}
@Test
public void loadingFromBusinessObjects() {
// this test is just to make sure the code snippet in the book compiles
binder.readBean(new BookPerson(1969, 50000));
BinderValidationStatus<BookPerson> status = binder.validate();
if (status.hasErrors()) {
Notification.show("Validation error count: "
+ status.getValidationErrors().size());
}
}
@Test
public void handlingCheckedException() {
// another test just to verify that book examples actually compile
try {
binder.writeBean(new BookPerson(2000, 50000));
} catch (ValidationException e) {
Notification.show("Validation error count: "
+ e.getValidationErrors().size());
}
}
@Test
public void simpleEmailValidator() {
binder.forField(field)
// Explicit validator instance
.withValidator(new EmailValidator(
"This doesn't look like a valid email address"))
.bind(BookPerson::getEmail, BookPerson::setEmail);
field.setValue("not-email");
BinderValidationStatus<?> status = binder.validate();
assertEquals(1, status.getFieldValidationErrors().size());
assertEquals("This doesn't look like a valid email address",
status.getFieldValidationErrors().get(0).getMessage().get());
assertEquals("This doesn't look like a valid email address",
((AbstractErrorMessage) field.getErrorMessage()).getMessage());
field.setValue("abc@vaadin.com");
status = binder.validate();
assertEquals(0, status.getBeanValidationErrors().size());
assertNull(field.getErrorMessage());
}
@Test
public void nameLengthTest() {
binder.forField(field)
// Validator defined based on a lambda and an error message
.withValidator(name -> name.length() >= 3,
"Last name must contain at least three characters")
.bind(BookPerson::getLastName, BookPerson::setLastName);
field.setValue("a");
BinderValidationStatus<?> status = binder.validate();
assertEquals(1, status.getFieldValidationErrors().size());
assertEquals("Last name must contain at least three characters",
status.getFieldValidationErrors().get(0).getMessage().get());
assertEquals("Last name must contain at least three characters",
((AbstractErrorMessage) field.getErrorMessage()).getMessage());
field.setValue("long last name");
status = binder.validate();
assertEquals(0, status.getFieldValidationErrors().size());
assertNull(field.getErrorMessage());
}
@Test
public void chainedEmailValidator() {
binder.forField(field)
// Explicit validator instance
.withValidator(new EmailValidator(
"This doesn't look like a valid email address"))
.withValidator(email -> email.endsWith("@acme.com"),
"Only acme.com email addresses are allowed")
.bind(BookPerson::getEmail, BookPerson::setEmail);
field.setValue("not-email");
BinderValidationStatus<?> status = binder.validate();
// Only one error per field should be reported
assertEquals(1, status.getFieldValidationErrors().size());
assertEquals("This doesn't look like a valid email address",
status.getFieldValidationErrors().get(0).getMessage().get());
assertEquals("This doesn't look like a valid email address",
((AbstractErrorMessage) field.getErrorMessage()).getMessage());
field.setValue("abc@vaadin.com");
status = binder.validate();
assertEquals(1, status.getFieldValidationErrors().size());
assertEquals("Only acme.com email addresses are allowed",
status.getFieldValidationErrors().get(0).getMessage().get());
assertEquals("Only acme.com email addresses are allowed",
((AbstractErrorMessage) field.getErrorMessage()).getMessage());
field.setValue("abc@acme.com");
status = binder.validate();
assertEquals(0, status.getFieldValidationErrors().size());
assertNull(field.getErrorMessage());
}
@Test
public void converterBookOfVaadinExample1() {
TextField yearOfBirthField = new TextField();
yearOfBirthField.setLocale(Locale.US);
// Slider for integers between 1 and 10
Slider salaryLevelField = new Slider("Salary level", 1, 10);
BindingBuilder<BookPerson, String> b1 = binder
.forField(yearOfBirthField);
BindingBuilder<BookPerson, Integer> b2 = b1.withConverter(
new StringToIntegerConverter("Must enter a number"));
b2.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
BindingBuilder<BookPerson, Double> salaryBinding1 = binder
.forField(salaryLevelField);
BindingBuilder<BookPerson, Integer> salaryBinding2 = salaryBinding1
.withConverter(Double::intValue, Integer::doubleValue);
salaryBinding2.bind(BookPerson::getSalaryLevel,
BookPerson::setSalaryLevel);
// Test that the book code works
BookPerson bookPerson = new BookPerson(1972, 4);
binder.setBean(bookPerson);
assertEquals(4.0, salaryLevelField.getValue().doubleValue(), 0);
assertEquals("1,972", yearOfBirthField.getValue());
bookPerson.setSalaryLevel(8);
binder.readBean(bookPerson);
assertEquals(8.0, salaryLevelField.getValue().doubleValue(), 0);
bookPerson.setYearOfBirth(123);
binder.readBean(bookPerson);
assertEquals("123", yearOfBirthField.getValue());
yearOfBirthField.setValue("2016");
salaryLevelField.setValue(1.0);
assertEquals(2016, bookPerson.getYearOfBirth());
assertEquals(1, bookPerson.getSalaryLevel());
}
@Test
public void converterBookOfVaadinExample2() {
TextField yearOfBirthField = new TextField();
binder.forField(yearOfBirthField)
.withConverter(Integer::valueOf, String::valueOf,
// Text to use instead of the NumberFormatException
// message
"Please enter a number")
.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
binder.setBean(new BookPerson(1900, 5));
yearOfBirthField.setValue("abc");
binder.validate();
assertEquals("Please enter a number",
yearOfBirthField.getComponentError().getFormattedHtmlMessage());
}
@Test
public void crossFieldValidation_validateUsingBinder() {
Binder<Trip> binder = new Binder<>();
DateField departing = new DateField("Departing");
DateField returning = new DateField("Returning");
Binding<Trip, LocalDate> returnBinding = binder.forField(returning)
.withValidator(
returnDate -> !returnDate
.isBefore(departing.getValue()),
"Cannot return before departing")
.bind(Trip::getReturnDate, Trip::setReturnDate);
departing.addValueChangeListener(event -> returnBinding.validate());
LocalDate past = LocalDate.now();
LocalDate before = past.plusDays(1);
LocalDate after = before.plusDays(1);
departing.setValue(before);
returning.setValue(after);
BinderValidationStatus<Trip> status = binder.validate();
assertTrue(status.getBeanValidationErrors().isEmpty());
assertNull(departing.getComponentError());
assertNull(returning.getComponentError());
// update returning => validation is done against this field
returning.setValue(past);
status = binder.validate();
assertFalse(status.getFieldValidationErrors().isEmpty());
assertNotNull(returning.getComponentError());
assertNull(departing.getComponentError());
// set correct value back
returning.setValue(before);
status = binder.validate();
assertTrue(status.getFieldValidationErrors().isEmpty());
assertNull(departing.getComponentError());
assertNull(returning.getComponentError());
// update departing => validation is done because of listener added
departing.setValue(after);
status = binder.validate();
assertFalse(status.getFieldValidationErrors().isEmpty());
assertNotNull(returning.getComponentError());
assertNull(departing.getComponentError());
}
@Test
public void crossFieldValidation_validateUsingBinding() {
Binder<Trip> binder = new Binder<>();
DateField departing = new DateField("Departing");
DateField returning = new DateField("Returning");
Binding<Trip, LocalDate> returnBinding = binder.forField(returning)
.withValidator(
returnDate -> !returnDate
.isBefore(departing.getValue()),
"Cannot return before departing")
.bind(Trip::getReturnDate, Trip::setReturnDate);
departing.addValueChangeListener(event -> returnBinding.validate());
LocalDate past = LocalDate.now();
LocalDate before = past.plusDays(1);
LocalDate after = before.plusDays(1);
departing.setValue(before);
returning.setValue(after);
BindingValidationStatus<LocalDate> result = returnBinding.validate();
assertFalse(result.isError());
assertNull(departing.getComponentError());
// update returning => validation is done against this field
returning.setValue(past);
result = returnBinding.validate();
assertTrue(result.isError());
assertNotNull(returning.getComponentError());
// set correct value back
returning.setValue(before);
result = returnBinding.validate();
assertFalse(result.isError());
assertNull(departing.getComponentError());
// update departing => validation is done because of listener added
departing.setValue(after);
result = returnBinding.validate();
assertTrue(result.isError());
assertNotNull(returning.getComponentError());
}
@Test
public void withStatusLabelExample() {
Label emailStatus = new Label();
String msg = "This doesn't look like a valid email address";
binder.forField(field).withValidator(new EmailValidator(msg))
.withStatusLabel(emailStatus)
.bind(BookPerson::getEmail, BookPerson::setEmail);
field.setValue("foo");
binder.validate();
assertTrue(emailStatus.isVisible());
assertEquals(msg, emailStatus.getValue());
field.setValue("foo@vaadin.com");
binder.validate();
assertFalse(emailStatus.isVisible());
assertEquals("", emailStatus.getValue());
}
@Test
public void withBindingStatusHandlerExample() {
Label nameStatus = new Label();
AtomicReference<BindingValidationStatus<?>> statusCapture = new AtomicReference<>();
String msg = "Full name must contain at least three characters";
binder.forField(field).withValidator(name -> name.length() >= 3, msg)
.withValidationStatusHandler(status -> {
nameStatus.setValue(status.getMessage().orElse(""));
// Only show the label when validation has failed
boolean error = status.getStatus() == Status.ERROR;
nameStatus.setVisible(error);
statusCapture.set(status);
}).bind(BookPerson::getLastName, BookPerson::setLastName);
field.setValue("aa");
binder.validate();
assertTrue(nameStatus.isVisible());
assertEquals(msg, nameStatus.getValue());
assertNotNull(statusCapture.get());
BindingValidationStatus<?> status = statusCapture.get();
assertEquals(Status.ERROR, status.getStatus());
assertEquals(msg, status.getMessage().get());
assertEquals(field, status.getField());
field.setValue("foo");
binder.validate();
assertFalse(nameStatus.isVisible());
assertEquals("", nameStatus.getValue());
assertNotNull(statusCapture.get());
status = statusCapture.get();
assertEquals(Status.OK, status.getStatus());
assertFalse(status.getMessage().isPresent());
assertEquals(field, status.getField());
}
@Test
public void binder_saveIfValid() {
Binder<BookPerson> binder = new Binder<>(BookPerson.class);
// Phone or email has to be specified for the bean
Validator<BookPerson> phoneOrEmail = Validator.from(
personBean -> !"".equals(personBean.getPhone())
|| !"".equals(personBean.getEmail()),
"A person must have either a phone number or an email address");
binder.withValidator(phoneOrEmail);
binder.forField(emailField).bind("email");
binder.forField(phoneField).bind("phone");
// Person person = // e.g. JPA entity or bean from Grid
BookPerson person = new BookPerson(1900, 5);
person.setEmail("Old Email");
// Load person data to a form
binder.readBean(person);
Button saveButton = new Button("Save", event -> {
// Using saveIfValid to avoid the try-catch block that is
// needed if using the regular save method
if (binder.writeBeanIfValid(person)) {
// Person is valid and updated
// TODO Store in the database
}
});
emailField.setValue("foo@bar.com");
assertTrue(binder.writeBeanIfValid(person));
// Person updated
assertEquals("foo@bar.com", person.getEmail());
emailField.setValue("");
assertFalse(binder.writeBeanIfValid(person));
// Person updated because phone and email are both empty
assertEquals("foo@bar.com", person.getEmail());
}
@Test
public void manyConvertersAndValidators() throws ValidationException {
TextField yearOfBirthField = new TextField();
binder.forField(yearOfBirthField)
// Validator will be run with the String value of the field
.withValidator(text -> text.length() == 4,
"Doesn't look like a year")
// Converter will only be run for strings with 4 characters
.withConverter(
new StringToIntegerConverter("Must enter a number"))
// Validator will be run with the converted value
.withValidator(year -> year >= 1900 && year <= 2000,
"Person must be born in the 20th century")
.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
yearOfBirthField.setValue("abc");
assertEquals("Doesn't look like a year", binder.validate()
.getFieldValidationErrors().get(0).getMessage().get());
yearOfBirthField.setValue("abcd");
assertEquals("Must enter a number", binder.validate()
.getFieldValidationErrors().get(0).getMessage().get());
yearOfBirthField.setValue("1200");
assertEquals("Person must be born in the 20th century",
binder.validate().getFieldValidationErrors().get(0).getMessage()
.get());
yearOfBirthField.setValue("1950");
assertFalse(binder.validate().hasErrors());
BookPerson person = new BookPerson(1500, 12);
binder.writeBean(person);
assertEquals(1950, person.getYearOfBirth());
}
class MyConverter implements Converter<String, Integer> {
@Override
public Result<Integer> convertToModel(String fieldValue,
ValueContext context) {
// Produces a converted value or an error
try {
// ok is a static helper method that creates a Result
return Result.ok(Integer.valueOf(fieldValue));
} catch (NumberFormatException e) {
// error is a static helper method that creates a Result
return Result.error("Please enter a number");
}
}
@Override
public String convertToPresentation(Integer integer,
ValueContext context) {
// Converting to the field type should always succeed,
// so there is no support for returning an error Result.
return String.valueOf(integer);
}
}
@Test
public void bindUsingCustomConverter() {
Binder<BookPerson> binder = new Binder<>();
TextField yearOfBirthField = new TextField();
// Using the converter
binder.forField(yearOfBirthField).withConverter(new MyConverter())
.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
BookPerson p = new BookPerson(1500, 12);
binder.setBean(p);
yearOfBirthField.setValue("abc");
assertTrue(binder.validate().hasErrors());
assertEquals("Please enter a number", binder.validate()
.getFieldValidationErrors().get(0).getMessage().get());
yearOfBirthField.setValue("123");
assertTrue(binder.validate().isOk());
p.setYearOfBirth(12500);
binder.readBean(p);
assertEquals("12500", yearOfBirthField.getValue());
assertTrue(binder.validate().isOk());
}
@Test
public void withBinderStatusLabelExample() {
Label formStatusLabel = new Label();
Binder<BookPerson> binder = new Binder<>(BookPerson.class);
binder.setStatusLabel(formStatusLabel);
final String message = "Too young, son";
final String message2 = "Y2K error";
TextField yearOfBirth = new TextField();
BookPerson p = new BookPerson(1500, 12);
binder.forField(yearOfBirth)
.withConverter(new StringToIntegerConverter("err"))
.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
binder.withValidator(bean -> bean.yearOfBirth < 2000, message)
.withValidator(bean -> bean.yearOfBirth != 2000, message2);
binder.setBean(p);
// first bean validator fails and passes error message to status label
yearOfBirth.setValue("2001");
BinderValidationStatus<?> status = binder.validate();
assertEquals(0, status.getFieldValidationErrors().size());
assertEquals(1, status.getBeanValidationErrors().size());
assertEquals(message,
status.getBeanValidationErrors().get(0).getErrorMessage());
assertEquals(message, formStatusLabel.getValue());
// value is correct, status label is cleared
yearOfBirth.setValue("1999");
status = binder.validate();
assertFalse(status.hasErrors());
assertEquals("", formStatusLabel.getValue());
// both bean validators fail, should be two error messages chained
yearOfBirth.setValue("2000");
status = binder.validate();
assertEquals(2, status.getBeanValidationResults().size());
assertEquals(0, status.getFieldValidationErrors().size());
assertEquals(2, status.getBeanValidationErrors().size());
// only first error is shown
assertEquals(message, formStatusLabel.getValue());
}
@Test
public void withBinderStatusHandlerExample() {
Label formStatusLabel = new Label();
BinderValidationStatusHandler<BookPerson> defaultHandler = binder
.getValidationStatusHandler();
binder.setValidationStatusHandler(status -> {
// create an error message on failed bean level validations
List<ValidationResult> errors = status.getBeanValidationErrors();
String errorMessage = errors.stream()
.map(ValidationResult::getErrorMessage)
.collect(Collectors.joining("\n"));
// show error in a label
formStatusLabel.setValue(errorMessage);
formStatusLabel.setVisible(!errorMessage.isEmpty());
// Let the default handler show messages for each field
defaultHandler.statusChange(status);
});
final String bindingMessage = "uneven";
final String message = "Too young, son";
final String message2 = "Y2K error";
TextField yearOfBirth = new TextField();
BookPerson p = new BookPerson(1500, 12);
binder.forField(yearOfBirth)
.withConverter(new StringToIntegerConverter("err"))
.withValidator(value -> value % 2 == 0, bindingMessage)
.bind(BookPerson::getYearOfBirth, BookPerson::setYearOfBirth);
binder.withValidator(bean -> bean.yearOfBirth < 2000, message)
.withValidator(bean -> bean.yearOfBirth != 2000, message2);
binder.setBean(p);
// first binding validation fails, no bean level validation is done
yearOfBirth.setValue("2001");
BinderValidationStatus<?> status = binder.validate();
assertEquals(1, status.getFieldValidationErrors().size());
assertEquals(bindingMessage,
status.getFieldValidationErrors().get(0).getMessage().get());
assertEquals("", formStatusLabel.getValue());
// first bean validator fails and passes error message to status label
yearOfBirth.setValue("2002");
status = binder.validate();
assertEquals(0, status.getFieldValidationErrors().size());
assertEquals(1, status.getBeanValidationErrors().size());
assertEquals(message,
status.getBeanValidationErrors().get(0).getErrorMessage());
assertEquals(message, formStatusLabel.getValue());
// value is correct, status label is cleared
yearOfBirth.setValue("1998");
status = binder.validate();
assertTrue(status.isOk());
assertFalse(status.hasErrors());
assertEquals(0, status.getFieldValidationErrors().size());
assertEquals(0, status.getBeanValidationErrors().size());
assertEquals("", formStatusLabel.getValue());
// both bean validators fail, should be two error messages chained
yearOfBirth.setValue("2000");
status = binder.validate();
assertEquals(0, status.getFieldValidationErrors().size());
assertEquals(2, status.getBeanValidationErrors().size());
assertEquals(message + "\n" + message2, formStatusLabel.getValue());
}
@Test
public void statusChangeListener_binderIsNotBound() {
Button saveButton = new Button();
Button resetButton = new Button();
AtomicBoolean eventIsFired = new AtomicBoolean(false);
binder.addStatusChangeListener(event -> {
boolean isValid = event.getBinder().isValid();
boolean hasChanges = event.getBinder().hasChanges();
eventIsFired.set(true);
saveButton.setEnabled(hasChanges && isValid);
resetButton.setEnabled(hasChanges);
});
binder.forField(field)
.withValidator(new StringLengthValidator("", 1, 3))
.bind(BookPerson::getLastName, BookPerson::setLastName);
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
BookPerson person = new BookPerson(2000, 1);
binder.readBean(person);
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
field.setValue("a");
// binder is not bound, no event fired
// no changes: see #375. There should be a change and enabled state
assertTrue(saveButton.isEnabled());
assertTrue(resetButton.isEnabled());
assertTrue(eventIsFired.get());
binder.writeBeanIfValid(person);
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
binder.validate();
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
field.setValue("");
// binder is not bound, no event fired
// no changes: see #375. There should be a change and disabled state for
// save button because of failed validation
assertFalse(saveButton.isEnabled());
assertTrue(resetButton.isEnabled());
assertTrue(eventIsFired.get());
}
@Test
public void statusChangeListener_binderIsBound() {
Button saveButton = new Button();
Button resetButton = new Button();
AtomicBoolean eventIsFired = new AtomicBoolean(false);
binder.addStatusChangeListener(event -> {
boolean isValid = event.getBinder().isValid();
boolean hasChanges = event.getBinder().hasChanges();
eventIsFired.set(true);
saveButton.setEnabled(hasChanges && isValid);
resetButton.setEnabled(hasChanges);
});
binder.forField(field)
.withValidator(new StringLengthValidator("", 1, 3))
.bind(BookPerson::getLastName, BookPerson::setLastName);
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
BookPerson person = new BookPerson(2000, 1);
binder.setBean(person);
// no changes
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
field.setValue("a");
// there are valid changes
verifyEventIsFired(eventIsFired);
field.setValue("");
// there are invalid changes
assertFalse(saveButton.isEnabled());
assertTrue(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
// set valid value
field.setValue("a");
verifyEventIsFired(eventIsFired);
binder.writeBeanIfValid(person);
// there are no changes.
assertFalse(saveButton.isEnabled());
assertFalse(resetButton.isEnabled());
verifyEventIsFired(eventIsFired);
}
@Test
public void statusChangeListener_multipleRequiredFields() {
Button saveButton = new Button();
binder.addStatusChangeListener(event -> {
boolean isValid = event.getBinder().isValid();
boolean hasChanges = event.getBinder().hasChanges();
saveButton.setEnabled(hasChanges && isValid);
});
binder.forField(field).asRequired("").bind(BookPerson::getLastName,
BookPerson::setLastName);
binder.forField(emailField).asRequired("").bind(BookPerson::getEmail,
BookPerson::setEmail);
assertFalse(saveButton.isEnabled());
field.setValue("not empty");
assertFalse(saveButton.isEnabled());
emailField.setValue("not empty");
assertTrue(saveButton.isEnabled());
field.clear();
assertFalse(saveButton.isEnabled());
}
@Test
public void writeBean_throwsValidationException_bookExampleShouldCompile() {
// The person to edit
// Would be loaded from the backend in a real application
BookPerson person = new BookPerson("John Doe", 1957);
// Updates the value in each bound field component
binder.readBean(person);
Button saveButton = new Button("Save", event -> {
try {
binder.writeBean(person);
// A real application would also save the updated person
// using the application's backend
} catch (ValidationException e) {
Notification.show("Person could not be saved, "
+ "please check error messages for each field.");
}
});
// Updates the fields again with the previously saved values
Button resetButton = new Button("Reset",
event -> binder.readBean(person));
}
private void verifyEventIsFired(AtomicBoolean flag) {
assertTrue(flag.get());
flag.set(false);
}
}
|