CidrValidator implements ConstraintValidator<Cidr, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return false; } int bitMask = 0; boolean validIpAddress = false; String[] cidr = value.split("/"); if (cidr.length == 2 && cidr[1].matches("\\d+")) { validIpAddress = InetAddressValidator.getInstance().isValid(cidr[0]); bitMask = Integer.parseInt(cidr[1]); } if (!validIpAddress || !(bitMask > 0 && bitMask <= CIDR_BIT_MASK_MAX_VALUE)) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(String.format("%s is invalid CIDR", value)) .addConstraintViolation(); return false; } return true; } @Inject  CidrValidator(); @Override void initialize(Cidr constraintAnnotation); @Override boolean isValid(String value, ConstraintValidatorContext context); static final int CIDR_BIT_MASK_MAX_VALUE; }
@Test public void testNull() { Assert.assertFalse(validator.isValid(null, context)); }
@Test public void testValidCidr() { Assert.assertTrue(validator.isValid("192.168.0.1/1", context)); Assert.assertTrue(validator.isValid("192.168.0.1/24", context)); Assert.assertTrue(validator.isValid("192.168.0.1/31", context)); }
@Test public void testInvalidCidr() { Assert.assertFalse(validator.isValid("192.168.0.1", context)); Assert.assertFalse(validator.isValid("192.168.0.1/", context)); Assert.assertFalse(validator.isValid("", context)); Assert.assertFalse(validator.isValid(" ", context)); Assert.assertFalse(validator.isValid("/", context)); Assert.assertFalse(validator.isValid("/24", context)); Assert.assertFalse(validator.isValid("192.168.0.1/24/18", context)); Assert.assertFalse(validator.isValid("192.168.0.500/24", context)); Assert.assertFalse(validator.isValid("192.168.0.1/0", context)); Assert.assertFalse(validator.isValid("192.168.0.1/a", context)); Assert.assertFalse(validator.isValid("192.168.0.a/24", context)); Assert.assertFalse(validator.isValid("192.168.0.1/32", context)); }