You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BinderTest.java 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. package com.vaadin.data;
  2. import static org.junit.Assert.assertArrayEquals;
  3. import static org.junit.Assert.assertEquals;
  4. import static org.junit.Assert.assertFalse;
  5. import static org.junit.Assert.assertNotEquals;
  6. import static org.junit.Assert.assertNotNull;
  7. import static org.junit.Assert.assertNull;
  8. import static org.junit.Assert.assertSame;
  9. import static org.junit.Assert.assertTrue;
  10. import static org.junit.Assert.fail;
  11. import java.util.Locale;
  12. import java.util.Objects;
  13. import java.util.concurrent.atomic.AtomicBoolean;
  14. import java.util.concurrent.atomic.AtomicInteger;
  15. import java.util.concurrent.atomic.AtomicReference;
  16. import java.util.stream.Stream;
  17. import org.junit.Assert;
  18. import org.junit.Before;
  19. import org.junit.Test;
  20. import org.junit.Rule;
  21. import org.junit.rules.ExpectedException;
  22. import com.vaadin.data.Binder.Binding;
  23. import com.vaadin.data.Binder.BindingBuilder;
  24. import com.vaadin.data.converter.StringToIntegerConverter;
  25. import com.vaadin.data.validator.IntegerRangeValidator;
  26. import com.vaadin.data.validator.NotEmptyValidator;
  27. import com.vaadin.data.validator.StringLengthValidator;
  28. import com.vaadin.server.ErrorMessage;
  29. import com.vaadin.shared.ui.ErrorLevel;
  30. import com.vaadin.tests.data.bean.Person;
  31. import com.vaadin.tests.data.bean.Sex;
  32. import com.vaadin.ui.TextField;
  33. import org.apache.commons.lang.StringUtils;
  34. import org.hamcrest.CoreMatchers;
  35. public class BinderTest extends BinderTestBase<Binder<Person>, Person> {
  36. @Rule
  37. /*
  38. * transient to avoid interfering with serialization tests that capture a
  39. * test instance in a closure
  40. */
  41. public transient ExpectedException exceptionRule = ExpectedException.none();
  42. @Before
  43. public void setUp() {
  44. binder = new Binder<>();
  45. item = new Person();
  46. item.setFirstName("Johannes");
  47. item.setAge(32);
  48. }
  49. @Test
  50. public void bindNullBean_noBeanPresent() {
  51. binder.setBean(item);
  52. assertNotNull(binder.getBean());
  53. binder.setBean(null);
  54. assertNull(binder.getBean());
  55. }
  56. @Test
  57. public void bindNullBean_FieldsAreCleared() {
  58. binder.forField(nameField).bind(Person::getFirstName,
  59. Person::setFirstName);
  60. binder.forField(ageField)
  61. .withConverter(new StringToIntegerConverter(""))
  62. .bind(Person::getAge, Person::setAge);
  63. binder.setBean(item);
  64. assertEquals("No name field value", "Johannes", nameField.getValue());
  65. assertEquals("No age field value", "32", ageField.getValue());
  66. binder.setBean(null);
  67. assertEquals("Name field not empty", "", nameField.getValue());
  68. assertEquals("Age field not empty", "", ageField.getValue());
  69. }
  70. @Test
  71. public void clearForReadBean_boundFieldsAreCleared() {
  72. binder.forField(nameField).bind(Person::getFirstName,
  73. Person::setFirstName);
  74. binder.forField(ageField)
  75. .withConverter(new StringToIntegerConverter(""))
  76. .bind(Person::getAge, Person::setAge);
  77. binder.readBean(item);
  78. assertEquals("No name field value", "Johannes", nameField.getValue());
  79. assertEquals("No age field value", "32", ageField.getValue());
  80. binder.readBean(null);
  81. assertEquals("Name field not empty", "", nameField.getValue());
  82. assertEquals("Age field not empty", "", ageField.getValue());
  83. }
  84. @Test
  85. public void clearReadOnlyField_shouldClearField() {
  86. binder.forField(nameField).bind(Person::getFirstName,
  87. Person::setFirstName);
  88. // Make name field read only
  89. nameField.setReadOnly(true);
  90. binder.setBean(item);
  91. assertEquals("No name field value", "Johannes", nameField.getValue());
  92. binder.setBean(null);
  93. assertEquals("ReadOnly field not empty", "", nameField.getValue());
  94. }
  95. @Test
  96. public void clearBean_setsHasChangesToFalse() {
  97. binder.forField(nameField).bind(Person::getFirstName,
  98. Person::setFirstName);
  99. // Make name field read only
  100. nameField.setReadOnly(true);
  101. binder.readBean(item);
  102. assertEquals("No name field value", "Johannes", nameField.getValue());
  103. nameField.setValue("James");
  104. assertTrue("Binder did not have value changes", binder.hasChanges());
  105. binder.readBean(null);
  106. assertFalse("Binder has changes after clearing all fields",
  107. binder.hasChanges());
  108. }
  109. @Test
  110. public void clearReadOnlyBinder_shouldClearFields() {
  111. binder.forField(nameField).bind(Person::getFirstName,
  112. Person::setFirstName);
  113. binder.forField(ageField)
  114. .withConverter(new StringToIntegerConverter(""))
  115. .bind(Person::getAge, Person::setAge);
  116. binder.setReadOnly(true);
  117. binder.setBean(item);
  118. binder.setBean(null);
  119. assertEquals("ReadOnly name field not empty", "", nameField.getValue());
  120. assertEquals("ReadOnly age field not empty", "", ageField.getValue());
  121. }
  122. @Test(expected = NullPointerException.class)
  123. public void bindNullField_throws() {
  124. binder.forField(null);
  125. }
  126. @Test(expected = NullPointerException.class)
  127. public void bindNullGetter_throws() {
  128. binder.bind(nameField, null, Person::setFirstName);
  129. }
  130. @Test
  131. public void fieldBound_bindItem_fieldValueUpdated() {
  132. binder.forField(nameField).bind(Person::getFirstName,
  133. Person::setFirstName);
  134. binder.setBean(item);
  135. assertEquals("Johannes", nameField.getValue());
  136. }
  137. @Test
  138. public void fieldBoundWithShortcut_bindBean_fieldValueUpdated() {
  139. bindName();
  140. assertEquals("Johannes", nameField.getValue());
  141. }
  142. @Test
  143. public void beanBound_updateFieldValue_beanValueUpdated() {
  144. binder.setBean(item);
  145. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  146. assertEquals("Johannes", nameField.getValue());
  147. nameField.setValue("Artur");
  148. assertEquals("Artur", item.getFirstName());
  149. }
  150. @Test
  151. public void bound_getBean_returnsBoundBean() {
  152. assertNull(binder.getBean());
  153. binder.setBean(item);
  154. assertSame(item, binder.getBean());
  155. }
  156. @Test
  157. public void unbound_getBean_returnsNothing() {
  158. binder.setBean(item);
  159. binder.removeBean();
  160. assertNull(binder.getBean());
  161. }
  162. @Test
  163. public void bound_changeFieldValue_beanValueUpdated() {
  164. bindName();
  165. nameField.setValue("Henri");
  166. assertEquals("Henri", item.getFirstName());
  167. }
  168. @Test
  169. public void unbound_changeFieldValue_beanValueNotUpdated() {
  170. bindName();
  171. nameField.setValue("Henri");
  172. binder.removeBean();
  173. nameField.setValue("Aleksi");
  174. assertEquals("Henri", item.getFirstName());
  175. }
  176. @Test
  177. public void bindNullSetter_valueChangesIgnored() {
  178. binder.bind(nameField, Person::getFirstName, null);
  179. binder.setBean(item);
  180. nameField.setValue("Artur");
  181. assertEquals(item.getFirstName(), "Johannes");
  182. }
  183. @Test
  184. public void bound_bindToAnotherBean_stopsUpdatingOriginal() {
  185. bindName();
  186. nameField.setValue("Leif");
  187. Person p2 = new Person();
  188. p2.setFirstName("Marlon");
  189. binder.setBean(p2);
  190. assertEquals("Marlon", nameField.getValue());
  191. assertEquals("Leif", item.getFirstName());
  192. assertSame(p2, binder.getBean());
  193. nameField.setValue("Ilia");
  194. assertEquals("Ilia", p2.getFirstName());
  195. assertEquals("Leif", item.getFirstName());
  196. }
  197. @Test
  198. public void save_unbound_noChanges() throws ValidationException {
  199. Binder<Person> binder = new Binder<>();
  200. Person person = new Person();
  201. int age = 10;
  202. person.setAge(age);
  203. binder.writeBean(person);
  204. assertEquals(age, person.getAge());
  205. }
  206. @Test
  207. public void save_bound_beanIsUpdated() throws ValidationException {
  208. Binder<Person> binder = new Binder<>();
  209. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  210. Person person = new Person();
  211. String fieldValue = "bar";
  212. nameField.setValue(fieldValue);
  213. person.setFirstName("foo");
  214. binder.writeBean(person);
  215. assertEquals(fieldValue, person.getFirstName());
  216. }
  217. @Test
  218. public void save_bound_beanAsDraft() {
  219. Binder<Person> binder = new Binder<>();
  220. binder.forField(nameField)
  221. .withValidator((value,context) -> {
  222. if (value.equals("Mike")) return ValidationResult.ok();
  223. else return ValidationResult.error("value must be Mike");
  224. })
  225. .bind(Person::getFirstName, Person::setFirstName);
  226. binder.forField(ageField)
  227. .withConverter(new StringToIntegerConverter(""))
  228. .bind(Person::getAge, Person::setAge);
  229. Person person = new Person();
  230. String fieldValue = "John";
  231. nameField.setValue(fieldValue);
  232. int age = 10;
  233. ageField.setValue("10");
  234. person.setFirstName("Mark");
  235. binder.writeBeanAsDraft(person);
  236. // name is not written to draft as validation / conversion
  237. // does not pass
  238. assertNotEquals(fieldValue, person.getFirstName());
  239. // age is written to draft even if firstname validation
  240. // fails
  241. assertEquals(age, person.getAge());
  242. }
  243. @Test
  244. public void load_bound_fieldValueIsUpdated() {
  245. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  246. Person person = new Person();
  247. String name = "bar";
  248. person.setFirstName(name);
  249. binder.readBean(person);
  250. assertEquals(name, nameField.getValue());
  251. }
  252. @Test
  253. public void load_unbound_noChanges() {
  254. nameField.setValue("");
  255. Person person = new Person();
  256. String name = "bar";
  257. person.setFirstName(name);
  258. binder.readBean(person);
  259. assertEquals("", nameField.getValue());
  260. }
  261. protected void bindName() {
  262. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  263. binder.setBean(item);
  264. }
  265. @Test
  266. public void binding_with_null_representation() {
  267. String nullRepresentation = "Some arbitrary text";
  268. String realName = "John";
  269. Person namelessPerson = new Person(null, "Doe", "", 25, Sex.UNKNOWN,
  270. null);
  271. binder.forField(nameField).withNullRepresentation(nullRepresentation)
  272. .bind(Person::getFirstName, Person::setFirstName);
  273. // Bind a person with null value and check that null representation is
  274. // used
  275. binder.setBean(namelessPerson);
  276. assertEquals(
  277. "Null value from bean was not converted to explicit null representation",
  278. nullRepresentation, nameField.getValue());
  279. // Verify that changes are applied to bean
  280. nameField.setValue(realName);
  281. assertEquals(
  282. "Bean was not correctly updated from a change in the field",
  283. realName, namelessPerson.getFirstName());
  284. // Verify conversion back to null
  285. nameField.setValue(nullRepresentation);
  286. assertEquals(
  287. "Two-way null representation did not change value back to null",
  288. null, namelessPerson.getFirstName());
  289. }
  290. @Test
  291. public void binding_with_default_null_representation() {
  292. TextField nullTextField = new TextField() {
  293. @Override
  294. public String getEmptyValue() {
  295. return "null";
  296. }
  297. };
  298. Person namelessPerson = new Person(null, "Doe", "", 25, Sex.UNKNOWN,
  299. null);
  300. binder.bind(nullTextField, Person::getFirstName, Person::setFirstName);
  301. binder.setBean(namelessPerson);
  302. assertTrue(nullTextField.isEmpty());
  303. assertEquals("null", namelessPerson.getFirstName());
  304. // Change value, see that textfield is not empty and bean is updated.
  305. nullTextField.setValue("");
  306. assertFalse(nullTextField.isEmpty());
  307. assertEquals("First name of person was not properly updated", "",
  308. namelessPerson.getFirstName());
  309. // Verify that default null representation does not map back to null
  310. nullTextField.setValue("null");
  311. assertTrue(nullTextField.isEmpty());
  312. assertEquals("Default one-way null representation failed.", "null",
  313. namelessPerson.getFirstName());
  314. }
  315. @Test
  316. public void binding_with_null_representation_value_not_null() {
  317. String nullRepresentation = "Some arbitrary text";
  318. binder.forField(nameField).withNullRepresentation(nullRepresentation)
  319. .bind(Person::getFirstName, Person::setFirstName);
  320. assertFalse("First name in item should not be null",
  321. Objects.isNull(item.getFirstName()));
  322. binder.setBean(item);
  323. assertEquals("Field value was not set correctly", item.getFirstName(),
  324. nameField.getValue());
  325. }
  326. @Test
  327. public void withConverter_disablesDefaulNullRepresentation() {
  328. Integer customNullConverter = 0;
  329. binder.forField(ageField).withNullRepresentation("foo")
  330. .withConverter(new StringToIntegerConverter(""))
  331. .withConverter(age -> age,
  332. age -> age == null ? customNullConverter : age)
  333. .bind(Person::getSalary, Person::setSalary);
  334. binder.setBean(item);
  335. assertEquals(customNullConverter.toString(), ageField.getValue());
  336. Integer salary = 11;
  337. ageField.setValue(salary.toString());
  338. assertEquals(11, salary.intValue());
  339. }
  340. @Test
  341. public void beanBinder_nullRepresentationIsNotDisabled() {
  342. Binder<Person> binder = new Binder<>(Person.class);
  343. binder.forField(nameField).bind("firstName");
  344. Person person = new Person();
  345. binder.setBean(person);
  346. assertEquals("", nameField.getValue());
  347. }
  348. @Test
  349. public void beanBinder_withConverter_nullRepresentationIsNotDisabled() {
  350. String customNullPointerRepresentation = "foo";
  351. Binder<Person> binder = new Binder<>(Person.class);
  352. binder.forField(nameField)
  353. .withConverter(value -> value,
  354. value -> value == null ? customNullPointerRepresentation
  355. : value)
  356. .bind("firstName");
  357. Person person = new Person();
  358. binder.setBean(person);
  359. assertEquals(customNullPointerRepresentation, nameField.getValue());
  360. }
  361. @Test
  362. public void withValidator_doesNotDisablesDefaulNullRepresentation() {
  363. String nullRepresentation = "foo";
  364. binder.forField(nameField).withNullRepresentation(nullRepresentation)
  365. .withValidator(new NotEmptyValidator<>(""))
  366. .bind(Person::getFirstName, Person::setFirstName);
  367. item.setFirstName(null);
  368. binder.setBean(item);
  369. assertEquals(nullRepresentation, nameField.getValue());
  370. String newValue = "bar";
  371. nameField.setValue(newValue);
  372. assertEquals(newValue, item.getFirstName());
  373. }
  374. @Test
  375. public void setRequired_withErrorMessage_fieldGetsRequiredIndicatorAndValidator() {
  376. TextField textField = new TextField();
  377. assertFalse(textField.isRequiredIndicatorVisible());
  378. BindingBuilder<Person, String> bindingBuilder = binder.forField(textField);
  379. assertFalse(textField.isRequiredIndicatorVisible());
  380. bindingBuilder.asRequired("foobar");
  381. assertTrue(textField.isRequiredIndicatorVisible());
  382. Binding<Person, String> binding = bindingBuilder.bind(Person::getFirstName, Person::setFirstName);
  383. binder.setBean(item);
  384. assertNull(textField.getErrorMessage());
  385. textField.setValue(textField.getEmptyValue());
  386. ErrorMessage errorMessage = textField.getErrorMessage();
  387. assertNotNull(errorMessage);
  388. assertEquals("foobar", errorMessage.getFormattedHtmlMessage());
  389. textField.setValue("value");
  390. assertNull(textField.getErrorMessage());
  391. assertTrue(textField.isRequiredIndicatorVisible());
  392. binding.setAsRequiredEnabled(false);
  393. assertFalse(textField.isRequiredIndicatorVisible());
  394. }
  395. @Test
  396. public void readNullBeanRemovesError() {
  397. TextField textField = new TextField();
  398. binder.forField(textField).asRequired("foobar")
  399. .bind(Person::getFirstName, Person::setFirstName);
  400. assertTrue(textField.isRequiredIndicatorVisible());
  401. assertNull(textField.getErrorMessage());
  402. binder.readBean(item);
  403. assertNull(textField.getErrorMessage());
  404. textField.setValue(textField.getEmptyValue());
  405. assertTrue(textField.isRequiredIndicatorVisible());
  406. assertNotNull(textField.getErrorMessage());
  407. binder.readBean(null);
  408. assertTrue(textField.isRequiredIndicatorVisible());
  409. assertNull(textField.getErrorMessage());
  410. }
  411. @Test
  412. public void setRequired_withErrorMessageProvider_fieldGetsRequiredIndicatorAndValidator() {
  413. TextField textField = new TextField();
  414. textField.setLocale(Locale.CANADA);
  415. assertFalse(textField.isRequiredIndicatorVisible());
  416. BindingBuilder<Person, String> binding = binder.forField(textField);
  417. assertFalse(textField.isRequiredIndicatorVisible());
  418. AtomicInteger invokes = new AtomicInteger();
  419. binding.asRequired(context -> {
  420. invokes.incrementAndGet();
  421. assertSame(Locale.CANADA, context.getLocale().get());
  422. return "foobar";
  423. });
  424. assertTrue(textField.isRequiredIndicatorVisible());
  425. binding.bind(Person::getFirstName, Person::setFirstName);
  426. binder.setBean(item);
  427. assertNull(textField.getErrorMessage());
  428. assertEquals(0, invokes.get());
  429. textField.setValue(textField.getEmptyValue());
  430. ErrorMessage errorMessage = textField.getErrorMessage();
  431. assertNotNull(errorMessage);
  432. assertEquals("foobar", errorMessage.getFormattedHtmlMessage());
  433. // validation is done for all changed bindings once.
  434. assertEquals(1, invokes.get());
  435. textField.setValue("value");
  436. assertNull(textField.getErrorMessage());
  437. assertTrue(textField.isRequiredIndicatorVisible());
  438. }
  439. @Test
  440. public void setRequired_withCustomValidator_fieldGetsRequiredIndicatorAndValidator() {
  441. TextField textField = new TextField();
  442. textField.setLocale(Locale.CANADA);
  443. assertFalse(textField.isRequiredIndicatorVisible());
  444. BindingBuilder<Person, String> binding = binder.forField(textField);
  445. assertFalse(textField.isRequiredIndicatorVisible());
  446. AtomicInteger invokes = new AtomicInteger();
  447. Validator<String> customRequiredValidator = (value, context) -> {
  448. invokes.incrementAndGet();
  449. if (StringUtils.isBlank(value)) {
  450. return ValidationResult.error("Input is required.");
  451. }
  452. return ValidationResult.ok();
  453. };
  454. binding.asRequired(customRequiredValidator);
  455. assertTrue(textField.isRequiredIndicatorVisible());
  456. binding.bind(Person::getFirstName, Person::setFirstName);
  457. binder.setBean(item);
  458. assertNull(textField.getErrorMessage());
  459. assertEquals(1, invokes.get());
  460. textField.setValue(" ");
  461. ErrorMessage errorMessage = textField.getErrorMessage();
  462. assertNotNull(errorMessage);
  463. assertEquals("Input&#32;is&#32;required&#46;",
  464. errorMessage.getFormattedHtmlMessage());
  465. // validation is done for all changed bindings once.
  466. assertEquals(2, invokes.get());
  467. textField.setValue("value");
  468. assertNull(textField.getErrorMessage());
  469. assertTrue(textField.isRequiredIndicatorVisible());
  470. }
  471. @Test
  472. public void setRequired_withCustomValidator_modelConverterBeforeValidator() {
  473. TextField textField = new TextField();
  474. textField.setLocale(Locale.CANADA);
  475. assertFalse(textField.isRequiredIndicatorVisible());
  476. Converter<String, String> stringBasicPreProcessingConverter = new Converter<String, String>() {
  477. @Override
  478. public Result<String> convertToModel(String value,
  479. ValueContext context) {
  480. if (StringUtils.isBlank(value)) {
  481. return Result.ok(null);
  482. }
  483. return Result.ok(StringUtils.trim(value));
  484. }
  485. @Override
  486. public String convertToPresentation(String value,
  487. ValueContext context) {
  488. if (value == null) {
  489. return "";
  490. }
  491. return value;
  492. }
  493. };
  494. AtomicInteger invokes = new AtomicInteger();
  495. Validator<String> customRequiredValidator = (value, context) -> {
  496. invokes.incrementAndGet();
  497. if (value == null) {
  498. return ValidationResult.error("Input required.");
  499. }
  500. return ValidationResult.ok();
  501. };
  502. binder.forField(textField)
  503. .withConverter(stringBasicPreProcessingConverter)
  504. .asRequired(customRequiredValidator)
  505. .bind(Person::getFirstName, Person::setFirstName);
  506. binder.setBean(item);
  507. assertNull(textField.getErrorMessage());
  508. assertEquals(1, invokes.get());
  509. textField.setValue(" ");
  510. ErrorMessage errorMessage = textField.getErrorMessage();
  511. assertNotNull(errorMessage);
  512. assertEquals("Input&#32;required&#46;",
  513. errorMessage.getFormattedHtmlMessage());
  514. // validation is done for all changed bindings once.
  515. assertEquals(2, invokes.get());
  516. textField.setValue("value");
  517. assertNull(textField.getErrorMessage());
  518. assertTrue(textField.isRequiredIndicatorVisible());
  519. }
  520. @Test
  521. public void validationStatusHandler_onlyRunForChangedField() {
  522. TextField firstNameField = new TextField();
  523. TextField lastNameField = new TextField();
  524. AtomicInteger invokes = new AtomicInteger();
  525. binder.forField(firstNameField)
  526. .withValidator(new NotEmptyValidator<>(""))
  527. .withValidationStatusHandler(
  528. validationStatus -> invokes.addAndGet(1))
  529. .bind(Person::getFirstName, Person::setFirstName);
  530. binder.forField(lastNameField)
  531. .withValidator(new NotEmptyValidator<>(""))
  532. .bind(Person::getLastName, Person::setLastName);
  533. binder.setBean(item);
  534. // setting the bean causes 2:
  535. assertEquals(2, invokes.get());
  536. lastNameField.setValue("");
  537. assertEquals(2, invokes.get());
  538. firstNameField.setValue("");
  539. assertEquals(3, invokes.get());
  540. binder.removeBean();
  541. Person person = new Person();
  542. person.setFirstName("a");
  543. person.setLastName("a");
  544. binder.readBean(person);
  545. // reading from a bean causes 2:
  546. assertEquals(5, invokes.get());
  547. lastNameField.setValue("");
  548. assertEquals(5, invokes.get());
  549. firstNameField.setValue("");
  550. assertEquals(6, invokes.get());
  551. }
  552. @Test(expected = IllegalStateException.class)
  553. public void noArgsConstructor_stringBind_throws() {
  554. binder.bind(new TextField(), "firstName");
  555. }
  556. @Test
  557. public void setReadOnly_unboundBinder() {
  558. binder.forField(nameField).bind(Person::getFirstName,
  559. Person::setFirstName);
  560. binder.forField(ageField);
  561. binder.setReadOnly(true);
  562. assertTrue(nameField.isReadOnly());
  563. assertFalse(ageField.isReadOnly());
  564. binder.setReadOnly(false);
  565. assertFalse(nameField.isReadOnly());
  566. assertFalse(ageField.isReadOnly());
  567. }
  568. @Test
  569. public void setReadOnly_boundBinder() {
  570. binder.forField(nameField).bind(Person::getFirstName,
  571. Person::setFirstName);
  572. binder.forField(ageField)
  573. .withConverter(new StringToIntegerConverter(""))
  574. .bind(Person::getAge, Person::setAge);
  575. binder.setBean(new Person());
  576. binder.setReadOnly(true);
  577. assertTrue(nameField.isReadOnly());
  578. assertTrue(ageField.isReadOnly());
  579. binder.setReadOnly(false);
  580. assertFalse(nameField.isReadOnly());
  581. assertFalse(ageField.isReadOnly());
  582. }
  583. @Test
  584. public void setReadOnly_binderLoadedByReadBean() {
  585. binder.forField(nameField).bind(Person::getFirstName,
  586. Person::setFirstName);
  587. binder.forField(ageField)
  588. .withConverter(new StringToIntegerConverter(""))
  589. .bind(Person::getAge, Person::setAge);
  590. binder.readBean(new Person());
  591. binder.setReadOnly(true);
  592. assertTrue(nameField.isReadOnly());
  593. assertTrue(ageField.isReadOnly());
  594. binder.setReadOnly(false);
  595. assertFalse(nameField.isReadOnly());
  596. assertFalse(ageField.isReadOnly());
  597. }
  598. @Test
  599. public void setReadonlyShouldIgnoreBindingsWithNullSetter() {
  600. binder.bind(nameField, Person::getFirstName, null);
  601. binder.forField(ageField)
  602. .withConverter(new StringToIntegerConverter(""))
  603. .bind(Person::getAge, Person::setAge);
  604. binder.setReadOnly(true);
  605. assertTrue("Name field should be ignored but should be readonly",
  606. nameField.isReadOnly());
  607. assertTrue("Age field should be readonly", ageField.isReadOnly());
  608. binder.setReadOnly(false);
  609. assertTrue("Name field should be ignored and should remain readonly",
  610. nameField.isReadOnly());
  611. assertFalse("Age field should not be readonly", ageField.isReadOnly());
  612. nameField.setReadOnly(false);
  613. binder.setReadOnly(false);
  614. assertFalse("Name field should be ignored and remain not readonly",
  615. nameField.isReadOnly());
  616. assertFalse("Age field should not be readonly", ageField.isReadOnly());
  617. binder.setReadOnly(true);
  618. assertFalse("Name field should be ignored and remain not readonly",
  619. nameField.isReadOnly());
  620. assertTrue("Age field should be readonly", ageField.isReadOnly());
  621. }
  622. @Test
  623. public void isValidTest_bound_binder() {
  624. binder.forField(nameField)
  625. .withValidator(Validator.from(
  626. name -> !name.equals("fail field validation"), ""))
  627. .bind(Person::getFirstName, Person::setFirstName);
  628. binder.withValidator(Validator.from(
  629. person -> !person.getFirstName().equals("fail bean validation"),
  630. ""));
  631. binder.setBean(item);
  632. assertTrue(binder.isValid());
  633. nameField.setValue("fail field validation");
  634. assertFalse(binder.isValid());
  635. nameField.setValue("");
  636. assertTrue(binder.isValid());
  637. nameField.setValue("fail bean validation");
  638. assertFalse(binder.isValid());
  639. }
  640. @Test
  641. public void isValidTest_unbound_binder() {
  642. binder.forField(nameField)
  643. .withValidator(Validator.from(
  644. name -> !name.equals("fail field validation"), ""))
  645. .bind(Person::getFirstName, Person::setFirstName);
  646. assertTrue(binder.isValid());
  647. nameField.setValue("fail field validation");
  648. assertFalse(binder.isValid());
  649. nameField.setValue("");
  650. assertTrue(binder.isValid());
  651. }
  652. @Test(expected = IllegalStateException.class)
  653. public void isValidTest_unbound_binder_throws_with_bean_level_validation() {
  654. binder.forField(nameField).bind(Person::getFirstName,
  655. Person::setFirstName);
  656. binder.withValidator(Validator.from(
  657. person -> !person.getFirstName().equals("fail bean validation"),
  658. ""));
  659. binder.isValid();
  660. }
  661. @Test
  662. public void getFields_returnsFields() {
  663. assertEquals(0, binder.getFields().count());
  664. binder.forField(nameField).bind(Person::getFirstName,
  665. Person::setFirstName);
  666. assertStreamEquals(Stream.of(nameField), binder.getFields());
  667. binder.forField(ageField)
  668. .withConverter(new StringToIntegerConverter(""))
  669. .bind(Person::getAge, Person::setAge);
  670. assertStreamEquals(Stream.of(nameField, ageField), binder.getFields());
  671. }
  672. private void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
  673. assertArrayEquals(s1.toArray(), s2.toArray());
  674. }
  675. @Test
  676. public void multiple_calls_to_same_binding_builder() {
  677. String stringLength = "String length failure";
  678. String conversion = "Conversion failed";
  679. String ageLimit = "Age not in valid range";
  680. BindingValidationStatus validation;
  681. binder = new Binder<>(Person.class);
  682. BindingBuilder builder = binder.forField(ageField);
  683. builder.withValidator(new StringLengthValidator(stringLength, 0, 3));
  684. builder.withConverter(new StringToIntegerConverter(conversion));
  685. builder.withValidator(new IntegerRangeValidator(ageLimit, 3, 150));
  686. Binding<Person, ?> bind = builder.bind("age");
  687. binder.setBean(item);
  688. ageField.setValue("123123");
  689. validation = bind.validate();
  690. assertTrue(validation.isError());
  691. assertEquals(stringLength, validation.getMessage().get());
  692. ageField.setValue("age");
  693. validation = bind.validate();
  694. assertTrue(validation.isError());
  695. assertEquals(conversion, validation.getMessage().get());
  696. ageField.setValue("256");
  697. validation = bind.validate();
  698. assertTrue(validation.isError());
  699. assertEquals(ageLimit, validation.getMessage().get());
  700. ageField.setValue("30");
  701. validation = bind.validate();
  702. assertFalse(validation.isError());
  703. assertEquals(30, item.getAge());
  704. }
  705. @Test
  706. public void remove_field_binding() {
  707. binder.forField(ageField)
  708. .withConverter(new StringToIntegerConverter("Can't convert"))
  709. .bind(Person::getAge, Person::setAge);
  710. // Test that the binding does work
  711. assertTrue("Field not initially empty", ageField.isEmpty());
  712. binder.setBean(item);
  713. assertEquals("Binding did not work", String.valueOf(item.getAge()),
  714. ageField.getValue());
  715. binder.setBean(null);
  716. assertTrue("Field not cleared", ageField.isEmpty());
  717. // Remove the binding
  718. binder.removeBinding(ageField);
  719. // Test that it does not work anymore
  720. binder.setBean(item);
  721. assertNotEquals("Binding was not removed",
  722. String.valueOf(item.getAge()), ageField.getValue());
  723. }
  724. @Test
  725. public void remove_propertyname_binding() {
  726. // Use a bean aware binder
  727. Binder<Person> binder = new Binder<>(Person.class);
  728. binder.bind(nameField, "firstName");
  729. // Test that the binding does work
  730. assertTrue("Field not initially empty", nameField.isEmpty());
  731. binder.setBean(item);
  732. assertEquals("Binding did not work", item.getFirstName(),
  733. nameField.getValue());
  734. binder.setBean(null);
  735. assertTrue("Field not cleared", nameField.isEmpty());
  736. // Remove the binding
  737. binder.removeBinding("firstName");
  738. // Test that it does not work anymore
  739. binder.setBean(item);
  740. assertNotEquals("Binding was not removed", item.getFirstName(),
  741. nameField.getValue());
  742. }
  743. @Test
  744. public void remove_binding() {
  745. Binding<Person, Integer> binding = binder.forField(ageField)
  746. .withConverter(new StringToIntegerConverter("Can't convert"))
  747. .bind(Person::getAge, Person::setAge);
  748. // Test that the binding does work
  749. assertTrue("Field not initially empty", ageField.isEmpty());
  750. binder.setBean(item);
  751. assertEquals("Binding did not work", String.valueOf(item.getAge()),
  752. ageField.getValue());
  753. binder.setBean(null);
  754. assertTrue("Field not cleared", ageField.isEmpty());
  755. // Remove the binding
  756. binder.removeBinding(binding);
  757. // Test that it does not work anymore
  758. binder.setBean(item);
  759. assertNotEquals("Binding was not removed",
  760. String.valueOf(item.getAge()), ageField.getValue());
  761. }
  762. @Test
  763. public void remove_binding_fromFieldValueChangeListener() {
  764. // Add listener before bind to make sure it will be executed first.
  765. nameField.addValueChangeListener(e -> {
  766. if (e.getValue() == "REMOVE") {
  767. binder.removeBinding(nameField);
  768. }
  769. });
  770. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  771. binder.setBean(item);
  772. nameField.setValue("REMOVE");
  773. // Removed binding should not update bean.
  774. assertNotEquals("REMOVE", item.getFirstName());
  775. }
  776. @Test
  777. public void beanvalidation_two_fields_not_equal() {
  778. TextField lastNameField = new TextField();
  779. setBeanValidationFirstNameNotEqualsLastName(nameField, lastNameField);
  780. item.setLastName("Valid");
  781. binder.setBean(item);
  782. assertFalse("Should not have changes initially", binder.hasChanges());
  783. assertTrue("Should be ok initially", binder.validate().isOk());
  784. assertNotEquals("First name and last name are not same initially",
  785. item.getFirstName(), item.getLastName());
  786. nameField.setValue("Invalid");
  787. assertFalse("First name change not handled", binder.hasChanges());
  788. assertTrue(
  789. "Changing first name to something else than last name should be ok",
  790. binder.validate().isOk());
  791. lastNameField.setValue("Invalid");
  792. assertTrue("Last name should not be saved yet", binder.hasChanges());
  793. assertFalse("Binder validation should fail with pending illegal value",
  794. binder.validate().isOk());
  795. assertNotEquals("Illegal last name should not be stored to bean",
  796. item.getFirstName(), item.getLastName());
  797. nameField.setValue("Valid");
  798. assertFalse("With new first name both changes should be saved",
  799. binder.hasChanges());
  800. assertTrue("Everything should be ok for 'Valid Invalid'",
  801. binder.validate().isOk());
  802. assertNotEquals("First name and last name should never match.",
  803. item.getFirstName(), item.getLastName());
  804. }
  805. @Test
  806. public void beanvalidation_initially_broken_bean() {
  807. TextField lastNameField = new TextField();
  808. setBeanValidationFirstNameNotEqualsLastName(nameField, lastNameField);
  809. item.setLastName(item.getFirstName());
  810. binder.setBean(item);
  811. assertFalse(binder.isValid());
  812. assertFalse(binder.validate().isOk());
  813. }
  814. @Test(expected = IllegalStateException.class)
  815. public void beanvalidation_isValid_throws_with_readBean() {
  816. TextField lastNameField = new TextField();
  817. setBeanValidationFirstNameNotEqualsLastName(nameField, lastNameField);
  818. binder.readBean(item);
  819. assertTrue(binder.isValid());
  820. }
  821. @Test(expected = IllegalStateException.class)
  822. public void beanvalidation_validate_throws_with_readBean() {
  823. TextField lastNameField = new TextField();
  824. setBeanValidationFirstNameNotEqualsLastName(nameField, lastNameField);
  825. binder.readBean(item);
  826. assertTrue(binder.validate().isOk());
  827. }
  828. protected void setBeanValidationFirstNameNotEqualsLastName(
  829. TextField firstNameField, TextField lastNameField) {
  830. binder.bind(firstNameField, Person::getFirstName, Person::setFirstName);
  831. binder.forField(lastNameField)
  832. .withValidator(t -> !"foo".equals(t),
  833. "Last name cannot be 'foo'")
  834. .bind(Person::getLastName, Person::setLastName);
  835. binder.withValidator(p -> !p.getFirstName().equals(p.getLastName()),
  836. "First name and last name can't be the same");
  837. }
  838. static class MyBindingHandler implements BindingValidationStatusHandler {
  839. boolean expectingError = false;
  840. int callCount = 0;
  841. @Override
  842. public void statusChange(BindingValidationStatus<?> statusChange) {
  843. ++callCount;
  844. if (expectingError) {
  845. assertTrue("Expecting error", statusChange.isError());
  846. } else {
  847. assertFalse("Unexpected error", statusChange.isError());
  848. }
  849. }
  850. }
  851. @Test
  852. public void execute_binding_status_handler_from_binder_status_handler() {
  853. MyBindingHandler bindingHandler = new MyBindingHandler();
  854. binder.forField(nameField)
  855. .withValidator(t -> !t.isEmpty(), "No empty values.")
  856. .withValidationStatusHandler(bindingHandler)
  857. .bind(Person::getFirstName, Person::setFirstName);
  858. String ageError = "CONVERSIONERROR";
  859. binder.forField(ageField)
  860. .withConverter(new StringToIntegerConverter(ageError))
  861. .bind(Person::getAge, Person::setAge);
  862. binder.setValidationStatusHandler(
  863. status -> status.notifyBindingValidationStatusHandlers());
  864. String initialName = item.getFirstName();
  865. int initialAge = item.getAge();
  866. binder.setBean(item);
  867. // Test specific error handling.
  868. bindingHandler.expectingError = true;
  869. nameField.setValue("");
  870. // Test default error handling.
  871. ageField.setValue("foo");
  872. assertTrue("Component error does not contain error message",
  873. ageField.getComponentError().getFormattedHtmlMessage()
  874. .contains(ageError));
  875. // Restore values and test no errors.
  876. ageField.setValue(String.valueOf(initialAge));
  877. assertNull("There should be no component error",
  878. ageField.getComponentError());
  879. bindingHandler.expectingError = false;
  880. nameField.setValue(initialName);
  881. // Assert that the handler was called.
  882. assertEquals(
  883. "Unexpected callCount to binding validation status handler", 6,
  884. bindingHandler.callCount);
  885. }
  886. @Test
  887. public void removed_binding_not_updates_value() {
  888. Binding<Person, Integer> binding = binder.forField(ageField)
  889. .withConverter(new StringToIntegerConverter("Can't convert"))
  890. .bind(Person::getAge, Person::setAge);
  891. binder.setBean(item);
  892. String modifiedAge = String.valueOf(item.getAge() + 10);
  893. String ageBeforeUnbind = String.valueOf(item.getAge());
  894. binder.removeBinding(binding);
  895. ageField.setValue(modifiedAge);
  896. assertEquals("Binding still affects bean even after unbind",
  897. ageBeforeUnbind, String.valueOf(item.getAge()));
  898. }
  899. @Test
  900. public void info_validator_not_considered_error() {
  901. String infoMessage = "Young";
  902. binder.forField(ageField)
  903. .withConverter(new StringToIntegerConverter("Can't convert"))
  904. .withValidator(i -> i > 5, infoMessage, ErrorLevel.INFO)
  905. .bind(Person::getAge, Person::setAge);
  906. binder.setBean(item);
  907. ageField.setValue("3");
  908. assertEquals(infoMessage,
  909. ageField.getComponentError().getFormattedHtmlMessage());
  910. assertEquals(ErrorLevel.INFO,
  911. ageField.getComponentError().getErrorLevel());
  912. assertEquals(3, item.getAge());
  913. }
  914. @Test
  915. public void two_asRequired_fields_without_initial_values() {
  916. binder.forField(nameField).asRequired("Empty name").bind(p -> "",
  917. (p, s) -> {
  918. });
  919. binder.forField(ageField).asRequired("Empty age").bind(p -> "",
  920. (p, s) -> {
  921. });
  922. binder.setBean(item);
  923. assertNull("Initially there should be no errors",
  924. nameField.getComponentError());
  925. assertNull("Initially there should be no errors",
  926. ageField.getComponentError());
  927. nameField.setValue("Foo");
  928. assertNull("Name with a value should not be an error",
  929. nameField.getComponentError());
  930. assertNull(
  931. "Age field should not be in error, since it has not been modified.",
  932. ageField.getComponentError());
  933. nameField.setValue("");
  934. assertNotNull("Empty name should now be in error.",
  935. nameField.getComponentError());
  936. assertNull("Age field should still be ok.",
  937. ageField.getComponentError());
  938. }
  939. @Test
  940. public void refreshValueFromBean() {
  941. Binding<Person, String> binding = binder.bind(nameField,
  942. Person::getFirstName, Person::setFirstName);
  943. binder.readBean(item);
  944. assertEquals("Name should be read from the item", item.getFirstName(),
  945. nameField.getValue());
  946. nameField.setValue("foo");
  947. assertNotEquals("Name should be different from the item",
  948. item.getFirstName(), nameField.getValue());
  949. binding.read(item);
  950. assertEquals("Name should be read again from the item",
  951. item.getFirstName(), nameField.getValue());
  952. }
  953. @Test(expected = IllegalArgumentException.class)
  954. public void remove_binding_from_different_binder() {
  955. Binder<Person> anotherBinder = new Binder<>();
  956. Binding<Person, String> binding = anotherBinder.bind(nameField,
  957. Person::getFirstName, Person::setFirstName);
  958. binder.removeBinding(binding);
  959. }
  960. @Test(expected = IllegalStateException.class)
  961. public void bindWithNullSetterSetReadWrite() {
  962. Binding<Person, String> binding = binder.bind(nameField,
  963. Person::getFirstName, null);
  964. binding.setReadOnly(false);
  965. }
  966. @Test
  967. public void bindWithNullSetterShouldMarkFieldAsReadonly() {
  968. Binding<Person, String> nameBinding = binder.bind(nameField,
  969. Person::getFirstName, null);
  970. binder.forField(ageField)
  971. .withConverter(new StringToIntegerConverter(""))
  972. .bind(Person::getAge, Person::setAge);
  973. assertTrue("Name field should be readonly", nameField.isReadOnly());
  974. assertFalse("Age field should not be readonly", ageField.isReadOnly());
  975. assertTrue("Binding should be marked readonly",
  976. nameBinding.isReadOnly());
  977. }
  978. @Test
  979. public void setReadOnly_binding() {
  980. Binding<Person, String> binding = binder.bind(nameField,
  981. Person::getFirstName, Person::setFirstName);
  982. assertFalse("Binding should not be readonly", binding.isReadOnly());
  983. assertFalse("Name field should not be readonly",
  984. nameField.isReadOnly());
  985. binding.setReadOnly(true);
  986. assertTrue("Binding should be readonly", binding.isReadOnly());
  987. assertTrue("Name field should be readonly", nameField.isReadOnly());
  988. }
  989. @Test
  990. public void conversionWithLocaleBasedErrorMessage() {
  991. String fiError = "VIRHE";
  992. String otherError = "ERROR";
  993. binder.forField(ageField).withConverter(new StringToIntegerConverter(
  994. context -> context.getLocale().map(Locale::getLanguage)
  995. .orElse("en").equals("fi") ? fiError : otherError))
  996. .bind(Person::getAge, Person::setAge);
  997. binder.setBean(item);
  998. ageField.setValue("not a number");
  999. assertEquals(otherError,
  1000. ageField.getErrorMessage().getFormattedHtmlMessage());
  1001. ageField.setLocale(new Locale("fi"));
  1002. // Re-validate to get the error message with correct locale
  1003. binder.validate();
  1004. assertEquals(fiError,
  1005. ageField.getErrorMessage().getFormattedHtmlMessage());
  1006. }
  1007. @Test
  1008. public void valueChangeListenerOrder() {
  1009. AtomicBoolean beanSet = new AtomicBoolean();
  1010. nameField.addValueChangeListener(e -> {
  1011. if (!beanSet.get()) {
  1012. assertEquals("Value in bean updated earlier than expected",
  1013. e.getOldValue(), item.getFirstName());
  1014. }
  1015. });
  1016. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  1017. nameField.addValueChangeListener(e -> {
  1018. if (!beanSet.get()) {
  1019. assertEquals("Value in bean not updated when expected",
  1020. e.getValue(), item.getFirstName());
  1021. }
  1022. });
  1023. beanSet.set(true);
  1024. binder.setBean(item);
  1025. beanSet.set(false);
  1026. nameField.setValue("Foo");
  1027. }
  1028. @Test
  1029. public void nonSymetricValue_setBean_writtenToBean() {
  1030. binder.bind(nameField, Person::getLastName, Person::setLastName);
  1031. assertNull(item.getLastName());
  1032. binder.setBean(item);
  1033. assertEquals("", item.getLastName());
  1034. }
  1035. @Test
  1036. public void nonSymmetricValue_readBean_beanNotTouched() {
  1037. binder.bind(nameField, Person::getLastName, Person::setLastName);
  1038. binder.addValueChangeListener(
  1039. event -> fail("No value change event should be fired"));
  1040. assertNull(item.getLastName());
  1041. binder.readBean(item);
  1042. assertNull(item.getLastName());
  1043. }
  1044. @Test
  1045. public void symetricValue_setBean_beanNotUpdated() {
  1046. binder.bind(nameField, Person::getFirstName, Person::setFirstName);
  1047. binder.setBean(new Person() {
  1048. @Override
  1049. public String getFirstName() {
  1050. return "First";
  1051. }
  1052. @Override
  1053. public void setFirstName(String firstName) {
  1054. fail("Setter should not be called");
  1055. }
  1056. });
  1057. }
  1058. @Test
  1059. public void nullRejetingField_nullValue_wrappedExceptionMentionsNullRepresentation() {
  1060. TextField field = createNullAnd42RejectingFieldWithEmptyValue("");
  1061. Binder<AtomicReference<Integer>> binder = createIntegerConverterBinder(
  1062. field);
  1063. exceptionRule.expect(IllegalStateException.class);
  1064. exceptionRule.expectMessage("null representation");
  1065. exceptionRule.expectCause(CoreMatchers.isA(NullPointerException.class));
  1066. binder.readBean(new AtomicReference<>());
  1067. }
  1068. @Test
  1069. public void nullRejetingField_otherRejectedValue_originalExceptionIsThrown() {
  1070. TextField field = createNullAnd42RejectingFieldWithEmptyValue("");
  1071. Binder<AtomicReference<Integer>> binder = createIntegerConverterBinder(
  1072. field);
  1073. exceptionRule.expect(IllegalArgumentException.class);
  1074. exceptionRule.expectMessage("42");
  1075. binder.readBean(new AtomicReference<>(Integer.valueOf(42)));
  1076. }
  1077. @Test(expected = NullPointerException.class)
  1078. public void nullAcceptingField_nullValue_originalExceptionIsThrown() {
  1079. /*
  1080. * Edge case with a field that throws for null but has null as the empty
  1081. * value. This is most likely the case if the field doesn't explicitly
  1082. * reject null values but is instead somehow broken so that any value is
  1083. * rejected.
  1084. */
  1085. TextField field = createNullAnd42RejectingFieldWithEmptyValue(null);
  1086. Binder<AtomicReference<Integer>> binder = createIntegerConverterBinder(
  1087. field);
  1088. binder.readBean(new AtomicReference<>(null));
  1089. }
  1090. private TextField createNullAnd42RejectingFieldWithEmptyValue(
  1091. String emptyValue) {
  1092. return new TextField() {
  1093. @Override
  1094. public void setValue(String value) {
  1095. if (value == null) {
  1096. throw new NullPointerException("Null value");
  1097. } else if ("42".equals(value)) {
  1098. throw new IllegalArgumentException("42 is not allowed");
  1099. }
  1100. super.setValue(value);
  1101. }
  1102. @Override
  1103. public String getEmptyValue() {
  1104. return emptyValue;
  1105. }
  1106. };
  1107. }
  1108. private Binder<AtomicReference<Integer>> createIntegerConverterBinder(
  1109. TextField field) {
  1110. Binder<AtomicReference<Integer>> binder = new Binder<>();
  1111. binder.forField(field)
  1112. .withConverter(new StringToIntegerConverter("Must have number"))
  1113. .bind(AtomicReference::get, AtomicReference::set);
  1114. return binder;
  1115. }
  1116. }