Java Code Examples for org.springframework.validation.BindingResult#reject()

The following examples show how to use org.springframework.validation.BindingResult#reject() . 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: SampleController.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * 验证失败返回true
 *
 * @param m
 * @param result
 * @return
 */
@Override
protected boolean hasError(Sample m, BindingResult result) {
    Assert.notNull(m);

    //字段错误 前台使用<es:showFieldError commandName="showcase/sample"/> 显示
    if (m.getBirthday() != null && m.getBirthday().after(new Date())) {
        //前台字段名(前台使用[name=字段名]取得dom对象) 错误消息键。。
        result.rejectValue("birthday", "birthday.past");
    }

    //全局错误 前台使用<es:showGlobalError commandName="showcase/sample"/> 显示
    if (m.getName().contains("admin")) {
        result.reject("name.must.not.admin");
    }

    return result.hasErrors();
}
 
Example 2
Source File: ResourceServerProperties.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
private void doValidate() throws BindException {
	BindingResult errors = new BeanPropertyBindingResult(this, "resourceServerProperties");
	boolean jwtConfigPresent = StringUtils.hasText(this.jwt.getKeyUri())
			|| StringUtils.hasText(this.jwt.getKeyValue());
	boolean jwkConfigPresent = StringUtils.hasText(this.jwk.getKeySetUri());
	if (jwtConfigPresent && jwkConfigPresent) {
		errors.reject("ambiguous.keyUri",
				"Only one of jwt.keyUri (or jwt.keyValue) and jwk.keySetUri should" + " be configured.");
	}
	if (!jwtConfigPresent && !jwkConfigPresent) {
		if (!StringUtils.hasText(this.userInfoUri) && !StringUtils.hasText(this.tokenInfoUri)) {
			errors.rejectValue("tokenInfoUri", "missing.tokenInfoUri",
					"Missing tokenInfoUri and userInfoUri and there is no " + "JWT verifier key");
		}
		if (StringUtils.hasText(this.tokenInfoUri) && isPreferTokenInfo()) {
			if (!StringUtils.hasText(this.clientSecret)) {
				errors.rejectValue("clientSecret", "missing.clientSecret", "Missing client secret");
			}
		}
	}
	if (errors.hasErrors()) {
		throw new BindException(errors);
	}
}
 
Example 3
Source File: AbstractEntityService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected T addEntity(String entityManagerCode, EntityDto request, BindingResult bindingResult) {
    IEntityManager entityManager = this.extractEntityManager(entityManagerCode);
    try {
        String id = request.getId();
        I oldEntity = (I) entityManager.getEntity(id);
        if (null != oldEntity) {
            bindingResult.reject(EntityValidator.ERRCODE_ENTITY_ALREADY_EXISTS,
                    new String[]{id}, "entity.exists");
            throw new ValidationConflictException(bindingResult);
        }
        I entity = this.getEntityPrototype(entityManager, request.getTypeCode());
        request.fillEntity(entity, this.getCategoryManager(), bindingResult);
        this.scanEntity(entity, bindingResult);
        if (!bindingResult.hasErrors()) {
            I newEntity = (I) this.addEntity(entityManager, entity);
            return this.buildEntityDto(newEntity);
        }
    } catch (ValidationConflictException vce) {
        throw vce;
    } catch (Exception e) {
        logger.error("Error adding entity", e);
        throw new RestServerError("error add entity", e);
    }
    return null;
}
 
Example 4
Source File: EntityValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validateBodyName(String id, EntityDto request, BindingResult bindingResult) {
    if (!StringUtils.equals(id, request.getId())) {
        bindingResult.rejectValue("id", ERRCODE_URINAME_MISMATCH, new String[]{id, request.getId()}, "entity.id.mismatch");
        throw new ValidationConflictException(bindingResult);
    }
    if (!this.existEntity(id)) {
        bindingResult.reject(ERRCODE_ENTITY_DOES_NOT_EXIST, new String[]{id}, "entity.notExists");
        throw new ResourceNotFoundException(bindingResult);
    }
}
 
Example 5
Source File: ReminderController.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
/**
 * Processes username requests
 */
@RequestMapping(value = {"/retrieveusername"}, method = RequestMethod.POST)
public String requestUsername(@ModelAttribute UserForm userForm, BindingResult results, Model model,
                              HttpServletRequest request, RedirectAttributes redirectAttributes) {
    log.debug("Requesting username reminder");
    User user = ModelUtils.convert(userForm);
    if (!validateEmail(user, results, model, request)) {
        return captchaRequest(model, request, ViewNames.USERNAME_REQUEST);
    }
    try {
        userService.sendUserNameReminder(user);
        populateRedirect(user, redirectAttributes);
        return ViewNames.REDIRECT_RETRIEVE_USERNAME;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.error("Exception while sending username reminder  {}", e);
        }
        results.reject("Unable to send username reminder :" + e.getMessage(), "Unable to send username reminder.");
        return captchaRequest(model, request, ViewNames.USERNAME_REQUEST);
    }
}
 
Example 6
Source File: BaseTreeableController.java    From es with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
public String deleteSelfAndChildren(
        Model model,
        @ModelAttribute("m") M m, BindingResult result,
        RedirectAttributes redirectAttributes) {


    if (permissionList != null) {
        permissionList.assertHasDeletePermission();
    }

    if (m.isRoot()) {
        result.reject("您删除的数据中包含根节点,根节点不能删除");
        return deleteForm(m, model);
    }

    baseService.deleteSelfAndChild(m);
    redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
    return redirectToUrl(viewName("success"));
}
 
Example 7
Source File: SecurityController.java    From java-course-ee with MIT License 6 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, @ModelAttribute LoginCommand command, BindingResult errors) {
    loginValidator.validate(command, errors);

    if (errors.hasErrors()) {
        return showLoginForm(model, command);
    }

    UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword(), command.isRememberMe());
    try {
        SecurityUtils.getSubject().login(token);
    } catch (AuthenticationException e) {
        errors.reject("error.login.generic", "Invalid username or password.  Please try again.");
    }

    if (errors.hasErrors()) {
        return showLoginForm(model, command);
    } else {
        return "redirect:/s/home";
    }
}
 
Example 8
Source File: ProfileTypeController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/profileTypes", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<UserProfileTypeDto>> addUserProfileTypes(@Valid @RequestBody ProfileTypeDtoRequest bodyRequest,
        BindingResult bindingResult) throws JsonProcessingException {
    //field validations
    this.getProfileTypeValidator().validate(bodyRequest, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    //business validations
    if (this.getProfileTypeValidator().existType(bodyRequest.getCode())) {
        bindingResult.reject(AbstractEntityTypeValidator.ERRCODE_ENTITY_TYPE_ALREADY_EXISTS, new String[]{bodyRequest.getCode()}, "entityType.exists");
    }
    if (bindingResult.hasErrors()) {
        throw new ValidationConflictException(bindingResult);
    }
    UserProfileTypeDto result = this.getUserProfileTypeService().addUserProfileType(bodyRequest, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    logger.debug("Main Response -> {}", result);
    return new ResponseEntity<>(new SimpleRestResponse<>(result), HttpStatus.OK);
}
 
Example 9
Source File: DeletedSampleController.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * 验证失败返回true
 *
 * @param m
 * @param result
 * @return
 */
@Override
protected boolean hasError(DeletedSample m, BindingResult result) {
    Assert.notNull(m);

    //字段错误 前台使用<es:showFieldError commandName="showcase/sample"/> 显示
    if (m.getBirthday() != null && m.getBirthday().after(new Date())) {
        //前台字段名(前台使用[name=字段名]取得dom对象) 错误消息键。。
        result.rejectValue("m.birthday", "birthday.past");
    }

    //全局错误 前台使用<es:showGlobalError commandName="showcase/sample"/> 显示
    if (m.getName().contains("admin")) {
        result.reject("name.must.not.admin");
    }

    return result.hasErrors();
}
 
Example 10
Source File: CategoryValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validatePutReferences(String categoryCode, CategoryDto request, BindingResult bindingResult) {
    if (!StringUtils.equals(categoryCode, request.getCode())) {
        bindingResult.rejectValue("code", ERRCODE_URINAME_MISMATCH, new String[]{categoryCode, request.getCode()}, "category.code.mismatch");
        throw new ValidationGenericException(bindingResult);
    }
    Category category = this.getCategoryManager().getCategory(request.getCode());
    if (null == category) {
        bindingResult.reject(ERRCODE_CATEGORY_NOT_FOUND, new String[]{request.getCode()}, "category.notexists");
        throw new ResourceNotFoundException(bindingResult);
    }
    Category parent = this.getCategoryManager().getCategory(request.getParentCode());
    if (null == parent) {
        bindingResult.reject(ERRCODE_PARENT_CATEGORY_NOT_FOUND, new String[]{request.getCode()}, "category.parent.notexists");
        throw new ResourceNotFoundException(bindingResult);
    } else if (!parent.getCode().equals(category.getParentCode())) {
        bindingResult.reject(ERRCODE_PARENT_CATEGORY_CANNOT_BE_CHANGED, new String[]{}, "category.parent.cannotBeChanged");
    }
}
 
Example 11
Source File: BulkImportController.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(FileUpload fileUpload, BindingResult result) {
    if (!fileUpload.getFile().isEmpty()) {
        try {
            saveFile(fileUpload.getFile());
        } catch (Throwable e) {
            result.reject(e.getMessage());
            return "bulk/upload";
        }
       return "bulk/upload";
   } else {
       return "bulk/upload";
   }
}
 
Example 12
Source File: ParentController.java    From es with Apache License 2.0 5 votes vote down vote up
/**
 * 验证失败返回true
 *
 * @param parent
 * @param result
 * @return
 */
protected boolean hasError(Parent parent, BindingResult result) {
    Assert.notNull(parent);

    //全局错误 前台使用<es:showGlobalError commandName="showcase/parent"/> 显示
    if (parent.getName().contains("admin")) {
        result.reject("name.must.not.admin");
    }

    return result.hasErrors();
}
 
Example 13
Source File: ContentService.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void scanEntity(Content currentEntity, BindingResult bindingResult) {
    super.scanEntity(currentEntity, bindingResult);

    //Validate Resources Main Group
    for (AttributeInterface attr : currentEntity.getAttributeList()) {
        if (AbstractResourceAttribute.class.isAssignableFrom(attr.getClass())) {
            AbstractResourceAttribute resAttr = (AbstractResourceAttribute) attr;

            for(ResourceInterface res : resAttr.getResources().values()) {
                AssetDto resource;
                try {
                    resource = resourcesService.getAsset(res.getId());
                } catch (ResourceNotFoundException e) {
                    logger.error("Resource not found: " + res.getId());
                    bindingResult.reject(EntityValidator.ERRCODE_ATTRIBUTE_INVALID,
                            "Resource not found - " + res.getId());
                    return;
                }

                String resourceMainGroup = resource.getGroup();

                if (!resourceMainGroup.equals(Group.FREE_GROUP_NAME)
                        && !resourceMainGroup.equals(currentEntity.getMainGroup())
                        && !currentEntity.getGroups().contains(resourceMainGroup)) {
                    bindingResult.reject(EntityValidator.ERRCODE_ATTRIBUTE_INVALID,
                            "Invalid resource group - " + resourceMainGroup);
                }
            }
        }
    }
}
 
Example 14
Source File: CategoryValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validatePostReferences(CategoryDto request, BindingResult bindingResult) {
    if (null != this.getCategoryManager().getCategory(request.getCode())) {
        bindingResult.reject(ERRCODE_CATEGORY_ALREADY_EXISTS, new String[]{request.getCode()}, "category.exists");
        throw new ValidationGenericException(bindingResult);
    }
    if (null == this.getCategoryManager().getCategory(request.getParentCode())) {
        bindingResult.reject(ERRCODE_PARENT_CATEGORY_NOT_FOUND, new String[]{request.getCode()}, "category.parent.notexists");
        throw new ResourceNotFoundException(bindingResult);
    }
}
 
Example 15
Source File: GoogleAnalyticsUpdateController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public String update(
		@PathVariable String language,
		@Validated @ModelAttribute(FORM_MODEL_KEY) GoogleAnalyticsUpdateForm form,
		BindingResult errors,
		@AuthenticationPrincipal AuthorizedUser authorizedUser,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
	redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

	if (errors.hasErrors()) {
		return "redirect:/_admin/{language}/analytics/edit?step.edit";
	}

	GoogleAnalyticsUpdateRequest request = new GoogleAnalyticsUpdateRequest();
	request.setBlogId(Blog.DEFAULT_ID);
	request.setTrackingId(form.getTrackingId());
	request.setProfileId(form.getProfileId());
	request.setCustomDimensionIndex(form.getCustomDimensionIndex());
	request.setServiceAccountId(form.getServiceAccountId());
	request.setServiceAccountP12File(form.getServiceAccountP12File());

	GoogleAnalytics updatedGoogleAnalytics;
	try {
		updatedGoogleAnalytics = blogService.updateGoogleAnalytics(request);
	} catch (GoogleAnalyticsException e) {
		errors.reject("GoogleAnalytics");
		return "redirect:/_admin/{language}/analytics/edit?step.edit";
	}

	redirectAttributes.getFlashAttributes().clear();
	redirectAttributes.addFlashAttribute("updatedGoogleAnalytics", updatedGoogleAnalytics);
	return "redirect:/_admin/{language}/analytics";
}
 
Example 16
Source File: TicketReservationManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public Optional<String> createTicketReservation(Event event,
                                                List<TicketReservationWithOptionalCodeModification> list,
                                                List<ASReservationWithOptionalCodeModification> additionalServices,
                                                Optional<String> promoCodeDiscount,
                                                Locale locale,
                                                BindingResult bindingResult) {
    Date expiration = DateUtils.addMinutes(new Date(), getReservationTimeout(event));
    try {
        String reservationId = createTicketReservation(event,
            list, additionalServices, expiration,
            promoCodeDiscount,
            locale, false);
        return Optional.of(reservationId);
    } catch (TicketReservationManager.NotEnoughTicketsException nete) {
        bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS);
    } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) {
        bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED);
    } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) {
        bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND);
    } catch (TicketReservationManager.TooManyTicketsForDiscountCodeException tooMany) {
        bindingResult.reject(ErrorsCode.STEP_2_DISCOUNT_CODE_USAGE_EXCEEDED);
    } catch (CannotProceedWithPayment cannotProceedWithPayment) {
        bindingResult.reject(ErrorsCode.STEP_1_CATEGORIES_NOT_COMPATIBLE);
        log.error("missing payment methods", cannotProceedWithPayment);
    }
    return Optional.empty();
}
 
Example 17
Source File: UserValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateUserPost(UserRequest request, BindingResult bindingResult) {
    String username = request.getUsername();
    UserDetails user = this.extractUser(username);
    if (null != user) {
        bindingResult.reject(UserValidator.ERRCODE_USER_ALREADY_EXISTS, new String[]{username}, "user.exists");
        throw new ValidationConflictException(bindingResult);
    }
    Matcher matcherUsername = pattern.matcher(username);
    int usLength = username.length();
    if (usLength < 4 || usLength > 80 || !matcherUsername.matches()) {
        bindingResult.reject(UserValidator.ERRCODE_USERNAME_FORMAT_INVALID, new String[]{username}, "user.username.format.invalid");
    }
    this.checkNewPassword(username, request.getPassword(), bindingResult);
}
 
Example 18
Source File: LogAdvice.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
private Throwable getCaughtError(BindingResult bindingResult) {
    Object attr = request.getAttribute(LogHandler.CAUGHT_ERROR_ATTRIBUTE_NAME);
    if (attr != null && attr instanceof Throwable) {
        bindingResult.reject("message.error");
        return (Throwable) attr;
    }
    return null;
}
 
Example 19
Source File: ProjectController.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/projects/create/ex")
public String createWithException(@Validated ProjectCreateForm projectCreateForm, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        bindingResult.reject("message.error.param", new Object[]{"foo"}, null);
        throw new RuntimeException("This is a test exception");
    }
    throw new RuntimeException("This is a test exception");
}
 
Example 20
Source File: UserValidator.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static BindingResult createSelfDeleteUserError(BindingResult bindingResult) {
    bindingResult.reject(UserValidator.ERRCODE_SELF_DELETE, new String[]{}, "user.self.delete.error");
    return bindingResult;
}