Search in sources :

Example 1 with BeanDescriptor

use of jakarta.validation.metadata.BeanDescriptor in project minijax by minijax.

the class MinijaxValidator method validate.

@Override
public <T> Set<ConstraintViolation<T>> validate(final T object, final Class<?>... groups) {
    final MinijaxConstraintValidatorContext<T> context = new MinijaxConstraintValidatorContext<>(object);
    final BeanDescriptor descriptor = getConstraintsForClass(object.getClass());
    for (final PropertyDescriptor propertyDescriptor : descriptor.getConstrainedProperties()) {
        final Object value = ((MinijaxPropertyDescriptor) propertyDescriptor).getValue(object);
        validateProperty(context, propertyDescriptor, value);
    }
    return context.getResult();
}
Also used : MinijaxPropertyDescriptor(org.minijax.validation.metadata.MinijaxPropertyDescriptor) PropertyDescriptor(jakarta.validation.metadata.PropertyDescriptor) MinijaxPropertyDescriptor(org.minijax.validation.metadata.MinijaxPropertyDescriptor) BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) MinijaxBeanDescriptor(org.minijax.validation.metadata.MinijaxBeanDescriptor)

Example 2 with BeanDescriptor

use of jakarta.validation.metadata.BeanDescriptor in project myfaces by apache.

the class BeanValidator method validate.

/**
 * {@inheritDoc}
 */
@Override
public void validate(final FacesContext context, final UIComponent component, final Object value) {
    Assert.notNull(context, "context");
    Assert.notNull(component, "component");
    ValueExpression valueExpression = component.getValueExpression("value");
    if (valueExpression == null) {
        log.warning("cannot validate component with empty value: " + component.getClientId(context));
        return;
    }
    // Obtain a reference to the to-be-validated object and the property name.
    ValueReference reference = ValueReferenceResolver.resolve(valueExpression, context);
    if (reference == null) {
        return;
    }
    Object base = reference.getBase();
    if (base == null) {
        return;
    }
    Class<?> valueBaseClass = base.getClass();
    if (valueBaseClass == null) {
        return;
    }
    Object referenceProperty = reference.getProperty();
    if (!(referenceProperty instanceof String)) {
        // can exit bean validation here
        return;
    }
    String valueProperty = (String) referenceProperty;
    // Initialize Bean Validation.
    ValidatorFactory validatorFactory = createValidatorFactory(context);
    jakarta.validation.Validator validator = createValidator(validatorFactory, context);
    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(valueBaseClass);
    if (!beanDescriptor.isBeanConstrained()) {
        return;
    }
    // Note that validationGroupsArray was initialized when createValidator was called
    Class[] validationGroupsArray = this.validationGroupsArray;
    // JSF 2.3: If the ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME application parameter is enabled and this Validator
    // instance has validation groups other than or in addition to the Default group
    boolean containsOtherValidationGroup = false;
    if (validationGroupsArray != null && validationGroupsArray.length > 0) {
        for (Class<?> clazz : validationGroupsArray) {
            if (!Default.class.equals(clazz)) {
                containsOtherValidationGroup = true;
                break;
            }
        }
    }
    // Delegate to Bean Validation.
    Set<?> constraintViolations = validator.validateValue(valueBaseClass, valueProperty, value, validationGroupsArray);
    if (!constraintViolations.isEmpty()) {
        Set<FacesMessage> messages = new LinkedHashSet<>(constraintViolations.size());
        for (Object violation : constraintViolations) {
            ConstraintViolation constraintViolation = (ConstraintViolation) violation;
            String message = constraintViolation.getMessage();
            Object[] args = new Object[] { message, MessageUtils.getLabel(context, component) };
            FacesMessage msg = MessageUtils.getErrorMessage(context, MESSAGE_ID, args);
            messages.add(msg);
        }
        if (isValidateWholeBeanEnabled(context) && containsOtherValidationGroup) {
            // JSF 2.3: record the fact that this field failed validation so that any <f:validateWholeBean />
            // component later in the tree is able to skip class-level validation for the bean for which this
            // particular field is a property. Regardless of whether or not
            // ENABLE_VALIDATE_WHOLE_BEAN_PARAM_NAME is set, throw the new exception.
            context.getViewRoot().getTransientStateHelper().putTransient(BEAN_VALIDATION_FAILED, Boolean.TRUE);
        }
        throw new ValidatorException(messages);
    } else {
        // Default group
        if (isValidateWholeBeanEnabled(context) && containsOtherValidationGroup) {
            // record the fact that this field passed validation so that any <f:validateWholeBean /> component
            // later in the tree is able to allow class-level validation for the bean for which this particular
            // field is a property.
            Map<String, Object> candidatesMap = (Map<String, Object>) context.getViewRoot().getTransientStateHelper().getTransient(CANDIDATE_COMPONENT_VALUES_MAP);
            if (candidatesMap == null) {
                candidatesMap = new LinkedHashMap<>();
                context.getViewRoot().getTransientStateHelper().putTransient(CANDIDATE_COMPONENT_VALUES_MAP, candidatesMap);
            }
            candidatesMap.put(component.getClientId(context), value);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ValidatorFactory(jakarta.validation.ValidatorFactory) Default(jakarta.validation.groups.Default) BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) ValueExpression(jakarta.el.ValueExpression) ConstraintViolation(jakarta.validation.ConstraintViolation) FacesMessage(jakarta.faces.application.FacesMessage) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ValueReference(jakarta.el.ValueReference)

Example 3 with BeanDescriptor

use of jakarta.validation.metadata.BeanDescriptor in project hibernate-validator by hibernate.

the class ValidationExtension method determineConstrainedCallables.

private <T> Set<AnnotatedCallable<? super T>> determineConstrainedCallables(AnnotatedType<T> type) {
    Set<AnnotatedCallable<? super T>> callables = new HashSet<>();
    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(type.getJavaClass());
    determineConstrainedConstructors(type, beanDescriptor, callables);
    determineConstrainedMethods(type, beanDescriptor, callables);
    return callables;
}
Also used : BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) AnnotatedCallable(jakarta.enterprise.inject.spi.AnnotatedCallable) HashSet(java.util.HashSet)

Example 4 with BeanDescriptor

use of jakarta.validation.metadata.BeanDescriptor in project hibernate-validator by hibernate.

the class MessageInterpolatorContextTest method testContextWithRightDescriptorAndValueAndRootBeanClassIsPassedToMessageInterpolator.

@Test
@TestForIssue(jiraKey = "HV-333")
public void testContextWithRightDescriptorAndValueAndRootBeanClassIsPassedToMessageInterpolator() {
    // use a easy mock message interpolator for verifying that the right MessageInterpolatorContext
    // will be passed
    MessageInterpolator mock = createMock(MessageInterpolator.class);
    Configuration<?> config = ValidatorUtil.getConfiguration().messageInterpolator(mock);
    Validator validator = config.buildValidatorFactory().getValidator();
    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(TestBean.class);
    PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty("test");
    Set<ConstraintDescriptor<?>> constraintDescriptors = propertyDescriptor.getConstraintDescriptors();
    assertTrue(constraintDescriptors.size() == 1);
    // prepare the mock interpolator to expect the right interpolate call
    String validatedValue = "value";
    expect(mock.interpolate(MESSAGE, new MessageInterpolatorContext(constraintDescriptors.iterator().next(), validatedValue, TestBean.class, null, Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), ExpressionLanguageFeatureLevel.BEAN_METHODS, false))).andReturn("invalid");
    replay(mock);
    Set<ConstraintViolation<TestBean>> violations = validator.validate(new TestBean(validatedValue));
    assertThat(violations).containsOnlyViolations(violationOf(Size.class).withMessage("invalid"));
    // verify that the right context was passed
    verify(mock);
}
Also used : PropertyDescriptor(jakarta.validation.metadata.PropertyDescriptor) MessageInterpolatorContext(org.hibernate.validator.internal.engine.MessageInterpolatorContext) HibernateMessageInterpolatorContext(org.hibernate.validator.messageinterpolation.HibernateMessageInterpolatorContext) BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) ConstraintDescriptor(jakarta.validation.metadata.ConstraintDescriptor) ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ResourceBundleMessageInterpolator(org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator) MessageInterpolator(jakarta.validation.MessageInterpolator) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) TestForIssue(org.hibernate.validator.testutil.TestForIssue)

Example 5 with BeanDescriptor

use of jakarta.validation.metadata.BeanDescriptor in project hibernate-validator by hibernate.

the class IgnoreCrossParameterConstraintTest method testCrossParameterConstraintsAreIgnored.

@Test
@TestForIssue(jiraKey = "HV-734")
public void testCrossParameterConstraintsAreIgnored() {
    Validator validator = getXmlConfiguredValidator("ignore-annotations-for-cross-parameter-constraints.xml");
    BeanDescriptor beanDescriptor = validator.getConstraintsForClass(this.getClass());
    // check that the test constructor has no cross parameter constraint
    ConstructorDescriptor constructorDescriptor = beanDescriptor.getConstraintsForConstructor(String.class, String.class);
    CrossParameterDescriptor crossParameterDescriptor = constructorDescriptor.getCrossParameterDescriptor();
    assertFalse(crossParameterDescriptor.hasConstraints(), "There should be no cross parameter constraints.");
    // check that the test method has no cross parameter constraint
    MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod("snafu", String.class, String.class);
    crossParameterDescriptor = methodDescriptor.getCrossParameterDescriptor();
    assertFalse(crossParameterDescriptor.hasConstraints(), "There should be no cross parameter constraints.");
}
Also used : BeanDescriptor(jakarta.validation.metadata.BeanDescriptor) ConstructorDescriptor(jakarta.validation.metadata.ConstructorDescriptor) CrossParameterDescriptor(jakarta.validation.metadata.CrossParameterDescriptor) MethodDescriptor(jakarta.validation.metadata.MethodDescriptor) Validator(jakarta.validation.Validator) ConstraintValidator(jakarta.validation.ConstraintValidator) Test(org.testng.annotations.Test) TestForIssue(org.hibernate.validator.testutil.TestForIssue)

Aggregations

BeanDescriptor (jakarta.validation.metadata.BeanDescriptor)61 Test (org.testng.annotations.Test)41 ValidatorUtil.getBeanDescriptor (org.hibernate.validator.testutils.ValidatorUtil.getBeanDescriptor)31 MethodDescriptor (jakarta.validation.metadata.MethodDescriptor)14 PropertyDescriptor (jakarta.validation.metadata.PropertyDescriptor)13 ConstraintDescriptor (jakarta.validation.metadata.ConstraintDescriptor)10 Test (org.junit.Test)10 Validator (jakarta.validation.Validator)7 ConstructorDescriptor (jakarta.validation.metadata.ConstructorDescriptor)7 CrossParameterDescriptor (jakarta.validation.metadata.CrossParameterDescriptor)7 TestForIssue (org.hibernate.validator.testutil.TestForIssue)7 ConstraintValidator (jakarta.validation.ConstraintValidator)3 ConstraintViolation (jakarta.validation.ConstraintViolation)3 ValidatorFactory (jakarta.validation.ValidatorFactory)3 ParameterDescriptor (jakarta.validation.metadata.ParameterDescriptor)3 ReturnValueDescriptor (jakarta.validation.metadata.ReturnValueDescriptor)3 ValueExpression (jakarta.el.ValueExpression)2 FacesMessage (jakarta.faces.application.FacesMessage)2 Default (jakarta.validation.groups.Default)2 LinkedHashSet (java.util.LinkedHashSet)2