下面列出了怎么用org.hibernate.validator.internal.engine.path.PathImpl的API类实例代码及写法,或者点击链接到github查看源代码。
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ConstraintViolationException.class)
public Result handleValidationException(ConstraintViolationException e) {
log.error(ErrorStatus.ILLEGAL_DATA.getMessage() + ":" + e.getMessage());
List<Map<String, Object>> fields = new ArrayList<>();
for (ConstraintViolation<?> cv : e.getConstraintViolations()) {
String fieldName = ((PathImpl) cv.getPropertyPath()).getLeafNode().asString();
String message = cv.getMessage();
Map<String, Object> field = new HashMap<>();
field.put("field", fieldName);
field.put("message", message);
fields.add(field);
}
return failure(ErrorStatus.ILLEGAL_DATA, fields);
}
@Override
public Response toResponse(ValidationException e) {
if (e instanceof ConstraintViolationException) {
ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
return buildResponse(
"[" +
constraintViolationException
.getConstraintViolations()
.stream()
.map(constraint -> {
Object value = constraint.getInvalidValue() == null ? ((PathImpl) constraint.getPropertyPath()).getLeafNode().asString() : constraint.getInvalidValue();
return value + ": " + constraint.getMessage();
})
.collect(Collectors.joining(","))
+
"]");
} else {
return buildResponse(e.getMessage());
}
}
@ExceptionHandler(ConstraintViolationException.class)
public BaseResponse handleError(ConstraintViolationException e) {
logger.warn("Constraint Violation", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
String message = String.format("%s:%s", path, violation.getMessage());
return BaseResponse
.builder()
.code(ResultCode.PARAM_VALID_ERROR)
.message(message)
.build();
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
logger.error(e.getMessage(), e);
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
e.printStackTrace();
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
e.printStackTrace();
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
/**
* Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails.
*
* @param cv the ConstraintViolation
*/
private void addValidationError(ConstraintViolation<?> cv) {
this.addValidationError(
cv.getRootBeanClass().getSimpleName(),
((PathImpl) cv.getPropertyPath()).getLeafNode().asString(),
cv.getInvalidValue(),
cv.getMessage());
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
logger.error(e.getMessage(), e);
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
/**
* Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails.
*
* @param cv the ConstraintViolation
*/
private void addValidationError(ConstraintViolation<?> cv) {
this.addValidationError(
cv.getRootBeanClass().getSimpleName(),
((PathImpl) cv.getPropertyPath()).getLeafNode().asString(),
cv.getInvalidValue(),
cv.getMessage());
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R handleError(ConstraintViolationException e) {
log.warn("参数验证失败", e.getMessage());
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
String message = String.format("%s:%s", path, violation.getMessage());
return R.fail(ResultCode.PARAM_VALID_ERROR, message);
}
/**
* Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails.
*
* @param cv the ConstraintViolation
*/
private void addValidationError(ConstraintViolation<?> cv) {
this.addValidationError(
cv.getRootBeanClass().getSimpleName(),
((PathImpl) cv.getPropertyPath()).getLeafNode().asString(),
cv.getInvalidValue(),
cv.getMessage());
}
/**
* Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails.
*
* @param cv the ConstraintViolation
*/
private void addValidationError(ConstraintViolation<?> cv) {
this.addValidationError(
cv.getRootBeanClass().getSimpleName(),
((PathImpl) cv.getPropertyPath()).getLeafNode().asString(),
cv.getInvalidValue(),
cv.getMessage());
}
ConstraintViolationBuilder getConstraintViolationBuilder() {
return new ConstraintValidatorContextImpl(null,
PathImpl.createRootPath(),
new DummyConstraintDescriptor(),
null
).buildConstraintViolationWithTemplate("dummytemplate");
}
@Before
public void setUp() {
underTest = new UpdateStackRequestValidator();
constraintValidatorContext = new ConstraintValidatorContextImpl(
null,
PathImpl.createPathFromString("status"),
new DummyConstraintDescriptor(),
null
);
}
@Override
public Path getPropertyPath() {
return PathImpl.createPathFromString(propertyPath);
}
private ConstraintValidatorContext createContext() {
return new ConstraintValidatorContextImpl(Collections.emptyList(), DefaultClockProvider.INSTANCE, PathImpl.createPathFromString("target"), mock(ConstraintDescriptor.class), null);
}
/**
* 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();
}
}
}
/**
* Utility method for adding error of ConstraintViolation. Usually when a @Validated
* validation fails.
* @param cv the ConstraintViolation
*/
private void addValidationError(ConstraintViolation<?> cv) {
this.addValidationError(cv.getRootBeanClass().getSimpleName(),
((PathImpl) cv.getPropertyPath()).getLeafNode().asString(), cv.getInvalidValue(), cv.getMessage());
}