MapKeyConstraint extends AbstractMapConstraint { public static ConstraintBuilder<Object[]> builderWith(final ConstraintFactory<?> cstFactory) { return new BasicConstraintBuilder<Object[]>(TypeTag, MapKeyConstraint.class, Docs, KEY_TYPE, CONSTRAINT_ID) { public Collection<Constraint<?>> constraintsFrom(Type type, boolean nullsAllowed, Map<String, String> values) { ConstraintBuilder<?> cb = builderFor(cstFactory, values, KEY_TYPE); if (cb == null) return null; Collection<Constraint<?>> constraints = cb.constraintsFrom(null, nullsAllowed, values); if (constraints == null || constraints.isEmpty()) return null; return withExtras(new MapKeyConstraint("", nullsAllowed, (ValueConstraint<?>)constraints.iterator().next()), values); } }; } MapKeyConstraint(String theId, boolean nullAllowed, ValueConstraint<?> theConstraint); static ConstraintBuilder<Object[]> builderWith(final ConstraintFactory<?> cstFactory); @Override String typeTag(); static final String TypeTag; static final String Docs; static final StringParameter KEY_TYPE; }
@Test public void testMapKeyConstraintBuilder() { Map<String,String> paramsByKey = asParams( MapKeyConstraint.KEY_TYPE, "string", AbstractMapConstraint.CONSTRAINT_ID, StringLengthConstraint.TypeTag, StringLengthConstraint.MIN_LENGTH, 3); Collection<Constraint<?>> vcs = MapKeyConstraint.builderWith(AvroConfiguration.ConstraintFactory).constraintsFrom(Type.MAP, false, paramsByKey); assertNotNull(vcs); assertEquals(vcs.size(), 1); paramsByKey = asParams( MapKeyConstraint.KEY_TYPE, "string", StringLengthConstraint.MIN_LENGTH, 3); vcs = MapKeyConstraint.builderWith(AvroConfiguration.ConstraintFactory).constraintsFrom(Type.MAP, false, paramsByKey); assertNull(vcs); }
@Test public void typedErrorFor() { Map<String,String> paramsByKey = asParams( MapKeyConstraint.KEY_TYPE, "string", AbstractMapConstraint.CONSTRAINT_ID, StringLengthConstraint.TypeTag, StringLengthConstraint.MIN_LENGTH, 3); Collection<Constraint<?>> vcs = MapKeyConstraint.builderWith(AvroConfiguration.ConstraintFactory).constraintsFrom(Type.MAP, false, paramsByKey); assertNotNull(vcs); assertEquals(vcs.size(), 1); ValueConstraint<?> vc = (ValueConstraint<?>)vcs.iterator().next(); Person person = PeopleBuilder.createPeople(1).iterator().next(); Violation violation = vc.errorFor(person.getPassports()); assertNull(violation); }