Search in sources :

Example 11 with BeanPropertyBindingResult

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

the class ValidatorFactoryTests method testSpringValidationWithClassLevel.

@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ObjectError(org.springframework.validation.ObjectError) Test(org.junit.Test)

Example 12 with BeanPropertyBindingResult

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

the class PayloadArgumentResolver method validate.

/**
	 * Validate the payload if applicable.
	 * <p>The default implementation checks for {@code @javax.validation.Valid},
	 * Spring's {@link org.springframework.validation.annotation.Validated},
	 * and custom annotations whose name starts with "Valid".
	 * @param message the currently processed message
	 * @param parameter the method parameter
	 * @param target the target payload object
	 * @throws MethodArgumentNotValidException in case of binding errors
	 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
    if (this.validator == null) {
        return;
    }
    for (Annotation ann : parameter.getParameterAnnotations()) {
        Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
        if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
            Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] { hints });
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, getParameterName(parameter));
            if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
                ((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
            } else {
                this.validator.validate(target, bindingResult);
            }
            if (bindingResult.hasErrors()) {
                throw new MethodArgumentNotValidException(message, parameter, bindingResult);
            }
            break;
        }
    }
}
Also used : Validated(org.springframework.validation.annotation.Validated) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) SmartValidator(org.springframework.validation.SmartValidator) Annotation(java.lang.annotation.Annotation)

Example 13 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult 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 BeanPropertyBindingResult

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

the class ModelResultMatchersTests method setUp.

@Before
public void setUp() throws Exception {
    this.matchers = new ModelResultMatchers();
    ModelAndView mav = new ModelAndView("view", "good", "good");
    BindingResult bindingResult = new BeanPropertyBindingResult("good", "good");
    mav.addObject(BindingResult.MODEL_KEY_PREFIX + "good", bindingResult);
    this.mvcResult = getMvcResult(mav);
    Date date = new Date();
    BindingResult bindingResultWithError = new BeanPropertyBindingResult(date, "date");
    bindingResultWithError.rejectValue("time", "error");
    ModelAndView mavWithError = new ModelAndView("view", "good", "good");
    mavWithError.addObject("date", date);
    mavWithError.addObject(BindingResult.MODEL_KEY_PREFIX + "date", bindingResultWithError);
    this.mvcResultWithError = getMvcResult(mavWithError);
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ModelAndView(org.springframework.web.servlet.ModelAndView) Date(java.util.Date) Before(org.junit.Before)

Example 15 with BeanPropertyBindingResult

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

the class DefaultHandlerExceptionResolverTests method handleMethodArgumentNotValid.

@Test
public void handleMethodArgumentNotValid() throws Exception {
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(new TestBean(), "testBean");
    errors.rejectValue("name", "invalid");
    MethodParameter parameter = new MethodParameter(this.getClass().getMethod("handle", String.class), 0);
    MethodArgumentNotValidException ex = new MethodArgumentNotValidException(parameter, errors);
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertNotNull("No ModelAndView returned", mav);
    assertTrue("No Empty ModelAndView returned", mav.isEmpty());
    assertEquals("Invalid status code", 400, response.getStatus());
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) TestBean(org.springframework.tests.sample.beans.TestBean) ModelAndView(org.springframework.web.servlet.ModelAndView) MethodParameter(org.springframework.core.MethodParameter) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) Test(org.junit.Test)

Aggregations

BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)73 Test (org.junit.Test)60 TestBean (org.springframework.tests.sample.beans.TestBean)19 Errors (org.springframework.validation.Errors)18 StringReader (java.io.StringReader)17 Document (org.dom4j.Document)17 Element (org.dom4j.Element)17 SAXReader (org.dom4j.io.SAXReader)17 BindingResult (org.springframework.validation.BindingResult)11 PropertyEditorSupport (java.beans.PropertyEditorSupport)10 List (java.util.List)10 ArrayList (java.util.ArrayList)8 CreateUserCommand (org.asqatasun.webapp.command.CreateUserCommand)6 CreateUserFormValidator (org.asqatasun.webapp.validator.CreateUserFormValidator)6 MockBodyContent (org.springframework.mock.web.test.MockBodyContent)6 LinkedList (java.util.LinkedList)5 ExtendedModelMap (org.springframework.ui.ExtendedModelMap)5 Model (org.springframework.ui.Model)5 FieldError (org.springframework.validation.FieldError)5 ObjectError (org.springframework.validation.ObjectError)5