CheckNoDuplicateDebtorsValidator implements ConstraintValidator<CheckNoDuplicateDebtors, List<Share>> { @Override public boolean isValid(List<Share> shares, ConstraintValidatorContext constraintValidatorContext) { if (shares == null) { constraintValidatorContext.disableDefaultConstraintViolation(); constraintValidatorContext.buildConstraintViolationWithTemplate("must not be null").addConstraintViolation(); return false; } final List<Person> allDebtors = shares.stream().map(Share::getDebtor).collect(toList()); final HashSet<Person> visitedDebtors = new HashSet<>(); for (int i = 0; i < allDebtors.size(); i++) { Person debtor = allDebtors.get(i); if (visitedDebtors.contains(debtor)) { constraintValidatorContext .buildConstraintViolationWithTemplate("Debtors must only occur once across all shares.") .addPropertyNode("debtor") .inIterable().atIndex(i) .addConstraintViolation(); } visitedDebtors.add(debtor); } return visitedDebtors.size() == allDebtors.size(); }  @Override void initialize(CheckNoDuplicateDebtors checkNoDuplicateDebtors); @Override boolean isValid(List<Share> shares, ConstraintValidatorContext constraintValidatorContext);  }
@Test public void shouldPassIfNoDuplicateNames() throws Exception { final List<Share> sharesWithoutDuplicateDebtors = Arrays.asList(randomShare(thomas), randomShare(matthias)); final boolean result = sut.isValid(sharesWithoutDuplicateDebtors, validatorContextMock); assertTrue(result); }
@Test public void shouldFailIfDuplicateNames() throws Exception { final List<Share> sharesWithoutDuplicateDebtors = Arrays.asList(randomShare(matthias), randomShare(matthias)); final boolean result = sut.isValid(sharesWithoutDuplicateDebtors, validatorContextMock); assertFalse(result); }