Java Code Examples for org.springframework.validation.BeanPropertyBindingResult

The following are top voted examples for showing how to use org.springframework.validation.BeanPropertyBindingResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SpringMvcBlog   File: UserValidationTests.java   View source code 7 votes vote down vote up
@Test
public void testValidateErrors(){
	
	User user = new User(){
		{
			setUserName("ey");
			setFirstName("Eyup");
			setLastName("Gevenim");
			setEmail("[email protected]");
			setPassword("123");
			setConfirmPassword("12");
		}
	};
	
	Errors errors = new BeanPropertyBindingResult(user, "user");
	userValidation.validate(user, errors);
	assertTrue(errors.hasErrors());
	assertTrue( errors.getErrorCount() == 3 );
	assertEquals("Kullan\u0131c\u0131 ad\u0131 en az �� karekter olmal\u0131.", 
			getConfiguredMessage(errors.getFieldError("UserName")));
	
}
 
Example 2
Project: SpringMvcBlog   File: UserValidationTests.java   View source code 7 votes vote down vote up
@Test
public void testValidateSuccess() throws Exception {
	
	User user = new User(){
		{
			setUserName("testSuccess");
			setFirstName("Test");
			setLastName("Test");
			setEmail("[email protected]");
			setPassword("123");
			setConfirmPassword("123");
		}
	};
	
	Errors errors = new BeanPropertyBindingResult(user, "user");
	userValidation.validate(user, errors);
	assertFalse(errors.hasErrors()); 
}
 
Example 3
Project: nixmash-blog   File: SiteOptionTests.java   View source code 6 votes vote down vote up
@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());

}
 
Example 4
Project: SpringMvcBlog   File: BlogValidationTests.java   View source code 6 votes vote down vote up
@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")));
	
}
 
Example 5
Project: spring4-understanding   File: PayloadArgumentResolver.java   View source code 6 votes vote down vote up
/**
 * 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;
		}
	}
}
 
Example 6
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 7
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 8
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 10
Project: spring4-understanding   File: MarshallingViewTests.java   View source code 6 votes vote down vote up
@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));
}
 
Example 11
Project: spring4-understanding   File: InputTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 12
Project: spring4-understanding   File: InputTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 13
Project: spring4-understanding   File: RadioButtonTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 14
Project: spring4-understanding   File: HiddenInputTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 15
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 16
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 17
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 18
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 19
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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");
}
 
Example 20
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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));
}
 
Example 21
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
@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));
}
 
Example 22
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 23
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
/**
 * 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"));
}
 
Example 24
Project: spring4-understanding   File: ErrorsTagTests.java   View source code 6 votes vote down vote up
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));
}
 
Example 25
Project: spring4-understanding   File: CheckboxTagTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 26
Project: spring4-understanding   File: SelectTagTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 27
Project: spring4-understanding   File: SelectTagTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 28
Project: spring4-understanding   File: SelectTagTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 29
Project: spring4-understanding   File: ModelResultMatchersTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 30
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 31
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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();
}
 
Example 32
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 33
Project: spring4-understanding   File: ValidatorFactoryTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 34
Project: cwlviewer   File: WorkflowFormValidatorTest.java   View source code 6 votes vote down vote up
/**
 * 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());

}
 
Example 35
Project: devwars.tv   File: BlogController.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 36
Project: c2mon   File: AlarmValueImplTest.java   View source code 6 votes vote down vote up
/** 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());
  }
 
Example 37
Project: subs   File: CoreValidatorTest.java   View source code 6 votes vote down vote up
@Before
public void setUp(){
    tearDown();

    team = Team.build(TEST_TEAM_1);
    submitter = Submitter.build("[email protected]");

    submission = new Submission();
    submission.setId("sub1");
    submission.setTeam(team);
    submission.setSubmitter(submitter);

    submissionRepository.insert(submission);


    sampleUnderValidation = new Sample();
    sampleUnderValidation.setAlias("testSample1");
    sampleUnderValidation.setTeam(team);
    sampleUnderValidation.setId("ts1");
    sampleUnderValidation.setSubmission(submission);

    errors = new BeanPropertyBindingResult(sampleUnderValidation, "sample");
}
 
Example 38
Project: IdentityRegistry   File: VesselValidatorTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 39
Project: IdentityRegistry   File: VesselValidatorTests.java   View source code 6 votes vote down vote up
@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());
}
 
Example 40
Project: springlets   File: CollectionValidator.java   View source code 6 votes vote down vote up
/**
 * 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);
  }
}