org.hibernate.validator.internal.engine.path.PathImpl Java Examples

The following examples show how to use org.hibernate.validator.internal.engine.path.PathImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GlobalExceptionHandler.java    From cola-cloud with MIT License 7 votes vote down vote up
@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);
}
 
Example #2
Source File: ValidationExceptionMapper.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #3
Source File: ApiError.java    From spring-boot-exception-handling with MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example #4
Source File: UpdateStackRequestValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    underTest = new UpdateStackRequestValidator();
    constraintValidatorContext = new ConstraintValidatorContextImpl(
            null,
            PathImpl.createPathFromString("status"),
            new DummyConstraintDescriptor(),
            null
    );
}
 
Example #5
Source File: AbstractValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
ConstraintViolationBuilder getConstraintViolationBuilder() {
    return new ConstraintValidatorContextImpl(null,
            PathImpl.createRootPath(),
            new DummyConstraintDescriptor(),
            null
    ).buildConstraintViolationWithTemplate("dummytemplate");
}
 
Example #6
Source File: RestApiError.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example #7
Source File: GlobalExceptionTranslator.java    From staffjoy with MIT License 5 votes vote down vote up
@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();
}
 
Example #8
Source File: BladeRestExceptionTranslator.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #9
Source File: ApiError.java    From spring-glee-o-meter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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());
}
 
Example #10
Source File: GlobalExceptionHandler.java    From litemall with MIT License 5 votes vote down vote up
@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();
}
 
Example #11
Source File: ApiError.java    From spring-boot-akka-event-sourcing-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example #12
Source File: GlobalExceptionHandler.java    From mall with MIT License 5 votes vote down vote up
@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();
}
 
Example #13
Source File: GlobalExceptionHandler.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example #14
Source File: GlobalExceptionHandler.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example #15
Source File: MockConstraintViolation.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
@Override
public Path getPropertyPath() {
    return PathImpl.createPathFromString(propertyPath);
}
 
Example #16
Source File: EnumListValidatorTest.java    From edison-microservice with Apache License 2.0 4 votes vote down vote up
private ConstraintValidatorContext createContext() {
    return new ConstraintValidatorContextImpl(Collections.emptyList(), DefaultClockProvider.INSTANCE, PathImpl.createPathFromString("target"), mock(ConstraintDescriptor.class), null);
}
 
Example #17
Source File: SheetBeanValidator.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
            
        }
        
    }
    
}
 
Example #18
Source File: ApiError.java    From POC with Apache License 2.0 2 votes vote down vote up
/**
 * 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());
}