Skip to content

Instantly share code, notes, and snippets.

@krisskross
Created May 6, 2012 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisskross/2622923 to your computer and use it in GitHub Desktop.
Save krisskross/2622923 to your computer and use it in GitHub Desktop.
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Config(desc = "A binary tree")
@BinaryTreeConstraint
public class BinaryTree {
@Id(desc = "id of current node")
private String id;
@Config(desc = "value of current node")
@NotNull
@Min(1)
private Integer value;
@Config(desc = "left child")
private BinaryTree left;
@Config(desc = "right child")
private BinaryTree right;
public int getId() { return new Integer(value).intValue(); }
public int getValue() { return value.intValue(); }
public BinaryTree getLeft() { return left; }
public BinaryTree getRight() { return right; }
public String toString() { return id + "=" + value; }
}
public class BinaryTreeValidator implements ConstraintValidator<BinaryTreeConstraint, BinaryTree> {
@Override
public boolean isValid(BinaryTree n, ConstraintValidatorContext c) {
if (n.getLeft() != null && n.getValue() < n.getLeft().getValue()) {
String msg = n.getLeft() + " must be to right of " + n;
c.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
return false;
}
if (n.getRight() != null && n.getValue() > n.getRight().getValue()) {
String msg = n.getRight() + " must be to left of " + n;
c.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
return false;
}
return true;
}
@Override
public void initialize(BinaryTreeConstraint constraintAnnotation) {
}
}
@Target({ TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BinaryTreeValidator.class)
public @interface BinaryTreeConstraint {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment