Java 类org.springframework.validation.BeanPropertyBindingResult 实例源码

项目:nixmash-blog    文件:SiteOptionTests.java   
@Test
public void SiteOptionMapDtoValidationTests() {

    SiteOptionMapDTO siteOptionMapDTO = SiteOptionMapDTO.withGeneralSettings(
            null,
            siteOptions.getSiteDescription(),
            siteOptions.getAddGoogleAnalytics(),
            siteOptions.getGoogleAnalyticsTrackingId(),
            siteOptions.getUserRegistration())
            .build();

    Errors errors = new BeanPropertyBindingResult(siteOptionMapDTO, "siteOptionMapDTO");
    ValidationUtils.invokeValidator(new SiteOptionMapDtoValidator(), siteOptionMapDTO, errors);
    assertTrue(errors.hasFieldErrors("siteName"));
    assertEquals("EMPTY", errors.getFieldError("siteName").getCode());

}
项目:SpringMvcBlog    文件:BlogValidationTests.java   
@Test
public void testValidationError(){
    Blog blog = new Blog(){
        {
            setBlogName("te");
            setBlogUrl("Test Blog");
        }
    };

    Errors errors = new BeanPropertyBindingResult(blog, "blog");
    blogValidation.validate(blog, errors);
    assertTrue(errors.hasErrors());
    assertTrue( errors.getErrorCount() == 1 );
    assertEquals("Blog ad\u0131 en az �� karekter olmal\u0131.", 
            getConfiguredMessage(errors.getFieldError("BlogName")));

}
项目:spring4-understanding    文件:PayloadArgumentResolver.java   
/**
 * 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;
        }
    }
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidation() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(2, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    List<String> errorCodes = Arrays.asList(fieldError.getCodes());
    assertEquals(4, errorCodes.size());
    assertTrue(errorCodes.contains("NotNull.person.name"));
    assertTrue(errorCodes.contains("NotNull.name"));
    assertTrue(errorCodes.contains("NotNull.java.lang.String"));
    assertTrue(errorCodes.contains("NotNull"));
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    errorCodes = Arrays.asList(fieldError.getCodes());
    assertEquals(5, errorCodes.size());
    assertTrue(errorCodes.contains("NotNull.person.address.street"));
    assertTrue(errorCodes.contains("NotNull.address.street"));
    assertTrue(errorCodes.contains("NotNull.street"));
    assertTrue(errorCodes.contains("NotNull.java.lang.String"));
    assertTrue(errorCodes.contains("NotNull"));
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@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"));
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidationWithErrorInListElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressList().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressList[0].street");
    assertEquals("addressList[0].street", fieldError.getField());
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidationWithErrorInSetElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.getAddressSet().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressSet[].street");
    assertEquals("addressSet[].street", fieldError.getField());
}
项目:spring4-understanding    文件:MarshallingViewTests.java   
@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
    Object toBeMarshalled = new Object();
    String modelKey = "key";
    Map<String, Object> model = new LinkedHashMap<String, Object>();
    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));
}
项目:spring4-understanding    文件:InputTagTests.java   
@Test
public void withErrors() throws Exception {
    this.tag.setPath("name");
    this.tag.setCssClass("good");
    this.tag.setCssErrorClass("bad");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", getType());
    assertValueAttribute(output, "Rob");
    assertContainsAttribute(output, "class", "bad");
}
项目:spring4-understanding    文件:InputTagTests.java   
@Test
public void withCustomBinder() throws Exception {
    this.tag.setPath("myFloat");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", getType());
    assertValueAttribute(output, "12.34f");
}
项目:spring4-understanding    文件:RadioButtonTagTests.java   
@Test
public void withCheckedObjectValueAndEditor() throws Exception {
    this.tag.setPath("myFloat");
    this.tag.setValue("F12.99");

    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    MyFloatEditor editor = new MyFloatEditor();
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(Float.class, editor);
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);
    assertContainsAttribute(output, "name", "myFloat");
    assertContainsAttribute(output, "type", "radio");
    assertContainsAttribute(output, "value", "F" + getFloat().toString());
    assertContainsAttribute(output, "checked", "checked");
}
项目:spring4-understanding    文件:HiddenInputTagTests.java   
@Test
public void withCustomBinder() throws Exception {
    this.tag.setPath("myFloat");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();

    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", "hidden");
    assertContainsAttribute(output, "value", "12.34f");
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void withExplicitNonWhitespaceBodyContent() throws Exception {
    String mockContent = "This is some explicit body content";
    this.tag.setBodyContent(new MockBodyContent(mockContent, getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);
    assertEquals(mockContent, getOutput());
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void withExplicitWhitespaceBodyContent() throws Exception {
    this.tag.setBodyContent(new MockBodyContent("\t\n   ", getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "Default Message");
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void withExplicitEmptyWhitespaceBodyContent() throws Exception {
    this.tag.setBodyContent(new MockBodyContent("", getWriter()));

    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "Default Message");
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void withErrors() throws Exception {
    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "<br/>");
    assertBlockTagContains(output, "Default Message");
    assertBlockTagContains(output, "Too Short");
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void withEscapedErrors() throws Exception {
    // construct an errors instance of the tag
    TestBean target = new TestBean();
    target.setName("Rob Harrop");
    Errors errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default <> Message");
    errors.rejectValue("name", "too.short", "Too & Short");

    exposeBindingResult(errors);

    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertElementTagOpened(output);
    assertElementTagClosed(output);

    assertContainsAttribute(output, "id", "name.errors");
    assertBlockTagContains(output, "<br/>");
    assertBlockTagContains(output, "Default &lt;&gt; Message");
    assertBlockTagContains(output, "Too &amp; Short");
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void asBodyTag() throws Exception {
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
@Test
public void asBodyTagWithExistingMessagesAttribute() throws Exception {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
/**
 * https://jira.spring.io/browse/SPR-2788
 */
@Test
public void asBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, PageContext.APPLICATION_SCOPE);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    assertTrue(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE) instanceof List);
    String bodyContent = "Foo";
    this.tag.setBodyContent(new MockBodyContent(bodyContent, getWriter()));
    this.tag.doEndTag();
    this.tag.doFinally();
    assertEquals(bodyContent, getOutput());
    assertEquals(existingAttribute,
            getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, PageContext.APPLICATION_SCOPE));
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
/**
 * https://jira.spring.io/browse/SPR-4005
 */
@Test
public void omittedPathMatchesObjectErrorsOnly() throws Exception {
    this.tag.setPath(null);
    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    errors.reject("some.code", "object error");
    errors.rejectValue("name", "some.code", "field error");
    exposeBindingResult(errors);
    this.tag.doStartTag();
    assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
    this.tag.doEndTag();
    String output = getOutput();
    assertTrue(output.contains("id=\"testBean.errors\""));
    assertTrue(output.contains("object error"));
    assertFalse(output.contains("field error"));
}
项目:spring4-understanding    文件:ErrorsTagTests.java   
private void assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(int scope) throws JspException {
    String existingAttribute = "something";
    getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, scope);

    Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
    exposeBindingResult(errors);
    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);

    String output = getOutput();
    assertEquals(0, output.length());

    assertEquals(existingAttribute, getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, scope));
}
项目:spring4-understanding    文件:CheckboxTagTests.java   
@Test
public void withSingleValueAndEditor() throws Exception {
    this.bean.setName("Rob Harrop");
    this.tag.setPath("name");
    this.tag.setValue("   Rob Harrop");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, new StringTrimmerEditor(false));
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element checkboxElement = (Element) document.getRootElement().elements().get(0);
    assertEquals("input", checkboxElement.getName());
    assertEquals("checkbox", checkboxElement.attribute("type").getValue());
    assertEquals("name", checkboxElement.attribute("name").getValue());
    assertEquals("checked", checkboxElement.attribute("checked").getValue());
    assertEquals("   Rob Harrop", checkboxElement.attribute("value").getValue());
}
项目:spring4-understanding    文件:SelectTagTests.java   
@Test
public void withListAndTransformTagAndEditor() throws Exception {
    this.tag.setPath("realCountry");
    this.tag.setItems(Country.getCountries());
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();

    TransformTag transformTag = new TransformTag();
    transformTag.setValue(Country.getCountries().get(0));
    transformTag.setVar("key");
    transformTag.setParent(this.tag);
    transformTag.setPageContext(getPageContext());
    transformTag.doStartTag();
    assertEquals("Austria", getPageContext().findAttribute("key"));
}
项目:spring4-understanding    文件:SelectTagTests.java   
@Test
public void withListAndEditor() throws Exception {
    this.tag.setPath("realCountry");
    this.tag.setItems(Country.getCountries());
    this.tag.setItemValue("isoCode");
    this.tag.setItemLabel("name");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();
    String output = getOutput();
    assertTrue(output.startsWith("<select "));
    assertTrue(output.endsWith("</select>"));
    assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
项目:spring4-understanding    文件:SelectTagTests.java   
@Test
public void nestedPathWithListAndEditor() throws Exception {
    this.tag.setPath("bean.realCountry");
    this.tag.setItems(Country.getCountries());
    this.tag.setItemValue("isoCode");
    this.tag.setItemLabel("name");
    TestBeanWrapper testBean = new TestBeanWrapper();
    testBean.setBean(getTestBean());
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(testBean , "testBean");
    bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(Country.getCountryWithIsoCode(text));
        }
        @Override
        public String getAsText() {
            return ((Country) getValue()).getName();
        }
    });
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
    this.tag.doStartTag();
    String output = getOutput();
    assertTrue(output.startsWith("<select "));
    assertTrue(output.endsWith("</select>"));
    assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
项目:spring4-understanding    文件:ModelResultMatchersTests.java   
@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);
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@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"));
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidationWithAutowiredValidator() throws Exception {
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
            LocalValidatorFactoryBean.class);
    LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

    ValidPerson person = new ValidPerson();
    person.expectsAutowiredValidator = true;
    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"));
    ctx.close();
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidationWithErrorInListElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();

    ValidPerson person = new ValidPerson();
    person.getAddressList().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressList[0].street");
    assertEquals("addressList[0].street", fieldError.getField());
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@Test
public void testSpringValidationWithErrorInSetElement() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();

    ValidPerson person = new ValidPerson();
    person.getAddressSet().add(new ValidAddress());
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(3, result.getErrorCount());
    FieldError fieldError = result.getFieldError("name");
    assertEquals("name", fieldError.getField());
    fieldError = result.getFieldError("address.street");
    assertEquals("address.street", fieldError.getField());
    fieldError = result.getFieldError("addressSet[].street");
    assertEquals("addressSet[].street", fieldError.getField());
}
项目:cwlviewer    文件:WorkflowFormValidatorTest.java   
/**
 * Packed URL
 */
@Test
public void packedUrl() throws Exception {

    WorkflowForm githubUrl = new WorkflowForm("https://github.com/MarkRobbo/workflows/tree/master/packed.cwl#workflowId");
    Errors errors = new BeanPropertyBindingResult(githubUrl, "workflowForm");
    GitDetails details = workflowFormValidator.validateAndParse(githubUrl, errors);

    assertNotNull(details);
    assertEquals("https://github.com/MarkRobbo/workflows.git", details.getRepoUrl());
    assertEquals("master", details.getBranch());
    assertEquals("packed.cwl", details.getPath());
    assertEquals("workflowId", details.getPackedId());
    assertFalse(errors.hasErrors());

}
项目:devwars.tv    文件:BlogController.java   
/**
 * Created new blog post
 *
 * @param blogPost JSON of the new post
 * @param user
 * @param session
 * @return
 */
@Transactional
@PreAuthorization(minRole = User.Role.BLOGGER)
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity createBlog(@JSONParam("post") BlogPost blogPost,
                                 @AuthedUser User user,
                                 SessionImpl session) {

    Errors errors = new BeanPropertyBindingResult(blogPost, "blogPost");
    blogPostValidator.validate(blogPost, errors);

    if (errors.hasErrors()) {
        return new ResponseEntity(errors.getAllErrors(), HttpStatus.BAD_REQUEST);
    }

    blogPost.setUser(user);

    session.save(blogPost);

    return new ResponseEntity(blogPost, HttpStatus.OK);
}
项目:c2mon    文件:AlarmValueImplTest.java   
/** Bean validator */
//  private LocalValidatorFactoryBean validator;

//  @Before
//  public void setup() {
//    validator = new LocalValidatorFactoryBean();
////    validator.setProviderClass(HibernateValidator.class);
//    validator.afterPropertiesSet();
//    
//    
//  }

  @Test
  public void testValidAlarmValidation() {
    AlarmValue alarm =
      new AlarmValueImpl(12342L, 1, "FaultMember1", "1FaultFamily", "Info1",
                         1234L, new Timestamp(System.currentTimeMillis()), true);

    BeanPropertyBindingResult result = new BeanPropertyBindingResult(alarm, "alarm");
//    validator.validate(alarm, result);
    assertEquals(0, result.getErrorCount());
  }
项目:IdentityRegistry    文件:VesselValidatorTests.java   
@Test
public void validateValidVesselWithAttributes() {
    Vessel validVessel = new Vessel();
    validVessel.setMrn("urn:mrn:mcl:org:test:vessel:valid-vessel");
    validVessel.setName("Test Vessel");
    VesselAttribute va1 = new VesselAttribute();
    va1.setAttributeName("flagstate");
    va1.setAttributeValue("Denmark");
    VesselAttribute va2 = new VesselAttribute();
    va2.setAttributeName("imo-number");
    va2.setAttributeValue("1234567");
    validVessel.setAttributes(new HashSet<>(Arrays.asList(va1, va2)));
    Errors errors = new BeanPropertyBindingResult(validVessel, "validVessel");
    this.vesselValidator.validate(validVessel, errors);
    assertEquals(0, errors.getErrorCount());
}
项目:IdentityRegistry    文件:VesselValidatorTests.java   
@Test
public void validateInvalidVesselWithAttributes() {
    Vessel invalidVessel = new Vessel();
    invalidVessel.setMrn("urn:mrn:mcl:org:test:vessel:invalid-vessel");
    invalidVessel.setName("Test Vessel");
    VesselAttribute va1 = new VesselAttribute();
    // Invalid attribute: value must not be empty
    va1.setAttributeName("flagstate");
    va1.setAttributeValue("");
    VesselAttribute va2 = new VesselAttribute();
    // Invalid attribute: must be one of the pre-defined values
    va2.setAttributeName(null);
    va2.setAttributeValue("1234567");
    invalidVessel.setAttributes(new HashSet<>(Arrays.asList(va1, va2)));
    Errors errors = new BeanPropertyBindingResult(invalidVessel, "invalidVessel");
    this.vesselValidator.validate(invalidVessel, errors);
    assertEquals(2, errors.getErrorCount());
}
项目:springlets    文件:CollectionValidator.java   
/**
 * Validate each element inside the supplied {@link Collection}.
 * 
 * The supplied errors instance is used to report the validation errors.
 * 
 * @param target the collection that is to be validated
 * @param errors contextual state about the validation process
 */
@Override
@SuppressWarnings("rawtypes")
public void validate(Object target, Errors errors) {
  Collection collection = (Collection) target;
  int index = 0;

  for (Object object : collection) {
    BeanPropertyBindingResult elementErrors = new BeanPropertyBindingResult(object,
        errors.getObjectName());
    elementErrors.setNestedPath("[".concat(Integer.toString(index++)).concat("]."));
    ValidationUtils.invokeValidator(validator, object, elementErrors);

    errors.addAllErrors(elementErrors);
  }
}