Search in sources :

Example 41 with BeanPropertyBindingResult

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

the class ValidatorFactoryTests method testListValidation.

@Test
public void testListValidation() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ListContainer listContainer = new ListContainer();
    listContainer.addString("A");
    listContainer.addString("X");
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(listContainer, "listContainer");
    errors.initConversion(new DefaultConversionService());
    validator.validate(listContainer, errors);
    FieldError fieldError = errors.getFieldError("list[1]");
    assertEquals("X", errors.getFieldValue("list[1]"));
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) FieldError(org.springframework.validation.FieldError) DefaultConversionService(org.springframework.core.convert.support.DefaultConversionService) Test(org.junit.Test)

Example 42 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 43 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project spring-mvc-31-demo by rstoyanchev.

the class AccountControllerTests method testSaveFail.

@Test
public void testSaveFail() {
    Account account = new Account();
    BindingResult result = new BeanPropertyBindingResult(account, "account");
    AccountManager mgr = createMock(AccountManager.class);
    mgr.saveOrUpdate(account);
    replay(mgr);
    AccountController contrlr = new AccountController(mgr);
    String view = contrlr.save(account, result);
    assertEquals("redirect:accounts", view);
    verify(mgr);
}
Also used : Account(org.springframework.samples.mvc31.crudcontroller.Account) BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) StubAccountManager(org.springframework.samples.mvc31.crudcontroller.StubAccountManager) AccountManager(org.springframework.samples.mvc31.crudcontroller.AccountManager) AccountController(org.springframework.samples.mvc31.crudcontroller.AccountController) Test(org.junit.Test)

Example 44 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Example 45 with BeanPropertyBindingResult

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

the class MarshallingViewTests method renderNoModelKeyAndBindingResultFirst.

@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
    Object toBeMarshalled = new Object();
    String modelKey = "key";
    Map<String, Object> model = new LinkedHashMap<>();
    model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey));
    model.put(modelKey, toBeMarshalled);
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true);
    given(marshallerMock.supports(Object.class)).willReturn(true);
    view.render(model, request, response);
    assertEquals("Invalid content type", "application/xml", response.getContentType());
    assertEquals("Invalid content length", 0, response.getContentLength());
    verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) StreamResult(javax.xml.transform.stream.StreamResult) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) LinkedHashMap(java.util.LinkedHashMap) 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