package com.smitchelus.validator.webwork; import java.util.Collection; import org.hibernate.validator.ClassValidator; import org.hibernate.validator.InvalidValue; import com.opensymphony.xwork.ActionContext; import com.opensymphony.xwork.util.OgnlValueStack; import com.opensymphony.xwork.validator.ValidationException; import com.opensymphony.xwork.validator.validators.FieldValidatorSupport; public class HibernateValidator extends FieldValidatorSupport { private boolean appendPrefix = true; /** * Sets whether the field name of this field validator should be prepended to the field name of * the visited field to determine the full field name when an error occurs. The default is * true. */ public void setAppendPrefix(boolean appendPrefix) { this.appendPrefix = appendPrefix; } /** * Flags whether the field name of this field validator should be prepended to the field name of * the visited field to determine the full field name when an error occurs. The default is * true. */ public boolean isAppendPrefix() { return appendPrefix; } public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); Object value = this.getFieldValue(fieldName, object); if (value == null) { log.warn("The visited object is null, VisitorValidator will not be able to handle validation properly. Please make sure the visited object is not null for VisitorValidator to function properly"); return; } OgnlValueStack stack = ActionContext.getContext().getValueStack(); stack.push(object); if (value instanceof Collection) { Collection coll = (Collection) value; Object[] array = coll.toArray(); validateArrayElements(array, fieldName); } else if (value instanceof Object[]) { Object[] array = (Object[]) value; validateArrayElements(array, fieldName); } else { validateObject(fieldName, value); } stack.pop(); } private void validateArrayElements(Object[] array, String fieldName) throws ValidationException { for (int i = 0; i < array.length; i++) { Object o = array[i]; validateObject(fieldName + "[" + i + "]", o); } } @SuppressWarnings("unchecked") private void validateObject(String fieldName, Object o) throws ValidationException { ClassValidator classValidator = new ClassValidator(o.getClass()); InvalidValue[] validationMessages = classValidator.getInvalidValues(o); if (validationMessages.length > 0) { String propertyPrefix = ""; if (appendPrefix) propertyPrefix = fieldName + "."; for (int i = 0; i < validationMessages.length; i++) { InvalidValue message = validationMessages[i]; System.out.println(message.getPropertyPath() + ": " + message.getPropertyName() + ": " + message.getMessage()); this.getValidatorContext().addFieldError(propertyPrefix + message.getPropertyName(), message.getMessage()); } } } }