|
| 1 | +/* |
| 2 | + * Jooby https://jooby.io |
| 3 | + * Apache License Version 2.0 https://jooby.io/LICENSE.txt |
| 4 | + * Copyright 2014 Edgar Espina |
| 5 | + */ |
| 6 | +package io.jooby.hbv; |
| 7 | + |
| 8 | + |
| 9 | +import edu.umd.cs.findbugs.annotations.NonNull; |
| 10 | +import io.jooby.Extension; |
| 11 | +import io.jooby.Jooby; |
| 12 | +import jakarta.validation.Validator; |
| 13 | +import jakarta.validation.ValidatorFactory; |
| 14 | +import org.hibernate.validator.HibernateValidator; |
| 15 | +import org.hibernate.validator.HibernateValidatorConfiguration; |
| 16 | + |
| 17 | +import java.lang.reflect.Type; |
| 18 | +import java.util.Set; |
| 19 | +import java.util.function.Consumer; |
| 20 | +import java.util.function.Predicate; |
| 21 | + |
| 22 | +import static jakarta.validation.Validation.byProvider; |
| 23 | +import static java.util.Objects.requireNonNull; |
| 24 | + |
| 25 | +public class HbvModule implements Extension { |
| 26 | + |
| 27 | + private final Predicate<Type> predicate; |
| 28 | + private Consumer<HibernateValidatorConfiguration> configurer; |
| 29 | + |
| 30 | + public HbvModule() { |
| 31 | + this(none()); |
| 32 | + } |
| 33 | + |
| 34 | + public HbvModule(Predicate<Type> predicate) { |
| 35 | + this.predicate = requireNonNull(predicate, "Predicate is required."); |
| 36 | + } |
| 37 | + |
| 38 | + public HbvModule(final Class<?>... classes) { |
| 39 | + this.predicate = typeIs(Set.of(classes)); |
| 40 | + } |
| 41 | + |
| 42 | + public HbvModule doWith(final Consumer<HibernateValidatorConfiguration> configurer) { |
| 43 | + this.configurer = requireNonNull(configurer, "Configurer callback is required."); |
| 44 | + return this; |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public void install(@NonNull Jooby application) { |
| 49 | + HibernateValidatorConfiguration cfg = byProvider(HibernateValidator.class).configure(); |
| 50 | + |
| 51 | + if (configurer != null) { |
| 52 | + configurer.accept(cfg); |
| 53 | + } |
| 54 | + |
| 55 | + try (ValidatorFactory factory = cfg.buildValidatorFactory()) { |
| 56 | + Validator validator = factory.getValidator(); |
| 57 | + application.messageValidator(validator, predicate); |
| 58 | + application.getServices().put(Validator.class, validator); |
| 59 | + } |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + static Predicate<Type> typeIs(final Set<Class<?>> classes) { |
| 64 | + return type -> classes.contains((Class<?>) type); |
| 65 | + } |
| 66 | + |
| 67 | + static Predicate<Type> none() { |
| 68 | + return type -> false; |
| 69 | + } |
| 70 | +} |
0 commit comments