|
| 1 | +/* |
| 2 | + * Hibernate Validator, declare and validate application constraints |
| 3 | + * |
| 4 | + * License: Apache License, Version 2.0 |
| 5 | + * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. |
| 6 | + */ |
| 7 | +package org.hibernate.validator.testutil; |
| 8 | + |
| 9 | +import jakarta.validation.ConstraintValidator; |
| 10 | +import jakarta.validation.ConstraintValidatorFactory; |
| 11 | + |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +public class PreconfiguredConstraintValidatorFactory implements ConstraintValidatorFactory { |
| 16 | + |
| 17 | + private final Map<Class<? extends ConstraintValidator>, ConstraintValidator<?, ?>> defaultValidators; |
| 18 | + private final ConstraintValidatorFactory delegated; |
| 19 | + |
| 20 | + private PreconfiguredConstraintValidatorFactory(Builder builder) { |
| 21 | + this.defaultValidators = builder.defaultValidators; |
| 22 | + this.delegated = builder.delegated; |
| 23 | + } |
| 24 | + |
| 25 | + public static Builder builder() { |
| 26 | + return new Builder(); |
| 27 | + } |
| 28 | + |
| 29 | + @SuppressWarnings("unchecked") |
| 30 | + @Override |
| 31 | + public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { |
| 32 | + if ( defaultValidators.containsKey( key ) ) { |
| 33 | + return (T) defaultValidators.get( key ); |
| 34 | + } |
| 35 | + |
| 36 | + return delegated.getInstance( key ); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public void releaseInstance(ConstraintValidator<?, ?> instance) { |
| 41 | + delegated.releaseInstance( instance ); |
| 42 | + } |
| 43 | + |
| 44 | + public static class Builder { |
| 45 | + |
| 46 | + private ConstraintValidatorFactory delegated; |
| 47 | + private final Map<Class<? extends ConstraintValidator>, ConstraintValidator<?, ?>> defaultValidators = new HashMap<>(); |
| 48 | + |
| 49 | + private Builder() { |
| 50 | + } |
| 51 | + |
| 52 | + public Builder defaultValidators( |
| 53 | + Map<Class<? extends ConstraintValidator>, ConstraintValidator<?, ?>> validators) { |
| 54 | + this.defaultValidators.putAll( validators ); |
| 55 | + return this; |
| 56 | + } |
| 57 | + |
| 58 | + public Builder delegated( |
| 59 | + ConstraintValidatorFactory delegated) { |
| 60 | + this.delegated = delegated; |
| 61 | + return this; |
| 62 | + } |
| 63 | + |
| 64 | + public PreconfiguredConstraintValidatorFactory build() { |
| 65 | + return new PreconfiguredConstraintValidatorFactory( this ); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments