From 609ff79abf18580849cab1518e86868fe8966f1e Mon Sep 17 00:00:00 2001 From: oswaldquek Date: Wed, 18 Sep 2024 10:31:57 +0100 Subject: [PATCH] bau: Move AllowedString constraint to pay-java-commons (#936) Moving from pay-connector as this validator would be useful for other java projects. --- .../api/validation/AllowedStrings.java | 33 +++++++++++++++++++ .../validation/AllowedStringsValidator.java | 21 ++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java create mode 100644 model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java diff --git a/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java new file mode 100644 index 00000000..c424511e --- /dev/null +++ b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStrings.java @@ -0,0 +1,33 @@ +package uk.gov.service.payments.commons.api.validation; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Target({ FIELD }) +@Retention(RUNTIME) +@Constraint(validatedBy = AllowedStringsValidator.class) +@Documented +public @interface AllowedStrings { + + String message(); + + Class[] groups() default { }; + + Class[] payload() default { }; + + String[] allowed(); + + @Target({ FIELD }) + @Retention(RUNTIME) + @Documented + @interface List { + + AllowedStrings[] value(); + } +} diff --git a/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java new file mode 100644 index 00000000..0f9a9156 --- /dev/null +++ b/model/src/main/java/uk/gov/service/payments/commons/api/validation/AllowedStringsValidator.java @@ -0,0 +1,21 @@ +package uk.gov.service.payments.commons.api.validation; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.Set; + +public class AllowedStringsValidator implements ConstraintValidator { + + private Set allowedStrings; + + @Override + public void initialize(AllowedStrings parameters) { + allowedStrings = Set.of(parameters.allowed()); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value == null) return false; + return allowedStrings.contains(value); + } +}