org.springframework.validation.BeanPropertyBindingResult Java Examples

The following examples show how to use org.springframework.validation.BeanPropertyBindingResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PortalPreferenceControllerTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdatePreferences_invalidPageSizeValue() {
    ModelMap model = new ExtendedModelMap();
    HashMap<String, PortalPreference> preferenceMap = new HashMap<String, PortalPreference>();
    PortalPreference pageSizePref = new PortalPreferenceImpl(PortalPreferenceKeys.PAGE_SIZE, "invalid");
    preferenceMap.put(PortalPreferenceKeys.PAGE_SIZE, pageSizePref);
    PortalPreferenceForm form = new PortalPreferenceForm(preferenceMap);
    final BindingResult errors = new BeanPropertyBindingResult(form, "form");
    SessionStatus sessionStatus = createMock(SessionStatus.class);

    replay(service, sessionStatus);
    String view = controller.updatePreferences(form, errors, validToken, validToken,REFERRER_ID, model, sessionStatus);

    assertEquals(ViewNames.ADMIN_PREFERENCE_DETAIL, view);
    assertTrue(errors.hasErrors());
    assertTrue(model.containsAttribute("topnav"));
    assertTrue(model.containsAttribute("tabs"));
    assertFalse("Model has not been cleared", model.isEmpty());

    verify(service, sessionStatus);
}
 
Example #2
Source File: PromoCodeRequestManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private Pair<Optional<String>, BindingResult> makeSimpleReservation(Event event,
                                                                    int ticketCategoryId,
                                                                    String promoCode,
                                                                    ServletWebRequest request,
                                                                    Optional<PromoCodeDiscount> promoCodeDiscount) {

    Locale locale = RequestUtils.getMatchingLocale(request, event);
    ReservationForm form = new ReservationForm();
    form.setPromoCode(promoCode);
    TicketReservationModification reservation = new TicketReservationModification();
    reservation.setAmount(1);
    reservation.setTicketCategoryId(ticketCategoryId);
    form.setReservation(Collections.singletonList(reservation));
    var bindingRes = new BeanPropertyBindingResult(form, "reservationForm");
    return Pair.of(createTicketReservation(form, bindingRes, event, locale, promoCodeDiscount.map(PromoCodeDiscount::getPromoCode)), bindingRes);
}
 
Example #3
Source File: WidgetControllerTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test(expected = SecurityException.class)
public void updateWidget_wrongToken() {
    WidgetImpl widget = new WidgetImpl();
    BindingResult errors = new BeanPropertyBindingResult(widget, "widget");
    SessionStatus sessionStatus = createMock(SessionStatus.class);
    ModelMap modelMap = new ExtendedModelMap();

    sessionStatus.setComplete();
    expectLastCall();
    replay(sessionStatus);

    String otherToken = AdminControllerUtil.generateSessionToken();

    controller.updateWidgetDetail(widget, errors, "sessionToken", otherToken,REFERRER_ID, modelMap, sessionStatus);

    verify(sessionStatus);
    assertFalse("Can't come here", true);
}
 
Example #4
Source File: CollectionValidator.java    From springlets with Apache License 2.0 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);
  }
}
 
Example #5
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithClassLevel() {
	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 #6
Source File: ErrorsTagTests.java    From java-technology-stack with MIT License 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 #7
Source File: SpringValidatorAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-13406
public void testNoStringArgumentValue() {
	TestBean testBean = new TestBean();
	testBean.setPassword("pass");
	testBean.setConfirmPassword("pass");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
	validatorAdapter.validate(testBean, errors);

	assertThat(errors.getFieldErrorCount("password"), is(1));
	assertThat(errors.getFieldValue("password"), is("pass"));
	FieldError error = errors.getFieldError("password");
	assertNotNull(error);
	assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Size of Password is must be between 8 and 128"));
	assertTrue(error.contains(ConstraintViolation.class));
	assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password"));
}
 
Example #8
Source File: SpringValidatorAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-13406
public void testApplyMessageSourceResolvableToStringArgumentValueWithResolvedLogicalFieldName() {
	TestBean testBean = new TestBean();
	testBean.setPassword("password");
	testBean.setConfirmPassword("PASSWORD");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
	validatorAdapter.validate(testBean, errors);

	assertThat(errors.getFieldErrorCount("password"), is(1));
	assertThat(errors.getFieldValue("password"), is("password"));
	FieldError error = errors.getFieldError("password");
	assertNotNull(error);
	assertThat(messageSource.getMessage(error, Locale.ENGLISH), is("Password must be same value as Password(Confirm)"));
	assertTrue(error.contains(ConstraintViolation.class));
	assertThat(error.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("password"));
}
 
Example #9
Source File: InputTagTests.java    From spring4-understanding with Apache License 2.0 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 #10
Source File: ErrorsTagTests.java    From spring4-understanding with Apache License 2.0 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 #11
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 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 #12
Source File: WidgetService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void removeWidget(String widgetCode) {
    try {
        WidgetType type = this.getWidgetManager().getWidgetType(widgetCode);
        BeanPropertyBindingResult validationResult = checkWidgetForDelete(type);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }
        List<String> fragmentCodes = this.getGuiFragmentManager().getGuiFragmentCodesByWidgetType(widgetCode);
        for (String fragmentCode : fragmentCodes) {
            this.getGuiFragmentManager().deleteGuiFragment(fragmentCode);
        }
        this.getWidgetManager().deleteWidgetType(widgetCode);
    } catch (ApsSystemException e) {
        logger.error("Failed to remove widget type for request {} ", widgetCode);
        throw new RestServerError("failed to update widget type by code ", e);
    }
}
 
Example #13
Source File: LabelService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public LabelDto updateLabelGroup(LabelDto labelRequest) {
    try {
        String code = labelRequest.getKey();
        ApsProperties labelGroup = this.getI18nManager().getLabelGroup(code);
        if (null == labelGroup) {
            logger.warn("no label found with key {}", code);
            throw new ResourceNotFoundException(LabelValidator.ERRCODE_LABELGROUP_NOT_FOUND, "label", code);
        }
        BeanPropertyBindingResult validationResult = this.validateUpdateLabelGroup(labelRequest);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }
        ApsProperties languages = new ApsProperties();
        languages.putAll(labelRequest.getTitles());
        this.getI18nManager().updateLabelGroup(code, languages);
        return labelRequest;
    } catch (ApsSystemException t) {
        logger.error("error in update label group with code {}", labelRequest.getKey(), t);
        throw new RestServerError("error in update label group", t);
    }
}
 
Example #14
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 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 #15
Source File: ModelResultMatchersTests.java    From java-technology-stack with MIT License 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 #16
Source File: WebMvcConfigurationSupportExtensionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void webBindingInitializer() throws Exception {
	RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();

	assertNotNull(initializer);

	BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");
	initializer.getValidator().validate(null, bindingResult);
	assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode());

	String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null);
	assertEquals("custom.invalid", codes[0]);
}
 
Example #17
Source File: ErrorsTagTests.java    From spring-analysis-note with MIT License 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 #18
Source File: ErrorsTagTests.java    From spring-analysis-note with MIT License 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 #19
Source File: HiddenInputTagTests.java    From java-technology-stack with MIT License 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 #20
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 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 #21
Source File: ErrorsTagTests.java    From spring-analysis-note with MIT License 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 #22
Source File: WidgetControllerTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void updateWidget_valid() {
    final String widgetUrl = "http://example.com/widget";
    WidgetImpl widget = new WidgetImpl("123", widgetUrl);
    widget.setTitle("WidgetImpl title");
    widget.setType("OpenSocial");
    widget.setDescription("Lorem ipsum");
    BindingResult errors = new BeanPropertyBindingResult(widget, "widget");
    SessionStatus sessionStatus = createMock(SessionStatus.class);
    ModelMap modelMap = new ExtendedModelMap();

    expect(service.getWidgetByUrl(widgetUrl)).andReturn(widget);
    service.updateWidget(widget);
    sessionStatus.setComplete();
    expectLastCall();
    replay(service, sessionStatus);
    String view = controller.updateWidgetDetail(widget, errors, validToken, validToken,REFERRER_ID, modelMap, sessionStatus);
    verify(service, sessionStatus);

    assertFalse("No errors", errors.hasErrors());
    assertEquals("redirect:/app/admin/widgets?action=update&referringPageId=" +REFERRER_ID, view);



}
 
Example #23
Source File: SelectTagTests.java    From spring4-understanding with Apache License 2.0 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 #24
Source File: SelectTagTests.java    From spring4-understanding with Apache License 2.0 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 #25
Source File: ErrorsTagTests.java    From spring-analysis-note with MIT License 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 #26
Source File: LabelService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public LabelDto addLabelGroup(LabelDto labelRequest) {
    try {
        BeanPropertyBindingResult validationResult = this.validateAddLabelGroup(labelRequest);
        if (validationResult.hasErrors()) {
            throw new ValidationConflictException(validationResult);
        }
        String code = labelRequest.getKey();
        ApsProperties languages = new ApsProperties();
        languages.putAll(labelRequest.getTitles());
        this.getI18nManager().addLabelGroup(code, languages);
        return labelRequest;
    } catch (ApsSystemException t) {
        logger.error("error in add label group with code {}", labelRequest.getKey(), t);
        throw new RestServerError("error in add label group", t);
    }
}
 
Example #27
Source File: MarshallingViewTests.java    From spring4-understanding with Apache License 2.0 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 #28
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithErrorInSetElement() {
	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 #29
Source File: GroupService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected BeanPropertyBindingResult checkGroupForDelete(Group group) throws ApsSystemException {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(group, "group");

    if (null == group) {
        return bindingResult;
    }
    if (Group.FREE_GROUP_NAME.equals(group.getName()) || Group.ADMINS_GROUP_NAME.equals(group.getName())) {
        bindingResult.reject(GroupValidator.ERRCODE_CANNOT_DELETE_RESERVED_GROUP, new String[]{group.getName()}, "group.cannot.delete.reserved");
    }
    if (!bindingResult.hasErrors()) {

        Map<String, Boolean> references = this.getReferencesInfo(group);
        if (references.size() > 0) {
            for (Map.Entry<String, Boolean> entry : references.entrySet()) {
                if (true == entry.getValue().booleanValue()) {

                    bindingResult.reject(GroupValidator.ERRCODE_GROUP_REFERENCES, new Object[]{group.getName(), entry.getKey()}, "group.cannot.delete.references");
                }
            }
        }
    }

    return bindingResult;
}
 
Example #30
Source File: PageModelService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected BeanPropertyBindingResult validateAdd(PageModelRequest pageModelRequest) {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(pageModelRequest, "pageModel");
    PageModel pageModel = pageModelManager.getPageModel(pageModelRequest.getCode());
    if (null != pageModel) {
        bindingResult.reject(PageModelValidator.ERRCODE_CODE_EXISTS, new String[]{pageModelRequest.getCode()}, "pageModel.code.exists");
        throw new ValidationConflictException(bindingResult);
    }
    this.validateDefaultWidgets(pageModelRequest, bindingResult);
    return bindingResult;
}