Validator for TimeZone for Spring ConfigurationProperties
package es.jaranda.commons.timeutils.application.properties;
import es.jaranda.commons.timeutils.validations.annotation.TimeZoneFormat;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public interface TimeRangeContract {
@NotNull
@Min(0)
@Max(23)
Integer getStartHourOfTimeRange();
@NotNull
@Min(0)
@Max(23)
Integer getEndHourOfTimeRange();
@NotNull
@TimeZoneFormat
String getAppliedTimeZoneForTimeRange();
}
package es.jaranda.commons.timeutils.validations.annotation;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.time.ZoneId;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ValidTimeZoneValidator.class)
public @interface TimeZoneFormat {
String message() default "Invalid Time-zone ID";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
class ValidTimeZoneValidator
implements ConstraintValidator<TimeZoneFormat, String> {
@Override
public void initialize(final TimeZoneFormat constraintAnnotation) {}
@Override
public boolean isValid(final String value,
final ConstraintValidatorContext context) {
return value == null || ZoneId.getAvailableZoneIds().contains(value);
}
}