Skip to content

Instantly share code, notes, and snippets.

@emmanuelbernard
Created April 9, 2015 20:06
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 emmanuelbernard/0ef40065842843de7f3d to your computer and use it in GitHub Desktop.
Save emmanuelbernard/0ef40065842843de7f3d to your computer and use it in GitHub Desktop.
Parent Constraint Bean Validation
package org.hibernate.validator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.internal.constraintvalidators.bv.NotNullValidator;
/**
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
public class Person {
@NotEmptyOnParent(property="nomDeFamille")
@Valid
Person pere;
Person mere;
String nomDeFamille;
@Documented
@Constraint(validatedBy = { NotEmptyOnParentValidator.class})
@NotNull
@Size
@Target({ ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface NotEmptyOnParent {
String message() default "{org.hibernate.validator.constraints.EAN.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String property();
}
class NotEmptyOnParentValidator implements ConstraintValidator<Person.NotEmptyOnParent,Person> {
private Method propertyMethod;
@Override
public void initialize(NotEmptyOnParent constraintAnnotation) {
try {
propertyMethod = Person.class.getMethod( constraintAnnotation.property() );
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@Override
public boolean isValid(Person value, ConstraintValidatorContext context) {
try {
boolean b = propertyMethod.invoke( value ) == null;
if ( b == false) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate( context.getDefaultConstraintMessageTemplate() )
.addPropertyNode( propertyMethod.getName() )
.addConstraintViolation();
return false;
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment