Bean Validation: How can I manually create a ConstraintViolation?

odedia picture odedia · Apr 8, 2014 · Viewed 17.7k times · Source

I have a specific scenario where I can only check for violation conditions manually, at a later point in the flow.

What I want to do is throw a ConstraintViolationException, and provide a "real" ConstraintViolation object to it (when I catch the exception up the stack, I use the #{validatedValue} and violation.getPropertyPath() parameters).

How can I create a ConstraintViolation myself without having the framework do it for me via annotations (I use Hibernate Validator)?

Code example:

List<String> columnsListForSorting = new ArrayList<String>(service.getColumnsList(domain));
Collections.sort(columnsListForSorting);

String firstFieldToSortBy = this.getTranslatedFieldName(domain.getClass().getCanonicalName(), sortingInfo.getSortedColumn());
if (!columnsListForSorting.contains(firstFieldToSortBy)){
    throw new ConstraintViolationException(<what here?...>);
}

Thanks.

Answer

Stefan Haberl picture Stefan Haberl · Feb 25, 2015

One more reason why I don't like Hibernate Validator that particular. They make it really hard to create a simple violation programmatically, when it should be dead simple. I do have test code where I need to create a violation to feed to my mocked subsystem.

Anyway, short of rolling your own implementation of a violation contraint - here is what I do to create a violation for a field:

private static final String MESSAGE_TEMPLATE = "{messageTemplate}";
private static final String MESSAGE = "message";

public static <T, A extends Annotation> ConstraintViolation<T> forField(
  final T rootBean, 
  final Class<T> clazz,
  final Class<A> annotationClazz,
  final Object leafBean, 
  final String field, 
  final Object offendingValue) {

  ConstraintViolation<T> violation = null;
  try {
    Field member = clazz.getDeclaredField(field);
    A annotation = member.getAnnotation(annotationClazz);
    ConstraintDescriptor<A> descriptor = new ConstraintDescriptorImpl<>(
      new ConstraintHelper(), 
      member, 
      annotation, 
      ElementType.FIELD);
    Path p = PathImpl.createPathFromString(field);
    violation = ConstraintViolationImpl.forBeanValidation(
      MESSAGE_TEMPLATE, 
      MESSAGE, 
      clazz, 
      rootBean, 
      leafBean,
      offendingValue, 
      p, 
      descriptor, 
      ElementType.FIELD);
  } catch (NoSuchFieldException ignore) {}
  return violation;

}

HTH