Skip to content

Instantly share code, notes, and snippets.

@zygm0nt
Created July 12, 2011 06:47
Show Gist options
  • Save zygm0nt/1077516 to your computer and use it in GitHub Desktop.
Save zygm0nt/1077516 to your computer and use it in GitHub Desktop.
oval dictionary check
import net.sf.oval.configuration.annotation.Constraint;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Constraint(checkWith = DictionaryValueCheck.class)
public @interface DictionaryValue {
/**
* message to be used for the ConstraintsViolatedException
*
* @see ConstraintsViolatedException
*/
String message() default "constraint.DictionaryValue.violated";
String file();
}
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class DictionaryValueCheck extends AbstractAnnotationCheck<DictionaryValue> {
private Log log = LogFactory.getLog(DictionaryValueCheck.class);
private String file;
Map<String, String> dictionary;
@Override
public void configure(final DictionaryValue constraintAnnotation) {
super.configure(constraintAnnotation);
setFile(constraintAnnotation.file());
}
private void setFile(String file) {
this.file = file;
dictionary = loadDictionaryFrom(file);
requireMessageVariablesRecreation();
}
private Map<String, String> loadDictionaryFrom(String file) {
String fileStr;
Map<String, String> map = new HashMap<String, String>();
try {
fileStr = IOUtils.toString(this.getClass().getResourceAsStream(file));
} catch (IOException e) {
log.error("Error loading file: ", e);
return map;
}
for (String line : fileStr.split("\n")) {
if (line.trim().length() == 0)
continue;
String[] tokens = line.split(" ", 2); // we want 2 substrings max
if (tokens.length == 2)
map.put(tokens[0], tokens[1]);
if (tokens.length == 1)
map.put(tokens[0], null);
}
return map;
}
public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context, Validator validator) throws OValException {
if (valueToValidate == null)
return true;
return dictionary.containsKey(valueToValidate);
}
}
public class Address {
....
@DictionaryValue(file = "/validation/voivodeship.txt") String state;
....
}
constraint.DictionaryValue.violated={context} is not among allowed dictionary values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment