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

The following examples show how to use org.springframework.validation.BeanPropertyBindingResult#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: ContentSettingsService.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ContentSettingsDto.Editor setEditor(String key) {
    Map<String,String> systemParams = getSystemParams();

    ContentSettingsDto.Editor editor = null;

    try {
        editor = ContentSettingsDto.Editor.fromValue(key);
    } catch (IllegalArgumentException ex) {
        BeanPropertyBindingResult errors = new BeanPropertyBindingResult(key, "contentSettings.editor");
        errors.reject(ERRCODE_INVALID_EDITOR, "plugins.jacms.contentsettings.error.invalidEditor");
        throw new ValidationGenericException(errors);
    }

    systemParams.put("hypertextEditor", editor.getKey());
    saveSystemParams(systemParams);

    return getEditor();
}
 
Example 2
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 3
Source File: WidgetValidatorCmsHelper.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void validateLink(WidgetConfigurationRequest widget, ILangManager langManager, IPageManager pageManager, BeanPropertyBindingResult errors) {
    String pageLink = extractConfigParam(widget, IContentListWidgetHelper.WIDGET_PARAM_PAGE_LINK);
    boolean existsPageLink = pageLink != null && pageManager.getDraftPage(pageLink) != null;
    String linkDescrParamPrefix = IContentListWidgetHelper.WIDGET_PARAM_PAGE_LINK_DESCR + "_";
    if (existsPageLink || isMultilanguageParamValued(widget, linkDescrParamPrefix, langManager)) {
        if (!existsPageLink) {
            errors.reject(ERRCODE_INVALID_CONFIGURATION, new String[]{pageLink}, widget.getCode() + ".pageLink.required");
        }
        Lang defaultLang = langManager.getDefaultLang();
        String defaultLinkDescrParam = linkDescrParamPrefix + defaultLang.getCode();
        String defaultLinkDescr = extractConfigParam(widget, defaultLinkDescrParam);
        if (defaultLinkDescr == null || defaultLinkDescr.length() == 0) {
            errors.reject(ERRCODE_INVALID_CONFIGURATION, new String[]{defaultLang.getDescr()}, widget.getCode() + ".defaultLangLink.required");
        }
    }
}
 
Example 4
Source File: PageModelService.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void validateDefaultWidgets(PageModelRequest pageModelRequest, BeanPropertyBindingResult bindingResult) {
    if (null == pageModelRequest || null == pageModelRequest.getConfiguration().getFrames()) {
        return;
    }
    List<PageModelFrameReq> frames = pageModelRequest.getConfiguration().getFrames();
    for (int i = 0; i < frames.size(); i++) {
        PageModelFrameReq frameReq = frames.get(i);
        DefaultWidgetReq dwr = frameReq.getDefaultWidget();
        if (null == dwr || null == dwr.getCode()) {
            continue;
        }
        WidgetType type = this.widgetTypeManager.getWidgetType(dwr.getCode());
        if (null == type) {
            bindingResult.reject(PageModelValidator.ERRCODE_DEFAULT_WIDGET_NOT_EXISTS, new Object[]{dwr.getCode(), i}, "pageModel.defaultWidget.notExists");
        } else if (null != dwr.getProperties()) {
            Iterator<String> iter = dwr.getProperties().keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                if (!type.hasParameter(key)) {
                    bindingResult.reject(PageModelValidator.ERRCODE_DEFAULT_WIDGET_INVALID_PARAMETER, new Object[]{key, dwr.getCode(), i}, "pageModel.defaultWidget.invalidParameter");
                }
            }
        }
    }
}
 
Example 5
Source File: ContentSettingsService.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validateCropRatio(List<String> cropRatios, String ratio) {
    final BeanPropertyBindingResult errors = new BeanPropertyBindingResult(ratio, "contentSettings.ratio");

    String[] split = Optional.ofNullable(ratio)
            .orElseThrow(() -> {
                errors.reject(ERRCODE_INVALID_CROP_RATIO, "plugins.jacms.contentsettings.error.cropRatio.invalid");
                return new ValidationGenericException(errors);
            })
            .split(":");

    if (split.length != 2) {
        errors.reject(ERRCODE_INVALID_CROP_RATIO, "plugins.jacms.contentsettings.error.cropRatio.invalid");
        throw new ValidationGenericException(errors);
    }

    try {
        Integer.valueOf(split[0]);
        Integer.valueOf(split[1]);
    } catch (NumberFormatException e) {
        errors.reject(ERRCODE_INVALID_CROP_RATIO, "plugins.jacms.contentsettings.error.cropRatio.invalid");
        throw new ValidationGenericException(errors);
    }
}
 
Example 6
Source File: DatabaseService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public byte[] getTableDump(String reportCode, String dataSource, String tableName) {
    File tempFile = null;
    byte[] bytes = null;
    try {
        InputStream stream = this.getDatabaseManager().getTableDump(tableName, dataSource, reportCode);
        if (null == stream) {
            logger.warn("no dump found with code {}, dataSource {}, table {}", reportCode, dataSource, tableName);
            BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(tableName, "tableName");
            bindingResult.reject(DatabaseValidator.ERRCODE_NO_TABLE_DUMP_FOUND, new Object[]{reportCode, dataSource, tableName}, "database.dump.table.notFound");
            throw new ResourceNotFoundException("code - dataSource - table",
                    "'" + reportCode + "' - '" + dataSource + "' - '" + tableName + "'");
        }
        tempFile = FileTextReader.createTempFile(new Random().nextInt(100) + reportCode + "_" + dataSource + "_" + tableName, stream);
        bytes = FileTextReader.fileToByteArray(tempFile);
    } catch (ResourceNotFoundException r) {
        throw r;
    } catch (Throwable t) {
        logger.error("error extracting database dump with code {}, dataSource {}, table {}", reportCode, dataSource, tableName, t);
        throw new RestServerError("error extracting database dump", t);
    } finally {
        if (null != tempFile) {
            boolean deleted = tempFile.delete();
            if (!deleted) {
                logger.warn("Failed to create temp file {}", tempFile.getAbsolutePath());
            }
        }
    }
    return bytes;
}
 
Example 7
Source File: PageService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public PageDto movePage(String pageCode, PagePositionRequest pageRequest) {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(pageCode, "page");
    if (pageCode.equals(pageRequest.getParentCode())) {
        bindingResult.reject(PageValidator.ERRCODE_INVALID_PARENT, new String[]{pageCode}, "page.movement.parent.invalid.1");
        throw new ValidationGenericException(bindingResult);
    }
    IPage parent = this.getPageManager().getDraftPage(pageRequest.getParentCode());
    IPage page = this.getPageManager().getDraftPage(pageCode);
    if (parent.isChildOf(pageCode, this.getPageManager())) {
        bindingResult.reject(PageValidator.ERRCODE_INVALID_PARENT,
                new String[]{pageRequest.getParentCode(), pageCode}, "page.movement.parent.invalid.2");
        throw new ValidationGenericException(bindingResult);
    }
    int iterations = Math.abs(page.getPosition() - pageRequest.getPosition());
    boolean moveUp = page.getPosition() > pageRequest.getPosition();
    try {
        if (page.getParentCode().equals(parent.getCode())) {
            while (iterations-- > 0 && this.getPageManager().movePage(pageCode, moveUp));
        } else {
            this.getPageManager().movePage(page, parent);
        }
        page = this.getPageManager().getDraftPage(pageCode);
    } catch (ApsSystemException e) {
        logger.error("Error moving page {}", pageCode, e);
        throw new RestServerError("error in moving page", e);
    }
    return this.getDtoBuilder().convert(page);
}
 
Example 8
Source File: LanguageService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected BeanPropertyBindingResult validateDisable(Lang lang) {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(lang, "lang");
    if (lang.isDefault()) {
        bindingResult.reject(LanguageValidator.ERRCODE_LANGUAGE_CANNOT_DISABLE_DEFAULT, new Object[]{lang.getCode(), lang.getDescr()}, "language.cannot.disable.default");
    }
    return bindingResult;

}
 
Example 9
Source File: ResourcesVersioningService.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ResourceDTO convertResourceToDto(ResourceInterface resource) {

        String type = extractTypeFromResource(resource.getType());

        if (FileResourceDTO.RESOURCE_TYPE.equals(type)) {
            return convertResourceToFileResourceDto((AttachResource) resource);
        } else if (ImageResourceDTO.RESOURCE_TYPE.equals(type)) {
            return convertResourceToImageResourceDto((ImageResource) resource);
        } else {
            logger.error("Resource type not supported");
            BeanPropertyBindingResult errors = new BeanPropertyBindingResult(type, "resources.file.type");
            errors.reject(ERRCODE_INVALID_RESOURCE_TYPE, "plugins.jacms.resources.invalidResourceType");
            throw new ValidationGenericException(errors);
        }
    }
 
Example 10
Source File: ResourcesService.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public AssetDto convertResourceToDto(ResourceInterface resource) {
    String type = unconvertResourceType(resource.getType());

    if (ImageAssetDto.RESOURCE_TYPE.equals(type)) {
        return convertImageResourceToDto((ImageResource) resource);
    } else if (FileAssetDto.RESOURCE_TYPE.equals(type)) {
        return convertFileResourceToDto((AttachResource) resource);
    } else {
        log.error("Resource type not allowed");
        BeanPropertyBindingResult errors = new BeanPropertyBindingResult(type, "resources.file.type");
        errors.reject(ERRCODE_INVALID_RESOURCE_TYPE, "plugins.jacms.resources.invalidResourceType");
        throw new ValidationGenericException(errors);
    }
}
 
Example 11
Source File: ContentSettingsService.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateCropRatioNotExists(List<String> cropRatios, String ratio) {
    final BeanPropertyBindingResult errors = new BeanPropertyBindingResult(ratio, "contentSettings.ratio");

    if (cropRatios.contains(ratio)) {
        errors.reject(ERRCODE_CONFLICT_CROP_RATIO, "plugins.jacms.contentsettings.error.cropRatio.conflict");
        throw new ValidationConflictException(errors);
    }
}
 
Example 12
Source File: ResourcesService.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateGroup(UserDetails user, String group) {
    List<Group> groups = authorizationManager.getGroupsByPermission(user, PERMISSION_MANAGE_RESOURCES);

    for(Group g : groups) {
        if (g.getAuthority().equals(group)) {
            return;
        }
    }

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(group, "resources.group");
    errors.reject(ERRCODE_GROUP_NOT_FOUND, "plugins.jacms.group.error.notFound");
    throw new ValidationGenericException(errors);
}
 
Example 13
Source File: ContentModelServiceImpl.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected BeanPropertyBindingResult validateForDelete(ContentModel contentModel) throws ApsSystemException {
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(contentModel, "contentModel");
    List<ContentModelReference> references = this.contentModelManager.getContentModelReferences(contentModel.getId());
    if (!references.isEmpty()) {
        errors.reject(ContentModelValidator.ERRCODE_CONTENTMODEL_REFERENCES, null, "contentmodel.page.references");
    }
    final List<SmallEntityType> defaultContentTemplateUsedList = this.contentManager.getSmallEntityTypes().stream()
            .filter(
                    f -> {
                        final String defaultModel = contentManager.getDefaultModel(f.getCode());
                        final boolean defaultModelUsed = String.valueOf(contentModel.getId())
                                .equals(defaultModel);
                        final String listModel = contentManager.getListModel(f.getCode());
                        final boolean listModelUsed = String.valueOf(contentModel.getId())
                                .equals(listModel);
                        return (defaultModelUsed || listModelUsed);
                    }
            ).collect(Collectors.toList());

    if (defaultContentTemplateUsedList.size()>0){
        ArrayList defList = new ArrayList();
        defaultContentTemplateUsedList.stream().forEach(f->defList.add(f.getCode()));
        final String defListString = String.join(", ", defList);
        ArrayList args = new ArrayList();
        args.add(defListString);
        errors.reject(ContentModelValidator.ERRCODE_CONTENTMODEL_METADATA_REFERENCES, args.toArray(), "contentmodel.defaultMetadata.references");
    }
    return errors;
}
 
Example 14
Source File: PageModelService.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected BeanPropertyBindingResult validateDelete(PageModel pageModel) throws ApsSystemException {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(pageModel, "pageModel");
    Map<String, List<Object>> references = this.getReferencingObjects(pageModel);
    if (references.size() > 0) {
        bindingResult.reject(PageModelValidator.ERRCODE_PAGEMODEL_REFERENCES, new Object[]{pageModel.getCode(), references}, "pageModel.cannot.delete.references");
    }
    return bindingResult;
}
 
Example 15
Source File: ContentListViewerWidgetValidator.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void validateFilters(WidgetConfigurationRequest widget, BeanPropertyBindingResult errors) {
    WidgetType type = this.getWidgetTypeManager().getWidgetType(widget.getCode());
    Map<String, Object> config = (Map<String, Object>) widget.getConfig();
    if (null != config
            && null != type
            && type.hasParameter(WIDGET_CONFIG_KEY_CATEGORIES)
            && type.hasParameter(WIDGET_CONFIG_KEY_MAXELEMFORITEM)
            && type.hasParameter(WIDGET_CONFIG_KEY_MAXELEMENTS)
            && StringUtils.isNotEmpty((String) config.get(WIDGET_CONFIG_KEY_CONTENTTYPE))
            && StringUtils.isEmpty((String) config.get(WIDGET_CONFIG_KEY_MAXELEMFORITEM))
            && StringUtils.isEmpty((String) config.get(WIDGET_CONFIG_KEY_MAXELEMENTS))) {
        errors.reject(WidgetValidatorCmsHelper.ERRCODE_INVALID_CONFIGURATION, new String[]{}, WIDGET_CODE + ".parameters.invalid");
    }
}
 
Example 16
Source File: WidgetValidatorCmsHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void validateContentModel(String widgetCode, String typeCode, String modelId, IContentModelManager contentModelManager, BeanPropertyBindingResult errors) {
    if (null == modelId) {
        //the model id can be null, default model will be used
        return;
    }
    List<String> contentModels = contentModelManager.getModelsForContentType(typeCode).stream().map(i -> String.valueOf(i.getId())).collect(Collectors.toList());
    contentModels.add("list");
    contentModels.add("default");
    if (!contentModels.contains(modelId)) {
        errors.reject(WidgetValidatorCmsHelper.ERRCODE_INVALID_CONFIGURATION, new String[]{modelId, typeCode}, widgetCode + ".contentmodel.invalid");
    }
}
 
Example 17
Source File: AbstractPaginationValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void validateRestListResult(RestListRequest listRequest, PagedMetadata<?> result) {
    if (listRequest.getPage() > 1 && (null == result.getBody() || result.getBody().isEmpty())) {
        BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(listRequest, "listRequest");
        bindingResult.reject(ERRCODE_NO_ITEM_ON_PAGE, new String[]{String.valueOf(listRequest.getPage())}, "pagination.item.empty");
        throw new ResourceNotFoundException(bindingResult);
    }
}
 
Example 18
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);
    }

}
 
Example 19
Source File: ContentModelServiceImpl.java    From entando-components with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected void validateContentType(String contentType, BeanPropertyBindingResult errors) {
    if (!this.contentManager.getSmallContentTypesMap().containsKey(contentType)) {
        Object[] args = {contentType};
        errors.reject(ContentModelValidator.ERRCODE_CONTENTMODEL_TYPECODE_NOT_FOUND, args, "contentmodel.contentType.notFound");
    }
}
 
Example 20
Source File: RoleService.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected void validateCodeExists(Role role, BeanPropertyBindingResult errors) {
    if (null != roleManager.getRole(role.getName())) {
        errors.reject(RoleValidator.ERRCODE_ROLE_ALREADY_EXISTS, new String[]{role.getName()}, "role.exists");
    }
}