Java Code Examples for org.springframework.validation.BeanPropertyBindingResult#hasErrors()

The following examples show how to use org.springframework.validation.BeanPropertyBindingResult#hasErrors() . 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: PayloadArgumentResolver.java    From java-technology-stack with MIT License 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 2
Source File: PayloadArgumentResolver.java    From spring4-understanding with Apache License 2.0 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 3
Source File: ContentService.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<ContentDto> updateContentsStatus(List<String> codes, String status, UserDetails user) {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(codes, "content");
    List<ContentDto> result = codes.stream()
            .map(code -> {
                try {
                    return updateContentStatus(code, status, user, bindingResult);
                } catch (Exception e) {
                    logger.error("Error in updating content(code: {}) status {}", code, e);
                    return null;
                }
            })
            .filter(content -> content != null)
            .collect(Collectors.toList());
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }

    return result;
}
 
Example 4
Source File: PageConfigurationController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/pages/{pageCode}/widgets/{frameId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RestResponse<WidgetConfigurationDto, Map>> getPageWidget(@PathVariable String pageCode,
        @PathVariable String frameId,
        @RequestParam(value = "status", required = false, defaultValue = IPageService.STATUS_DRAFT) String status
) {
    logger.debug("requested widget detail for page {} and frame {}", pageCode, frameId);

    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(frameId, "frameId");
    this.validateFrameId(frameId, bindingResult);

    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }

    WidgetConfigurationDto widgetConfiguration = this.getPageService().getWidgetConfiguration(pageCode, Integer.valueOf(frameId), status);

    Map<String, String> metadata = new HashMap<>();
    metadata.put("status", status);
    return new ResponseEntity<>(new RestResponse<>(widgetConfiguration, metadata), HttpStatus.OK);
}
 
Example 5
Source File: PageConfigurationController.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@ActivityStreamAuditable
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/pages/{pageCode}/widgets/{frameId}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RestResponse<Map, Map>> deletePageWidget(@PathVariable String pageCode, @PathVariable String frameId) {
    logger.debug("removing widget configuration in page {} and frame {}", pageCode, frameId);
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(frameId, "frameId");
    this.validateFrameId(frameId, bindingResult);
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    this.getPageService().deleteWidgetConfiguration(pageCode, Integer.valueOf(frameId));
    Map<String, String> result = new HashMap<>();
    result.put("code", frameId);
    Map<String, String> metadata = new HashMap<>();
    metadata.put("status", IPageService.STATUS_DRAFT);
    return new ResponseEntity<>(new RestResponse<>(result, metadata), HttpStatus.OK);
}
 
Example 6
Source File: ContentModelServiceImpl.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ContentModelDto create(ContentModelDto entity) {
    try {
        ContentModel contentModel = this.createContentModel(entity);
        BeanPropertyBindingResult validationResult = this.validateForAdd(contentModel);
        if (validationResult.hasErrors()) {
            throw new ValidationConflictException(validationResult);
        }
        this.contentModelManager.addContentModel(contentModel);
        ContentModelDto dto = this.dtoBuilder.convert(contentModel);
        return dto;
    } catch (ApsSystemException e) {
        logger.error("Error saving a content model", e);
        throw new RestServerError("Error saving a content model", e);
    }
}
 
Example 7
Source File: RoleService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public RoleDto addRole(RoleRequest roleRequest) {
    try {
        Role role = this.createRole(roleRequest);
        BeanPropertyBindingResult validationResult = this.validateRoleForAdd(role);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }
        this.getRoleManager().addRole(role);
        RoleDto dto = this.getDtoBuilder().toDto(role, this.getRoleManager().getPermissionsCodes());
        return dto;
    } catch (ApsSystemException e) {
        logger.error("Error adding a role", e);
        throw new RestServerError("error in add role", e);
    }
}
 
Example 8
Source File: RoleService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void removeRole(String roleCode) {
    try {
        Role role = this.getRoleManager().getRole(roleCode);
        if (null == role) {
            logger.info("role {} does not exists", roleCode);
            return;
        }
        BeanPropertyBindingResult validationResult = this.validateRoleForDelete(role);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }
        this.getRoleManager().removeRole(role);
    } catch (ApsSystemException e) {
        logger.error("Error in delete role {}", roleCode, e);
        throw new RestServerError("error in delete role", e);
    }
}
 
Example 9
Source File: GroupService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void removeGroup(String groupName) {
    try {
        Group group = this.getGroupManager().getGroup(groupName);

        BeanPropertyBindingResult validationResult = this.checkGroupForDelete(group);
        if (validationResult.hasErrors()) {
            throw new ValidationConflictException(validationResult);
        }

        if (null != group) {
            this.getGroupManager().removeGroup(group);
        }
    } catch (ApsSystemException e) {
        logger.error("Error in delete group {}", groupName, e);
        throw new RestServerError("error in delete group", e);
    }
}
 
Example 10
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 11
Source File: DataObjectModelService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void removeDataObjectModel(Long dataModelId) {
    try {
        DataObjectModel dataObjectModel = this.getDataObjectModelManager().getDataObjectModel(dataModelId);
        if (null == dataObjectModel) {
            return;
        }
        DataModelDto dto = this.getDtoBuilder().convert(dataObjectModel);
        BeanPropertyBindingResult validationResult = this.checkDataObjectModelForDelete(dataObjectModel, dto);
        if (validationResult.hasErrors()) {
            throw new ValidationConflictException(validationResult);
        }
        this.getDataObjectModelManager().removeDataObjectModel(dataObjectModel);
    } catch (ApsSystemException e) {
        logger.error("Error in delete DataObjectModel {}", dataModelId, e);
        throw new RestServerError("error in delete DataObjectModel", e);
    }
}
 
Example 12
Source File: GuiFragmentService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void removeGuiFragment(String guiFragmentCode) {
    try {
        GuiFragment fragment = this.getGuiFragmentManager().getGuiFragment(guiFragmentCode);
        if (null == fragment) {
            return;
        }
        GuiFragmentDto dto = this.getDtoBuilder().convert(fragment);
        BeanPropertyBindingResult validationResult = this.checkFragmentForDelete(fragment, dto);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }
        this.getGuiFragmentManager().deleteGuiFragment(guiFragmentCode);
    } catch (ApsSystemException e) {
        logger.error("Error in delete guiFragmentCode {}", guiFragmentCode, e);
        throw new RestServerError("error in delete guiFragmentCode", 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: RawWebSocketMessage.java    From chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Deserializes the given message.
 * 
 * @param action
 * @return
 * @throws Exception
 */
public T deserialize(WebSocketAction action) throws Exception {
	// first deserialize
	T message = null;
	
	if (messageClass != null) {
		message = serDe.deserialize(new ByteBufferBackedInputStream(rawData), messageClass);
	}
	
	// then validate
	if (message != null && action.shouldValidatePayload()) {
		SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter(messageValidator);
		
		BeanPropertyBindingResult result = new BeanPropertyBindingResult(message, messageClass.getName());
		
		validatorAdapter.validate(message, result);
		
		if (result.hasErrors()) {
			throw new MethodArgumentNotValidException(new MethodParameter(action.getMethod(), action.getPayloadParameterIndex()), result);
		}
	}
	
	return message;
}
 
Example 15
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public WidgetConfigurationDto updateWidgetConfiguration(String pageCode, int frameId, WidgetConfigurationRequest widgetReq) {
    try {
        IPage page = this.loadPage(pageCode, STATUS_DRAFT);
        if (null == page) {
            throw new ResourceNotFoundException(ERRCODE_PAGE_NOT_FOUND, "page", pageCode);
        }
        if (page.getWidgets() == null || frameId > page.getWidgets().length) {
            throw new ResourceNotFoundException(ERRCODE_FRAME_INVALID, "frame", String.valueOf(frameId));
        }
        if (null == this.getWidgetType(widgetReq.getCode())) {
            throw new ResourceNotFoundException(ERRCODE_WIDGET_INVALID, "widget", String.valueOf(widgetReq.getCode()));
        }
        BeanPropertyBindingResult validation = this.getWidgetValidatorFactory().get(widgetReq.getCode()).validate(widgetReq, page);
        if (null != validation && validation.hasErrors()) {
            throw new ValidationConflictException(validation);
        }
        ApsProperties properties = (ApsProperties) this.getWidgetProcessorFactory().get(widgetReq.getCode()).buildConfiguration(widgetReq);
        WidgetType widgetType = this.getWidgetType(widgetReq.getCode());
        Widget widget = new Widget();
        widget.setType(widgetType);
        widget.setConfig(properties);
        this.getPageManager().joinWidget(pageCode, widget, frameId);

        ApsProperties outProperties = this.getWidgetProcessorFactory().get(widgetReq.getCode()).extractConfiguration(widget.getConfig());
        return new WidgetConfigurationDto(widget.getType().getCode(), outProperties);
    } catch (ApsSystemException e) {
        logger.error("Error in update widget configuration {}", pageCode, e);
        throw new RestServerError("error in update widget configuration", e);
    }
}
 
Example 16
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link 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 17
Source File: DataObjectModelService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected BeanPropertyBindingResult checkDataObjectModelForDelete(DataObjectModel model, DataModelDto dto) throws ApsSystemException {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(model, "dataObjectModel");
    if (null == model) {
        return bindingResult;
    }
    Map<String, List<IPage>> pages = this.getDataObjectModelManager().getReferencingPages(model.getId());
    if (!bindingResult.hasErrors() && !pages.isEmpty()) {
        bindingResult.reject(GuiFragmentValidator.ERRCODE_FRAGMENT_REFERENCES, new Object[]{String.valueOf(model.getId())}, "guifragment.cannot.delete.references");
    }
    return bindingResult;
}
 
Example 18
Source File: RoleService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public RoleDto updateRole(RoleRequest roleRequest) {
    try {
        Role role = this.getRoleManager().getRole(roleRequest.getCode());

        if (null == role) {
            logger.warn("no role found with code {}", roleRequest.getCode());
            throw new ResourceNotFoundException(RoleValidator.ERRCODE_ROLE_NOT_FOUND, "role", roleRequest.getCode());
        }

        role.setDescription(roleRequest.getName());
        role.getPermissions().clear();
        if (null != roleRequest.getPermissions()) {
            roleRequest.getPermissions().entrySet().stream().filter(entry -> null != entry.getValue() && entry.getValue().booleanValue()).forEach(i -> role.addPermission(i.getKey()));
        }
        BeanPropertyBindingResult validationResult = this.validateRoleForUpdate(role);
        if (validationResult.hasErrors()) {
            throw new ValidationGenericException(validationResult);
        }

        this.getRoleManager().updateRole(role);
        RoleDto dto = this.getDtoBuilder().toDto(role, this.getRoleManager().getPermissionsCodes());
        return dto;
    } catch (ApsSystemException e) {
        logger.error("Error updating a role", e);
        throw new RestServerError("error in update role", e);
    }
}
 
Example 19
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	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});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				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);
				}
			};
		}
	}
	return null;
}
 
Example 20
Source File: AbstractPaginationValidator.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void validateRestListRequest(RestListRequest listRequest, Class<?> type) {
    this.checkDefaultSortField(listRequest);
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(listRequest, "listRequest");
    if (listRequest.getPage() < 1) {
        bindingResult.reject(ERRCODE_PAGE_INVALID, new Object[]{}, "pagination.page.invalid");
        throw new ValidationGenericException(bindingResult);
    }
    if (listRequest.getPageSize() < 0) {
        bindingResult.reject(ERRCODE_PAGE_SIZE_INVALID, new Object[]{}, "pagination.page.size.invalid");
    } else if (listRequest.getPage() > 1 && listRequest.getPageSize() == 0) {
        bindingResult.reject(ERRCODE_NO_ITEM_ON_PAGE, new String[]{String.valueOf(listRequest.getPage())}, "pagination.item.empty");
        throw new ResourceNotFoundException(bindingResult);
    }
    if (null == type) {
        return;
    }
    if (!isValidField(listRequest.getSort(), type)) {
        bindingResult.reject(ERRCODE_SORTING_INVALID, new Object[]{listRequest.getSort()}, "sorting.sort.invalid");
    }
    if (listRequest.getFilters() != null) {
        List<String> attributes = Arrays.asList(listRequest.getFilters()).stream().filter(filter -> filter.getEntityAttr() == null)
                .map(filter -> filter.getAttributeName()).filter(attr -> !isValidField(attr, type)).collect(Collectors.toList());
        if (attributes.size() > 0) {
            bindingResult.reject(ERRCODE_FILTERING_ATTR_INVALID, new Object[]{attributes.get(0)}, "filtering.filter.attr.name.invalid");
        }

        if (Arrays.stream(FilterOperator.values())
                .map(FilterOperator::getValue)
                .noneMatch(op -> Arrays.stream(listRequest.getFilters())
                .map(Filter::getOperator)
                .anyMatch(op::equals))) {
            bindingResult.reject(ERRCODE_FILTERING_OP_INVALID, new Object[]{}, "filtering.filter.operation.invalid");
        }

        Arrays.stream(listRequest.getFilters())
                .filter(f -> getDateFilterKeys().contains(f.getAttribute()))
                .forEach(f -> {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(SystemConstants.API_DATE_FORMAT);
                        sdf.parse(f.getValue());
                    } catch (ParseException ex) {
                        bindingResult.reject(ERRCODE_FILTERING_OP_INVALID, new Object[]{f.getValue(), f.getAttribute()}, "filtering.filter.date.format.invalid");
                    }
                });
    }
    if (!Arrays.asList(directions).contains(listRequest.getDirection())) {
        bindingResult.reject(ERRCODE_DIRECTION_INVALID, new Object[]{}, "sorting.direction.invalid");
    }
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }

}