下面列出了javax.validation.ConstraintViolation#getLeafBean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String createValidationMessage(Set<ConstraintViolation<?>> constraintViolations) {
if (constraintViolations.isEmpty()) {
return "No Constraint Validations!";
}
StringBuilder builder = new StringBuilder("Constraint Validations: ");
for (ConstraintViolation<?> violation : constraintViolations) {
if (builder.length() > 0) {
builder.append(", ");
}
Object leafBean = violation.getLeafBean();
if (leafBean instanceof HasMetadata) {
HasMetadata hasMetadata = (HasMetadata) leafBean;
ObjectMeta metadata = hasMetadata.getMetadata();
if (metadata != null) {
leafBean = "" + hasMetadata.getKind() + ": " + metadata;
}
}
builder.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean);
}
return builder.toString();
}
public static <T> void validate(T item, Validator v) {
if (v == null) {
v = getValidator();
}
if (v == null) {
return;
}
Set<ConstraintViolation<T>> violations = v.validate(item);
if (!violations.isEmpty()) {
StringBuilder sb = new StringBuilder("Constraint Validations: ");
boolean first = true;
for (ConstraintViolation violation : violations) {
if (first) {
first = false;
} else {
sb.append(", ");
}
Object leafBean = violation.getLeafBean();
sb.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean);
}
throw new ConstraintViolationException(sb.toString(), violations);
}
}
/**
* Take a stab at fixing validation problems ?
*
* @param object
*/
private void validate(Object object) {
Set<ConstraintViolation<Object>> viols = validator.validate(object);
for (ConstraintViolation<Object> constraintViolation : viols) {
if (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {
Object o = constraintViolation.getLeafBean();
Iterator<Node> iterator = constraintViolation.getPropertyPath().iterator();
String propertyName = null;
while (iterator.hasNext()) {
propertyName = iterator.next().getName();
}
if (propertyName != null) {
try {
PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);
descriptor.getWriteMethod().invoke(o, new Object[] { null });
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
@AroundInvoke
public Object validateMethodInvocation(InvocationContext invocationContext) throws Exception {
Validator validator = validatorFactory.getValidator();
if (validator == null) {
return invocationContext.proceed();
}
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(invocationContext.getTarget());
for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
Path propertyPath = constraintViolation.getPropertyPath();
Path.Node lastPathNode = null;
for (Path.Node pathNode : propertyPath) {
lastPathNode = pathNode;
}
if ((lastPathNode != null) && (lastPathNode.getKind() == ElementKind.PROPERTY)) {
Object leafBean = constraintViolation.getLeafBean();
Class<?> leafBeanClass = leafBean.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(leafBean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyDescriptorName = propertyDescriptor.getName();
if (propertyDescriptorName.equals("targetClass")) {
Method readMethod = propertyDescriptor.getReadMethod();
leafBeanClass = (Class<?>) readMethod.invoke(leafBean);
}
}
Field leafBeanField = leafBeanClass.getDeclaredField(lastPathNode.getName());
String paramName = null;
Annotation[] annotations = leafBeanField.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof CookieParam) {
CookieParam cookieParam = (CookieParam) annotation;
paramName = cookieParam.value();
break;
}
else if (annotation instanceof FormParam) {
FormParam formParam = (FormParam) annotation;
paramName = formParam.value();
break;
}
else if (annotation instanceof HeaderParam) {
HeaderParam headerParam = (HeaderParam) annotation;
paramName = headerParam.value();
break;
}
else if (annotation instanceof QueryParam) {
QueryParam queryParam = (QueryParam) annotation;
paramName = queryParam.value();
}
}
String interpolatedMessage = constraintViolation.getMessage();
if (messageInterpolator != null) {
interpolatedMessage = messageInterpolator.interpolate(constraintViolation.getMessageTemplate(),
new MessageInterpolatorContextImpl(constraintViolation), mvcContext.getLocale());
}
mutableBindingResult.addValidationError(new ValidationErrorImpl(paramName, interpolatedMessage,
constraintViolation));
}
}
return invocationContext.proceed();
}
/**
* BeanValidationの検証結果をSheet用のエラーに変換する
* @param violations BeanValidationの検証結果
* @param errors シートのエラー
*/
protected void processConstraintViolation(final Set<ConstraintViolation<Object>> violations,
final SheetBindingErrors<?> errors) {
for(ConstraintViolation<Object> violation : violations) {
final String fieldName = violation.getPropertyPath().toString();
final Optional<FieldError> fieldError = errors.getFirstFieldError(fieldName);
if(fieldError.isPresent() && fieldError.get().isConversionFailure()) {
// 型変換エラーが既存のエラーにある場合は、処理をスキップする。
continue;
}
final ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
/*
* エラーメッセージのコードは、後から再変換できるよう、BeanValidationの形式のエラーコードも付けておく。
*/
final String[] errorCodes = new String[]{
cd.getAnnotation().annotationType().getSimpleName(),
cd.getAnnotation().annotationType().getCanonicalName(),
cd.getAnnotation().annotationType().getCanonicalName() + ".message"
};
final Map<String, Object> errorVars = createVariableForConstraint(cd);
final String nestedPath = errors.buildFieldPath(fieldName);
if(Utils.isEmpty(nestedPath)) {
// オブジェクトエラーの場合
errors.createGlobalError(errorCodes)
.variables(errorVars)
.defaultMessage(violation.getMessage())
.buildAndAddError();
} else {
// フィールドエラーの場合
// 親のオブジェクトから、セルの座標を取得する
final Object parentObj = violation.getLeafBean();
final Path path = violation.getPropertyPath();
Optional<CellPosition> cellAddress = Optional.empty();
Optional<String> label = Optional.empty();
if(path instanceof PathImpl) {
final PathImpl pathImpl = (PathImpl) path;
cellAddress = new PositionGetterFactory().create(parentObj.getClass(), pathImpl.getLeafNode().getName())
.map(getter -> getter.get(parentObj)).orElse(Optional.empty());
label = new LabelGetterFactory().create(parentObj.getClass(), pathImpl.getLeafNode().getName())
.map(getter -> getter.get(parentObj)).orElse(Optional.empty());
}
// フィールドフォーマッタ
Class<?> fieldType = errors.getFieldType(nestedPath);
if(fieldType != null) {
FieldFormatter<?> fieldFormatter = errors.findFieldFormatter(nestedPath, fieldType);
if(fieldFormatter != null) {
errorVars.putIfAbsent("fieldFormatter", fieldFormatter);
}
}
// 実際の値を取得する
errorVars.putIfAbsent("validatedValue", violation.getInvalidValue());
errors.createFieldError(fieldName, errorCodes)
.variables(errorVars)
.address(cellAddress)
.label(label)
.defaultMessage(violation.getMessage())
.buildAndAddError();
}
}
}
/**
* Extract the rejected value behind the given constraint violation,
* for exposure through the Spring errors representation.
* @param field the field that caused the binding error
* @param violation the corresponding JSR-303 ConstraintViolation
* @param bindingResult a Spring BindingResult for the backing object
* which contains the current field's value
* @return the invalid value to expose as part of the field error
* @since 4.2
* @see javax.validation.ConstraintViolation#getInvalidValue()
* @see org.springframework.validation.FieldError#getRejectedValue()
*/
@Nullable
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
Object invalidValue = violation.getInvalidValue();
if (!"".equals(field) && !field.contains("[]") &&
(invalidValue == violation.getLeafBean() || field.contains("[") || field.contains("."))) {
// Possibly a bean constraint with property path: retrieve the actual property value.
// However, explicitly avoid this for "address[]" style paths that we can't handle.
invalidValue = bindingResult.getRawFieldValue(field);
}
return invalidValue;
}
/**
* Extract the rejected value behind the given constraint violation,
* for exposure through the Spring errors representation.
* @param field the field that caused the binding error
* @param violation the corresponding JSR-303 ConstraintViolation
* @param bindingResult a Spring BindingResult for the backing object
* which contains the current field's value
* @return the invalid value to expose as part of the field error
* @since 4.2
* @see javax.validation.ConstraintViolation#getInvalidValue()
* @see org.springframework.validation.FieldError#getRejectedValue()
*/
@Nullable
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
Object invalidValue = violation.getInvalidValue();
if (!"".equals(field) && !field.contains("[]") &&
(invalidValue == violation.getLeafBean() || field.contains("[") || field.contains("."))) {
// Possibly a bean constraint with property path: retrieve the actual property value.
// However, explicitly avoid this for "address[]" style paths that we can't handle.
invalidValue = bindingResult.getRawFieldValue(field);
}
return invalidValue;
}
/**
* Extract the rejected value behind the given constraint violation,
* for exposure through the Spring errors representation.
* @param field the field that caused the binding error
* @param violation the corresponding JSR-303 ConstraintViolation
* @param bindingResult a Spring BindingResult for the backing object
* which contains the current field's value
* @return the invalid value to expose as part of the field error
* @since 4.2
* @see javax.validation.ConstraintViolation#getInvalidValue()
* @see org.springframework.validation.FieldError#getRejectedValue()
*/
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
Object invalidValue = violation.getInvalidValue();
if (!"".equals(field) && (invalidValue == violation.getLeafBean() ||
(!field.contains("[]") && (field.contains("[") || field.contains("."))))) {
// Possibly a bean constraint with property path: retrieve the actual property value.
// However, explicitly avoid this for "address[]" style paths that we can't handle.
invalidValue = bindingResult.getRawFieldValue(field);
}
return invalidValue;
}
/**
* Extract the rejected value behind the given constraint violation,
* for exposure through the Spring errors representation.
* @param field the field that caused the binding error
* @param violation the corresponding JSR-303 ConstraintViolation
* @param bindingResult a Spring BindingResult for the backing object
* which contains the current field's value
* @return the invalid value to expose as part of the field error
* @since 4.2
* @see javax.validation.ConstraintViolation#getInvalidValue()
* @see org.springframework.validation.FieldError#getRejectedValue()
*/
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
Object invalidValue = violation.getInvalidValue();
if (!"".equals(field) && (invalidValue == violation.getLeafBean() ||
(field.contains(".") && !field.contains("[]")))) {
// Possibly a bean constraint with property path: retrieve the actual property value.
// However, explicitly avoid this for "address[]" style paths that we can't handle.
invalidValue = bindingResult.getRawFieldValue(field);
}
return invalidValue;
}