From ef0ae6b61df0d9911247c69368b42e27a62b878b Mon Sep 17 00:00:00 2001 From: Pekka Helenius Date: Sun, 13 Sep 2020 23:48:56 +0300 Subject: [PATCH] Implement CurrentYear validator Signed-off-by: Pekka Helenius --- .../bookstore/validation/CurrentYear.java | 24 ++++++++++++++++++ .../validation/CurrentYearValidator.java | 25 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYear.java create mode 100644 bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYearValidator.java diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYear.java b/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYear.java new file mode 100644 index 0000000..04a7c6b --- /dev/null +++ b/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYear.java @@ -0,0 +1,24 @@ +//Pekka Helenius , Fjordtek 2020 + +package com.fjordtek.bookstore.validation; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Constraint(validatedBy = CurrentYearValidator.class) +@Target(value={ElementType.TYPE_USE, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) + +public @interface CurrentYear { + String message() default "Year must not be in the future"; + Class[] groups() default { }; + Class[] payload() default { }; + +} \ No newline at end of file diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYearValidator.java b/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYearValidator.java new file mode 100644 index 0000000..0b5a76e --- /dev/null +++ b/bookstore/src/main/java/com/fjordtek/bookstore/validation/CurrentYearValidator.java @@ -0,0 +1,25 @@ +//Pekka Helenius , Fjordtek 2020 + +package com.fjordtek.bookstore.validation; + +import java.time.Year; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +import org.springframework.stereotype.Component; + +@Component +public class CurrentYearValidator implements ConstraintValidator { + + private static final int yearNow = Year.now().getValue(); + + @Override + public void initialize(CurrentYear year) { + } + + @Override + public boolean isValid(Integer year, ConstraintValidatorContext constraintValidatorContext) { + return year <= yearNow; + } +} \ No newline at end of file