Search in sources :

Example 26 with ObjectError

use of org.springframework.validation.ObjectError in project spring-boot by spring-projects.

the class YamlConfigurationFactory method validate.

private void validate() throws BindException {
    BindingResult errors = new BeanPropertyBindingResult(this.configuration, "configuration");
    this.validator.validate(this.configuration, errors);
    if (errors.hasErrors()) {
        logger.error("YAML configuration failed validation");
        for (ObjectError error : errors.getAllErrors()) {
            logger.error(getErrorMessage(error));
        }
        throw new BindException(errors);
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ObjectError(org.springframework.validation.ObjectError) BindException(org.springframework.validation.BindException)

Example 27 with ObjectError

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

the class SpringValidatorAdapter method processConstraintViolations.

/**
	 * Process the given JSR-303 ConstraintViolations, adding corresponding errors to
	 * the provided Spring {@link Errors} object.
	 * @param violations the JSR-303 ConstraintViolation results
	 * @param errors the Spring errors object to register to
	 */
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = determineField(violation);
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = determineErrorCode(cd);
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs, violation.getMessage()));
                    } else {
                        Object rejectedValue = getRejectedValue(field, violation, bindingResult);
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, rejectedValue, false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex);
            }
        }
    }
}
Also used : BindingResult(org.springframework.validation.BindingResult) ObjectError(org.springframework.validation.ObjectError) NotReadablePropertyException(org.springframework.beans.NotReadablePropertyException) FieldError(org.springframework.validation.FieldError)

Example 28 with ObjectError

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

the class PayloadArgumentResolver method resolveArgument.

@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
    Payload ann = parameter.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.expression())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }
    Object payload = message.getPayload();
    if (isEmptyPayload(payload)) {
        if (ann == null || ann.required()) {
            String paramName = getParameterName(parameter);
            BindingResult bindingResult = new BeanPropertyBindingResult(payload, paramName);
            bindingResult.addError(new ObjectError(paramName, "Payload value must not be empty"));
            throw new MethodArgumentNotValidException(message, parameter, bindingResult);
        } else {
            return null;
        }
    }
    Class<?> targetClass = parameter.getParameterType();
    Class<?> payloadClass = payload.getClass();
    if (ClassUtils.isAssignable(targetClass, payloadClass)) {
        validate(message, parameter, payload);
        return payload;
    } else {
        if (this.converter instanceof SmartMessageConverter) {
            SmartMessageConverter smartConverter = (SmartMessageConverter) this.converter;
            payload = smartConverter.fromMessage(message, targetClass, parameter);
        } else {
            payload = this.converter.fromMessage(message, targetClass);
        }
        if (payload == null) {
            throw new MessageConversionException(message, "Cannot convert from [" + payloadClass.getName() + "] to [" + targetClass.getName() + "] for " + message);
        }
        validate(message, parameter, payload);
        return payload;
    }
}
Also used : SmartMessageConverter(org.springframework.messaging.converter.SmartMessageConverter) BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ObjectError(org.springframework.validation.ObjectError) MessageConversionException(org.springframework.messaging.converter.MessageConversionException) Payload(org.springframework.messaging.handler.annotation.Payload)

Example 29 with ObjectError

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

the class ValidatorFactoryTests method testSpringValidationWithClassLevel.

@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ObjectError(org.springframework.validation.ObjectError) Test(org.junit.Test)

Example 30 with ObjectError

use of org.springframework.validation.ObjectError in project opennms by OpenNMS.

the class DefaultDistributedPollerService method pauseLocationMonitor.

/**
 * {@inheritDoc}
 */
@Override
public void pauseLocationMonitor(LocationMonitorIdCommand command, BindingResult errors) {
    if (command == null) {
        throw new IllegalStateException("command argument cannot be null");
    }
    if (errors == null) {
        throw new IllegalStateException("errors argument cannot be null");
    }
    if (errors.hasErrors()) {
        return;
    }
    OnmsLocationMonitor monitor = m_locationMonitorDao.load(command.getMonitorId());
    if (monitor.getStatus() == MonitorStatus.PAUSED) {
        errors.addError(new ObjectError(MonitorStatus.class.getName(), new String[] { "distributed.locationMonitor.alreadyPaused" }, new Object[] { command.getMonitorId() }, "Location monitor " + command.getMonitorId() + " is already paused."));
        return;
    }
    monitor.setStatus(MonitorStatus.PAUSED);
    m_locationMonitorDao.update(monitor);
}
Also used : ObjectError(org.springframework.validation.ObjectError) OnmsLocationMonitor(org.opennms.netmgt.model.OnmsLocationMonitor)

Aggregations

ObjectError (org.springframework.validation.ObjectError)57 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 BindException (org.springframework.validation.BindException)10 FieldError (org.springframework.validation.FieldError)8 BusinessRuleException (org.mifos.service.BusinessRuleException)7 ModelAndView (org.springframework.web.servlet.ModelAndView)7 BindingResult (org.springframework.validation.BindingResult)6 DocumentBuilder (javax.xml.parsers.DocumentBuilder)5 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)5 Test (org.junit.Test)5 OnmsLocationMonitor (org.opennms.netmgt.model.OnmsLocationMonitor)5 LocationMonitorIdCommand (org.opennms.web.svclayer.model.LocationMonitorIdCommand)5 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)5 MapBindingResult (org.springframework.validation.MapBindingResult)5 Document (org.w3c.dom.Document)5 Element (org.w3c.dom.Element)5 ArrayList (java.util.ArrayList)3 Errors (org.springframework.validation.Errors)3 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)3 ServletException (javax.servlet.ServletException)2