CollectionSizeConstraint extends AbstractCollectionConstraint { @Override public Violation typedErrorFor(Object[] value) { int len = value == null ? 0 : value.length; if (minSize != null && minSize > len) return new Violation(this, "too few items, need at least " + minSize); if (maxSize != null && maxSize < len) return new Violation(this, "too many items, limit is " + maxSize); return null; } CollectionSizeConstraint(String theId, boolean nullAllowed, Integer theMin, Integer theMax); @Override String typeTag(); @Override Map<Parameter<?>, Object> parameters(); @Override Violation typedErrorFor(Object[] value); @Override String toString(); static final String TypeTag; static final String Docs; static final IntegerParameter MIN_ITEMS; static final IntegerParameter MAX_ITEMS; static final ConstraintBuilder<Object[]> Builder; }
@Test public void typedErrorFor() { Map<String,String> paramsByKey = asParams( CollectionSizeConstraint.MIN_ITEMS, 3, CollectionSizeConstraint.MAX_ITEMS, 5, StringLengthConstraint.MIN_LENGTH, 43); Collection<Constraint<?>> vcs = CollectionSizeConstraint.Builder.constraintsFrom(Schema.Type.ARRAY, false, paramsByKey); ValueConstraint<?> vc = (ValueConstraint<?>)vcs.iterator().next(); Violation v = vc.errorFor(Arrays.asList("1", "2", "3", "4")); Assert.assertNull(v); v = vc.errorFor(Arrays.asList("1", "2")); Assert.assertNotNull(v); v = vc.errorFor(Arrays.asList("1", "2", "3", "4", "5", "6")); Assert.assertNotNull(v); }