WhitespaceConstraint extends AbstractStringConstraint { @Override public Violation typedErrorFor(String value) { int len = value.length(); if (len == 0) return null; if (checkLeading) { char ch = value.charAt(0); if (Character.isWhitespace(ch)) { return new Violation(this, "Illegal starting whitespace: " + ch); } } if (checkTrailing) { char ch = value.charAt(len-1); if (Character.isWhitespace(ch)) { return new Violation(this, "Illegal ending whitespace: " + ch); } } return null; } WhitespaceConstraint(String theId, boolean nullAllowed, Boolean noLeadingFlag, Boolean noTrailingFlag); @Override Violation typedErrorFor(String value); @Override Map<Parameter<?>, Object> parameters(); @Override String typeTag(); static final String TypeTag; static final String Docs; static final BooleanParameter NO_LEADING; static final BooleanParameter NO_TRAILING; static final ConstraintBuilder<String> Builder; }
@Test public void testTypedErrorFor() { Map<String,String> paramsByKey = asParams(WhitespaceConstraint.NO_LEADING, true); Collection<Constraint<?>> vcs = WhitespaceConstraint.Builder.constraintsFrom(Schema.Type.STRING, false, paramsByKey); assertNotNull(vcs); ValueConstraint<?> vc =(ValueConstraint<?>) vcs.iterator().next(); Violation violation = vc.errorFor("hello"); assertNull(violation); violation = vc.errorFor("hello\n"); assertNull(violation); violation = vc.errorFor("\thello"); assertNotNull(violation); paramsByKey = asParams(WhitespaceConstraint.NO_TRAILING, true); vcs = WhitespaceConstraint.Builder.constraintsFrom(Schema.Type.STRING, false, paramsByKey); assertNotNull(vcs); vc = (ValueConstraint<?>)vcs.iterator().next(); violation = vc.errorFor("hello"); assertNull(violation); violation = vc.errorFor("\thello"); assertNull(violation); violation = vc.errorFor("hello\n"); assertNotNull(violation); }