Search in sources :

Example 66 with BindingResult

use of org.springframework.validation.BindingResult in project alf.io by alfio-event.

the class AdditionalServiceApiController method insert.

@PostMapping(value = "/event/{eventId}/additional-services")
@Transactional
public ResponseEntity<EventModification.AdditionalService> insert(@PathVariable("eventId") int eventId, @RequestBody EventModification.AdditionalService additionalService, BindingResult bindingResult) {
    ValidationResult validationResult = Validator.validateAdditionalService(additionalService, bindingResult);
    Validate.isTrue(validationResult.isSuccess(), "validation failed");
    return eventRepository.findOptionalById(eventId).map(event -> ResponseEntity.ok(eventManager.insertAdditionalService(event, additionalService))).orElseThrow(IllegalArgumentException::new);
}
Also used : PriceContainer(alfio.model.PriceContainer) ValidationResult(alfio.model.result.ValidationResult) ExportUtils(alfio.util.ExportUtils) RequiredArgsConstructor(lombok.RequiredArgsConstructor) BindingResult(org.springframework.validation.BindingResult) EventModification(alfio.model.modification.EventModification) Objects.requireNonNullElse(java.util.Objects.requireNonNullElse) BigDecimal(java.math.BigDecimal) Map(java.util.Map) AdditionalServiceManager(alfio.manager.AdditionalServiceManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) EventRepository(alfio.repository.EventRepository) Validator(alfio.util.Validator) Collectors(java.util.stream.Collectors) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) EventManager(alfio.manager.EventManager) AdditionalService(alfio.model.AdditionalService) Validate(org.apache.commons.lang3.Validate) Principal(java.security.Principal) Stream(java.util.stream.Stream) MonetaryUtil(alfio.util.MonetaryUtil) DateTimeFormatter(java.time.format.DateTimeFormatter) Log4j2(lombok.extern.log4j.Log4j2) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) Event(alfio.model.Event) Collections(java.util.Collections) Transactional(org.springframework.transaction.annotation.Transactional) ValidationResult(alfio.model.result.ValidationResult) Transactional(org.springframework.transaction.annotation.Transactional)

Example 67 with BindingResult

use of org.springframework.validation.BindingResult in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Example 68 with BindingResult

use of org.springframework.validation.BindingResult in project grails-core by grails.

the class AbstractConstraint method rejectValueWithDefaultMessage.

public void rejectValueWithDefaultMessage(Object target, Errors errors, String defaultMessage, String[] codes, Object[] args) {
    BindingResult result = (BindingResult) errors;
    Set<String> newCodes = new LinkedHashSet<String>();
    if (args.length > 1 && messageSource != null) {
        if ((args[0] instanceof String) && (args[1] instanceof Class<?>)) {
            final Locale locale = LocaleContextHolder.getLocale();
            final Class<?> constrainedClass = (Class<?>) args[1];
            final String fullClassName = constrainedClass.getName();
            String classNameCode = fullClassName + ".label";
            String resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            final String classAsPropertyName = GrailsNameUtils.getPropertyName(constrainedClass);
            if (resolvedClassName.equals(fullClassName)) {
                // try short version
                classNameCode = classAsPropertyName + ".label";
                resolvedClassName = messageSource.getMessage(classNameCode, null, fullClassName, locale);
            }
            // update passed version
            if (!resolvedClassName.equals(fullClassName)) {
                args[1] = resolvedClassName;
            }
            String propertyName = (String) args[0];
            String propertyNameCode = fullClassName + '.' + propertyName + ".label";
            String resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            if (resolvedPropertyName.equals(propertyName)) {
                propertyNameCode = classAsPropertyName + '.' + propertyName + ".label";
                resolvedPropertyName = messageSource.getMessage(propertyNameCode, null, propertyName, locale);
            }
            // update passed version
            if (!resolvedPropertyName.equals(propertyName)) {
                args[0] = resolvedPropertyName;
            }
        }
    }
    //Qualified class name is added first to match before unqualified class (which is still resolved for backwards compatibility)
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + getName() + ".error", constraintPropertyName)));
    newCodes.addAll(Arrays.asList(result.resolveMessageCodes(classShortName + '.' + constraintPropertyName + '.' + getName() + ".error", constraintPropertyName)));
    for (String code : codes) {
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(constraintOwningClass.getName() + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(classShortName + '.' + constraintPropertyName + '.' + code, constraintPropertyName)));
        //We resolve the error code on it's own last so that a global code doesn't override a class/field specific error
        newCodes.addAll(Arrays.asList(result.resolveMessageCodes(code, constraintPropertyName)));
    }
    FieldError error = new FieldError(errors.getObjectName(), errors.getNestedPath() + constraintPropertyName, getPropertyValue(errors, target), false, newCodes.toArray(new String[newCodes.size()]), args, defaultMessage);
    ((BindingResult) errors).addError(error);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Locale(java.util.Locale) BindingResult(org.springframework.validation.BindingResult) FieldError(org.springframework.validation.FieldError)

Example 69 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class ModelResultMatchers method attributeHasFieldErrorCode.

/**
	 * Assert a field error code for a model attribute using a {@link org.hamcrest.Matcher}.
	 * @since 4.1
	 */
public <T> ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final Matcher<? super String> matcher) {
    return new ResultMatcher() {

        @Override
        public void match(MvcResult mvcResult) throws Exception {
            ModelAndView mav = getModelAndView(mvcResult);
            BindingResult result = getBindingResult(mav, name);
            assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
            boolean hasFieldErrors = result.hasFieldErrors(fieldName);
            assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);
            String code = result.getFieldError(fieldName).getCode();
            assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
        }
    };
}
Also used : BindingResult(org.springframework.validation.BindingResult) ModelAndView(org.springframework.web.servlet.ModelAndView) ResultMatcher(org.springframework.test.web.servlet.ResultMatcher) MvcResult(org.springframework.test.web.servlet.MvcResult)

Example 70 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class ModelResultMatchers method attributeHasErrors.

/**
	 * Assert the given model attribute(s) have errors.
	 */
public ResultMatcher attributeHasErrors(final String... names) {
    return new ResultMatcher() {

        @Override
        public void match(MvcResult mvcResult) throws Exception {
            ModelAndView mav = getModelAndView(mvcResult);
            for (String name : names) {
                BindingResult result = getBindingResult(mav, name);
                assertTrue("No errors for attribute [" + name + "]", result.hasErrors());
            }
        }
    };
}
Also used : BindingResult(org.springframework.validation.BindingResult) ModelAndView(org.springframework.web.servlet.ModelAndView) ResultMatcher(org.springframework.test.web.servlet.ResultMatcher) MvcResult(org.springframework.test.web.servlet.MvcResult)

Aggregations

BindingResult (org.springframework.validation.BindingResult)143 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)28 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)24 List (java.util.List)23 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)23 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)21 ResponseEntity (org.springframework.http.ResponseEntity)20 Collectors (java.util.stream.Collectors)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 FieldError (org.springframework.validation.FieldError)18 ObjectError (org.springframework.validation.ObjectError)17 Model (org.springframework.ui.Model)15 ControllerAdvice (org.springframework.web.bind.annotation.ControllerAdvice)14 HashMap (java.util.HashMap)13 Nonnull (javax.annotation.Nonnull)13 Nullable (javax.annotation.Nullable)13 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)13 DefaultProblem (org.zalando.problem.DefaultProblem)13 Problem (org.zalando.problem.Problem)13