Search in sources :

Example 1 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project spring-framework by spring-projects.

the class MethodValidationInterceptor method invoke.

@Override
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
    // Avoid Validator invocation on FactoryBean.getObjectType/isSingleton
    if (isFactoryBeanMetadataMethod(invocation.getMethod())) {
        return invocation.proceed();
    }
    Class<?>[] groups = determineValidationGroups(invocation);
    // Standard Bean Validation 1.1 API
    ExecutableValidator execVal = this.validator.forExecutables();
    Method methodToValidate = invocation.getMethod();
    Set<ConstraintViolation<Object>> result;
    Object target = invocation.getThis();
    Assert.state(target != null, "Target must not be null");
    try {
        result = execVal.validateParameters(target, methodToValidate, invocation.getArguments(), groups);
    } catch (IllegalArgumentException ex) {
        // Probably a generic type mismatch between interface and impl as reported in SPR-12237 / HV-1011
        // Let's try to find the bridged method on the implementation class...
        methodToValidate = BridgeMethodResolver.findBridgedMethod(ClassUtils.getMostSpecificMethod(invocation.getMethod(), target.getClass()));
        result = execVal.validateParameters(target, methodToValidate, invocation.getArguments(), groups);
    }
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }
    Object returnValue = invocation.proceed();
    result = execVal.validateReturnValue(target, methodToValidate, returnValue, groups);
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }
    return returnValue;
}
Also used : ExecutableValidator(jakarta.validation.executable.ExecutableValidator) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) Method(java.lang.reflect.Method) Nullable(org.springframework.lang.Nullable)

Example 2 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project spring-framework by spring-projects.

the class ValidatorFactoryTests method testSimpleValidationWithCustomProvider.

@Test
public void testSimpleValidationWithCustomProvider() {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.setProviderClass(HibernateValidator.class);
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
    assertThat(result.size()).isEqualTo(2);
    for (ConstraintViolation<ValidPerson> cv : result) {
        String path = cv.getPropertyPath().toString();
        assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual));
        assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class);
    }
    Validator nativeValidator = validator.unwrap(Validator.class);
    assertThat(nativeValidator.getClass().getName().startsWith("org.hibernate")).isTrue();
    assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class);
    assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class);
    validator.destroy();
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintValidator(jakarta.validation.ConstraintValidator) HibernateValidator(org.hibernate.validator.HibernateValidator) Test(org.junit.jupiter.api.Test)

Example 3 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project wicket by apache.

the class DefaultPropertyResolverTest method testBundleKeysResolution.

/**
 * Test custom bundle mechanism of jsr 303
 *
 * https://issues.apache.org/jira/browse/WICKET-5654
 *
 * @throws Exception
 */
@Test
void testBundleKeysResolution() throws Exception {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    DefaultViolationTranslator translator = new DefaultViolationTranslator();
    // test with a too short password
    BeanWithPassword bean = new BeanWithPassword("short");
    Set<ConstraintViolation<BeanWithPassword>> constraintViolations = validator.validate(bean);
    assertEquals(1, constraintViolations.size());
    @SuppressWarnings("unchecked") ConstraintViolation<BeanWithPassword> shortViolation = (ConstraintViolation<BeanWithPassword>) constraintViolations.toArray()[0];
    ValidationError error = translator.convert(shortViolation);
    checkErrorBundleKeys(error, DEFAULT_BUNDLE_KEY + ".String", DEFAULT_BUNDLE_KEY);
    // test with a password containing non-word chars
    bean.setPassword("notWord&%$£");
    constraintViolations = validator.validate(bean);
    assertEquals(1, constraintViolations.size());
    @SuppressWarnings("unchecked") ConstraintViolation<BeanWithPassword> nonWordviolation = (ConstraintViolation<BeanWithPassword>) constraintViolations.toArray()[0];
    error = translator.convert(nonWordviolation);
    checkErrorBundleKeys(error, CUSTOM_BUNDLE_KEY + ".String", CUSTOM_BUNDLE_KEY, DEFAULT_BUNDLE_KEY + ".String", DEFAULT_BUNDLE_KEY);
    // test with a valid password
    bean.setPassword("aValidPassword1234");
    constraintViolations = validator.validate(bean);
    assertEquals(0, constraintViolations.size());
}
Also used : ValidatorFactory(jakarta.validation.ValidatorFactory) ConstraintViolation(jakarta.validation.ConstraintViolation) ValidationError(org.apache.wicket.validation.ValidationError) Validator(jakarta.validation.Validator) Test(org.junit.jupiter.api.Test)

Example 4 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project spring-cloud-config by spring-cloud.

the class SshPropertyValidatorTest method hostKeyWithMissingAlgoFails.

@Test
public void hostKeyWithMissingAlgoFails() throws Exception {
    MultipleJGitEnvironmentProperties missingAlgo = new MultipleJGitEnvironmentProperties();
    missingAlgo.setUri(SSH_URI);
    missingAlgo.setIgnoreLocalSshSettings(true);
    missingAlgo.setPrivateKey(VALID_PRIVATE_KEY);
    missingAlgo.setHostKey("some_host");
    Set<ConstraintViolation<MultipleJGitEnvironmentProperties>> constraintViolations = validator.validate(missingAlgo);
    assertThat(constraintViolations).hasSize(1);
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) MultipleJGitEnvironmentProperties(org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties) Test(org.junit.Test)

Example 5 with ConstraintViolation

use of jakarta.validation.ConstraintViolation in project spring-cloud-config by spring-cloud.

the class SshPropertyValidatorTest method validatorNotRunIfIgnoreLocalSettingsFalse.

@Test
public void validatorNotRunIfIgnoreLocalSettingsFalse() throws Exception {
    MultipleJGitEnvironmentProperties useLocal = new MultipleJGitEnvironmentProperties();
    useLocal.setUri(SSH_URI);
    useLocal.setIgnoreLocalSshSettings(false);
    useLocal.setPrivateKey("invalid_key");
    Set<ConstraintViolation<MultipleJGitEnvironmentProperties>> constraintViolations = validator.validate(useLocal);
    assertThat(constraintViolations).hasSize(0);
}
Also used : ConstraintViolation(jakarta.validation.ConstraintViolation) MultipleJGitEnvironmentProperties(org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties) Test(org.junit.Test)

Aggregations

ConstraintViolation (jakarta.validation.ConstraintViolation)397 Test (org.testng.annotations.Test)309 Validator (jakarta.validation.Validator)258 TestForIssue (org.hibernate.validator.testutil.TestForIssue)134 HibernateValidator (org.hibernate.validator.HibernateValidator)123 ValidatorUtil.getValidator (org.hibernate.validator.testutils.ValidatorUtil.getValidator)70 ExecutableValidator (jakarta.validation.executable.ExecutableValidator)60 ConstraintValidator (jakarta.validation.ConstraintValidator)57 ConstraintMapping (org.hibernate.validator.cfg.ConstraintMapping)54 Method (java.lang.reflect.Method)46 ValidatorFactory (jakarta.validation.ValidatorFactory)41 Test (org.junit.Test)39 ConstraintViolationException (jakarta.validation.ConstraintViolationException)35 Path (jakarta.validation.Path)35 NotNull (jakarta.validation.constraints.NotNull)32 HibernateValidatorConfiguration (org.hibernate.validator.HibernateValidatorConfiguration)27 NotNullDef (org.hibernate.validator.cfg.defs.NotNullDef)19 SizeDef (org.hibernate.validator.cfg.defs.SizeDef)18 Size (jakarta.validation.constraints.Size)17 PropertyNode (org.hibernate.validator.path.PropertyNode)14