Hi, you could have a string constraint whose validator implementation reads a whitelist with allowed values from a text file. E.g. like so:
Code:
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = InWhitelistValidator.class)
@Documented
@Repeatable(List.class)
public @interface InWhitelist {
String message() default "{com.example.InWhitelist.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String whitelistFile();
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@interface List {
InWhitelist[] value();
}
}
Code:
public class InWhitelistValidator implements ConstraintValidator<InWhitelist, String> {
private Set<String> whitelist;
@Override
public void initialize(InWhitelist constraintAnnotation) {
this.whitelist = readFile( constraintAnnotation.whitelistFile() ).toSet(); // read contents of given whitelist file
}
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if ( object == null ) {
return true;
}
return whitelist.contains( object );
}
}
You then can create constraints for specific "enums" via constraint composition (
http://docs.jboss.org/hibernate/stable/ ... omposition):
Code:
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
@InWhitelist(whitelistFile="currency-codes.txt")
@Repeatable(List.class)
public @interface ValidCurrencyCode {
String message() default "{com.example.ValidCurrencyCode.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@interface List {
ValidCurrencyCode[] value();
}
}
Hth,
--Gunnar