Search in sources :

Example 11 with BindingResult

use of org.springframework.validation.BindingResult in project spring-boot by spring-projects.

the class RelaxedDataBinderTests method testBindMap.

@Test
public void testBindMap() throws Exception {
    Map<String, Object> target = new LinkedHashMap<>();
    BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla");
    assertThat(result.getErrorCount()).isEqualTo(0);
    assertThat(target.get("value")).isEqualTo("123");
}
Also used : BindingResult(org.springframework.validation.BindingResult) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 12 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class SpringValidatorAdapter method processConstraintViolations.

/**
	 * Process the given JSR-303 ConstraintViolations, adding corresponding errors to
	 * the provided Spring {@link Errors} object.
	 * @param violations the JSR-303 ConstraintViolation results
	 * @param errors the Spring errors object to register to
	 */
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = determineField(violation);
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = determineErrorCode(cd);
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs, violation.getMessage()));
                    } else {
                        Object rejectedValue = getRejectedValue(field, violation, bindingResult);
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, rejectedValue, false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex);
            }
        }
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult) ObjectError(org.springframework.validation.ObjectError) NotReadablePropertyException(org.springframework.beans.NotReadablePropertyException) FieldError(org.springframework.validation.FieldError)

Example 13 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class PayloadArgumentResolver method resolveArgument.

@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
    Payload ann = parameter.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.expression())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }
    Object payload = message.getPayload();
    if (isEmptyPayload(payload)) {
        if (ann == null || ann.required()) {
            String paramName = getParameterName(parameter);
            BindingResult bindingResult = new BeanPropertyBindingResult(payload, paramName);
            bindingResult.addError(new ObjectError(paramName, "Payload value must not be empty"));
            throw new MethodArgumentNotValidException(message, parameter, bindingResult);
        } else {
            return null;
        }
    }
    Class<?> targetClass = parameter.getParameterType();
    Class<?> payloadClass = payload.getClass();
    if (ClassUtils.isAssignable(targetClass, payloadClass)) {
        validate(message, parameter, payload);
        return payload;
    } else {
        if (this.converter instanceof SmartMessageConverter) {
            SmartMessageConverter smartConverter = (SmartMessageConverter) this.converter;
            payload = smartConverter.fromMessage(message, targetClass, parameter);
        } else {
            payload = this.converter.fromMessage(message, targetClass);
        }
        if (payload == null) {
            throw new MessageConversionException(message, "Cannot convert from [" + payloadClass.getName() + "] to [" + targetClass.getName() + "] for " + message);
        }
        validate(message, parameter, payload);
        return payload;
    }
}
Also used : SmartMessageConverter(org.springframework.messaging.converter.SmartMessageConverter) BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ObjectError(org.springframework.validation.ObjectError) MessageConversionException(org.springframework.messaging.converter.MessageConversionException) Payload(org.springframework.messaging.handler.annotation.Payload)

Example 14 with BindingResult

use of org.springframework.validation.BindingResult in project cas by apereo.

the class RegisteredServiceSimpleFormControllerTests method verifyAddRegisteredServiceNoValues.

@Test
public void verifyAddRegisteredServiceNoValues() throws Exception {
    final BindingResult result = mock(BindingResult.class);
    when(result.getModel()).thenReturn(new HashMap<>());
    when(result.hasErrors()).thenReturn(true);
    assertTrue(result.hasErrors());
}
Also used : BindingResult(org.springframework.validation.BindingResult) Test(org.junit.Test)

Example 15 with BindingResult

use of org.springframework.validation.BindingResult in project entando-core by entando.

the class RestExceptionHandler method processRestRourceNotFoundEx.

@ExceptionHandler(value = RestRourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public RestResponse processRestRourceNotFoundEx(RestRourceNotFoundException ex) {
    logger.debug("Handling {} error", ex.getClass().getSimpleName());
    RestResponse response = null;
    if (null != ex.getBindingResult()) {
        BindingResult result = ex.getBindingResult();
        response = processAllErrors(result);
    } else {
        response = new RestResponse();
        RestError error = new RestError(ex.getErrorCode(), this.resolveLocalizedErrorMessage("NOT_FOUND", new Object[] { ex.getObjectName(), ex.getObjectCode() }));
        List<RestError> errors = new ArrayList<>();
        errors.add(error);
        response.setErrors(errors);
        response.setMetaData(new HashMap<>());
    }
    return response;
}
Also used : BindingResult(org.springframework.validation.BindingResult) RestResponse(org.entando.entando.web.common.model.RestResponse) RestError(org.entando.entando.web.common.model.RestError) ArrayList(java.util.ArrayList) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

BindingResult (org.springframework.validation.BindingResult)140 Test (org.junit.Test)28 Test (org.junit.jupiter.api.Test)27 List (java.util.List)23 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)23 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)23 ResponseEntity (org.springframework.http.ResponseEntity)20 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)20 Collectors (java.util.stream.Collectors)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 FieldError (org.springframework.validation.FieldError)16 ObjectError (org.springframework.validation.ObjectError)16 Model (org.springframework.ui.Model)15 ControllerAdvice (org.springframework.web.bind.annotation.ControllerAdvice)14 HashMap (java.util.HashMap)13 Nonnull (javax.annotation.Nonnull)13 Nullable (javax.annotation.Nullable)13 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)13 DefaultProblem (org.zalando.problem.DefaultProblem)13 Problem (org.zalando.problem.Problem)13