Java Code Examples for org.springframework.validation.DataBinder#getBindingResult()

The following examples show how to use org.springframework.validation.DataBinder#getBindingResult() . 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: UserController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RestAccessControl(permission = Permission.MANAGE_USERS)
@RequestMapping(value = "/{target:.+}/authorities", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse> deleteUserAuthorities(@ModelAttribute("user") UserDetails user, @PathVariable String target) throws ApsSystemException {
    logger.debug("user {} requesting delete authorities for username {}", user.getUsername(), target);
    DataBinder binder = new DataBinder(target);
    BindingResult bindingResult = binder.getBindingResult();
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    //business validations
    getUserValidator().validateUpdateSelf(target, user.getUsername(), bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    this.getUserService().deleteUserAuthorities(target);
    return new ResponseEntity<>(new SimpleRestResponse<>(new ArrayList<>()), HttpStatus.OK);
}
 
Example 2
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public PageDto getPage(String pageCode, String status) {
    IPage page = this.loadPage(pageCode, status);
    if (null == page) {
        logger.warn("no page found with code {} and status {}", pageCode, status);
        DataBinder binder = new DataBinder(pageCode);
        BindingResult bindingResult = binder.getBindingResult();
        String errorCode = status.equals(STATUS_DRAFT) ? ERRCODE_PAGE_NOT_FOUND : ERRCODE_PAGE_ONLY_DRAFT;
        bindingResult.reject(errorCode, new String[]{pageCode, status}, "page.NotFound");
        throw new ResourceNotFoundException(bindingResult);
    }
    String token = this.getPageTokenManager().encrypt(pageCode);
    PageDto pageDto = this.getDtoBuilder().convert(page);
    pageDto.setToken(token);
    pageDto.setReferences(this.getReferencesInfo(page));
    return pageDto;
}
 
Example 3
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public PageConfigurationDto restorePageConfiguration(String pageCode) {
    try {
        IPage pageD = this.loadPage(pageCode, STATUS_DRAFT);
        if (null == pageD) {
            throw new ResourceNotFoundException(ERRCODE_PAGE_NOT_FOUND, "page", pageCode);
        }
        IPage pageO = this.loadPage(pageCode, STATUS_ONLINE);
        if (null == pageO) {
            DataBinder binder = new DataBinder(pageCode);
            BindingResult bindingResult = binder.getBindingResult();
            bindingResult.reject(ERRCODE_STATUS_INVALID, new String[]{pageCode}, "page.status.invalid");
            throw new ValidationGenericException(bindingResult);
        }
        pageD.setMetadata(pageO.getMetadata());
        pageD.setWidgets(pageO.getWidgets());
        this.getPageManager().updatePage(pageD);
        PageConfigurationDto pageConfigurationDto = new PageConfigurationDto(pageO, STATUS_ONLINE);
        return pageConfigurationDto;
    } catch (ApsSystemException e) {
        logger.error("Error restoring page {} configuration", pageCode, e);
        throw new RestServerError("error in restoring page configuration", e);
    }
}
 
Example 4
Source File: BindTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException {
	PageContext pc = createPageContext();
	IndexedTestBean tb = new IndexedTestBean();
	DataBinder binder = new ServletRequestDataBinder(tb, "tb");
	binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() {
		@Override
		public String getAsText() {
			return "something";
		}
	});
	Errors errors = binder.getBindingResult();
	errors.rejectValue("array[0]", "code1", "message1");
	errors.rejectValue("array[0]", "code2", "message2");
	pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);

	BindTag tag = new BindTag();
	tag.setPageContext(pc);
	tag.setPath("tb.array[0]");
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
	assertTrue("Has status variable", status != null);
	assertTrue("Correct expression", "array[0]".equals(status.getExpression()));
	// because of the custom editor getValue() should return a String
	assertTrue("Value is TestBean", status.getValue() instanceof String);
	assertTrue("Correct value", "something".equals(status.getValue()));
}
 
Example 5
Source File: BindTagTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException {
	PageContext pc = createPageContext();
	IndexedTestBean tb = new IndexedTestBean();
	DataBinder binder = new ServletRequestDataBinder(tb, "tb");
	binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() {
		@Override
		public String getAsText() {
			return "something";
		}
	});
	Errors errors = binder.getBindingResult();
	errors.rejectValue("array[0]", "code1", "message1");
	errors.rejectValue("array[0]", "code2", "message2");
	pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);

	BindTag tag = new BindTag();
	tag.setPageContext(pc);
	tag.setPath("tb.array[0]");
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
	assertTrue("Has status variable", status != null);
	assertTrue("Correct expression", "array[0]".equals(status.getExpression()));
	// because of the custom editor getValue() should return a String
	assertTrue("Value is TestBean", status.getValue() instanceof String);
	assertTrue("Correct value", "something".equals(status.getValue()));
}
 
Example 6
Source File: BindTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException {
	PageContext pc = createPageContext();
	IndexedTestBean tb = new IndexedTestBean();
	DataBinder binder = new ServletRequestDataBinder(tb, "tb");
	binder.registerCustomEditor(TestBean.class, null, new PropertyEditorSupport() {
		@Override
		public String getAsText() {
			return "something";
		}
	});
	Errors errors = binder.getBindingResult();
	errors.rejectValue("array[0]", "code1", "message1");
	errors.rejectValue("array[0]", "code2", "message2");
	pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);

	BindTag tag = new BindTag();
	tag.setPageContext(pc);
	tag.setPath("tb.array[0]");
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	BindStatus status = (BindStatus) pc.getAttribute(BindTag.STATUS_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
	assertTrue("Has status variable", status != null);
	assertTrue("Correct expression", "array[0]".equals(status.getExpression()));
	// because of the custom editor getValue() should return a String
	assertTrue("Value is TestBean", status.getValue() instanceof String);
	assertTrue("Correct value", "something".equals(status.getValue()));
}
 
Example 7
Source File: ApiConsumerValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The secret must be not null for creating the consumer. Instead it can be
 * null during the update.
 */
public void validateForCreate(ApiConsumer consumer) {
    if (StringUtils.isEmpty(consumer.getSecret())) {
        DataBinder dataBinder = new DataBinder(consumer);
        BindingResult bindingResult = dataBinder.getBindingResult();
        bindingResult.rejectValue("secret", "notBlank", new String[]{"secret"}, "string.notBlank");
        throw new ValidationGenericException(bindingResult);
    }
}
 
Example 8
Source File: ApiConsumerValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateForUpdate(String consumerKey, ApiConsumer consumer) {
    if (!consumer.getKey().equals(consumerKey)) {
        DataBinder dataBinder = new DataBinder(consumer);
        BindingResult bindingResult = dataBinder.getBindingResult();
        bindingResult.rejectValue("key", ERRCODE_URINAME_MISMATCH, new String[]{consumerKey, consumer.getKey()}, "api.consumer.key.mismatch");
        throw new ValidationGenericException(bindingResult);
    }
}
 
Example 9
Source File: PageSettingsController.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/pageSettings", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<PageSettingsDto>> updatePageSettings(@RequestBody PageSettingsRequest request) {
    //params validations
    if (request == null || request.isEmpty()) {
        DataBinder binder = new DataBinder(request);
        BindingResult bindingResult = binder.getBindingResult();
        bindingResult.reject("NotEmpty.pagesettings.params");
        throw new ValidationGenericException(bindingResult);
    }
    PageSettingsDto pageSettings = this.getPageSettingsService().updatePageSettings(request);
    return new ResponseEntity<>(new SimpleRestResponse<>(pageSettings), HttpStatus.OK);
}
 
Example 10
Source File: PageController.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ActivityStreamAuditable
@RestAccessControl(permission = Permission.MANAGE_PAGES)
@RequestMapping(value = "/pages/{pageCode}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<?>> deletePage(@ModelAttribute("user") UserDetails user, @PathVariable String pageCode) throws ApsSystemException {
    logger.debug("deleting {}", pageCode);
    if (!this.getAuthorizationService().isAuth(user, pageCode)) {
        return new ResponseEntity<>(new SimpleRestResponse<>(new PageDto()), HttpStatus.UNAUTHORIZED);
    }
    DataBinder binder = new DataBinder(pageCode);
    BindingResult bindingResult = binder.getBindingResult();
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    //business validations
    getPageValidator().validateOnlinePage(pageCode, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    //business validations
    getPageValidator().validateChildren(pageCode, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    this.getPageService().removePage(pageCode);
    Map<String, String> payload = new HashMap<>();
    payload.put("code", pageCode);
    return new ResponseEntity<>(new SimpleRestResponse<>(payload), HttpStatus.OK);
}
 
Example 11
Source File: ApiConsumerServiceImpl.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void validateForCreate(ApiConsumer consumer) throws ApsSystemException {

        if (consumerManager.getConsumerRecord(consumer.getKey()) != null) {
            DataBinder binder = new DataBinder(consumer);
            BindingResult bindingResult = binder.getBindingResult();
            bindingResult.reject(ERRCODE_CONSUMER_ALREADY_EXISTS, new String[]{consumer.getKey()}, "api.consumer.exists");
            throw new ValidationConflictException(bindingResult);
        }
    }
 
Example 12
Source File: ContentController.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RestAccessControl(permission = Permission.CONTENT_EDITOR)
@RequestMapping(value = "/{code}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<?>> deleteContent(@PathVariable String code) {
    logger.debug("Deleting content -> {}", code);
    DataBinder binder = new DataBinder(code);
    BindingResult bindingResult = binder.getBindingResult();
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    this.getContentService().deleteContent(code, HttpSessionHelper.extractCurrentUser(httpSession));
    Map<String, String> payload = new HashMap<>();
    payload.put("code", code);
    return new ResponseEntity<>(new SimpleRestResponse<>(payload), HttpStatus.OK);
}
 
Example 13
Source File: ErrorsMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private BindingResult createBindingResult(Foo target, String name) {
	DataBinder binder = this.bindingContext.createDataBinder(this.exchange, target, name);
	return binder.getBindingResult();
}
 
Example 14
Source File: DataBinderDemo.java    From geekbang-lessons with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        // 创建空白对象
        User user = new User();
        // 1. 创建 DataBinder
        DataBinder binder = new DataBinder(user, "");

        // 2. 创建 PropertyValues
        Map<String, Object> source = new HashMap<>();
        source.put("id", 1);
        source.put("name", "小马哥");

        // a. PropertyValues 存在 User 中不存在属性值
        // DataBinder 特性一 : 忽略未知的属性
        source.put("age", 18);

        // b. PropertyValues 存在一个嵌套属性,比如 company.name
        // DataBinder 特性二:支持嵌套属性
        // Company company = new Company();
        // company.setName("geekbang");
        // user.setCompany(compay)

//        source.put("company", new Company());
        source.put("company.name", "geekbang");

        PropertyValues propertyValues = new MutablePropertyValues(source);

        // 1. 调整 IgnoreUnknownFields true(默认) -> false(抛出异常,age 字段不存在于 User 类)
        // binder.setIgnoreUnknownFields(false);

        // 2. 调整自动增加嵌套路径 true(默认) —> false
        binder.setAutoGrowNestedPaths(false);

        // 3. 调整 ignoreInvalidFields false(默认) -> true(默认情况调整不变化,需要调增 AutoGrowNestedPaths 为 false)
        binder.setIgnoreInvalidFields(true);

        binder.setRequiredFields("id", "name", "city");

        binder.bind(propertyValues);

        // 3. 输出 User 内容
        System.out.println(user);

        // 4. 获取绑定结果(结果包含错误文案 code,不会抛出异常)
        BindingResult result = binder.getBindingResult();
        System.out.println(result);
    }
 
Example 15
Source File: ErrorsMethodArgumentResolverTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
private BindingResult createBindingResult(Foo target, String name) {
	DataBinder binder = this.bindingContext.createDataBinder(this.exchange, target, name);
	return binder.getBindingResult();
}