1 package org.xmlfield.validation.handlers; 2 3 import java.lang.annotation.Annotation; 4 import java.lang.reflect.InvocationTargetException; 5 import java.lang.reflect.Method; 6 import java.util.HashSet; 7 import java.util.Set; 8 9 import org.apache.commons.lang.ArrayUtils; 10 import org.apache.commons.lang.StringUtils; 11 import org.xmlfield.validation.annotations.Values; 12 13 public class ValuesHandler implements IHandler { 14 15 @Override 16 public boolean handles(Annotation a) { 17 return a instanceof Values; 18 } 19 20 @Override 21 public Set<ConstraintViolation<Object>> validate(Annotation a, Method m, Object xmlFieldObject, Class<?> group) 22 throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { 23 24 Values av = (Values) a; 25 if ((group == null && av.groups().length == 0) || ArrayUtils.contains(av.groups(), group)) { 26 27 Object o = m.invoke(xmlFieldObject, new Object[] {}); 28 29 if (o == null) 30 return null; 31 32 boolean ok = false; 33 if (av.string().length > 0) { 34 Object[] acceptedValues = av.string(); 35 for (Object ao : acceptedValues) { 36 if (ao.equals(o)) { 37 ok = true; 38 break; 39 } 40 } 41 if (!ok) 42 return createResultFromViolation(new ConstraintViolation<Object>(m.getName(), StringUtils.join( 43 acceptedValues, ","), o == null ? "null" : o.toString())); 44 45 } 46 47 else if (av.integer().length > 0) { 48 int[] acceptedValues = av.integer(); 49 50 for (int ao : acceptedValues) { 51 if (o != null && o.equals(ao)) { 52 ok = true; 53 break; 54 } 55 } 56 57 if (!ok) 58 return createResultFromViolation(new ConstraintViolation<Object>(m.getName(), 59 ArrayUtils.toString(acceptedValues), o == null ? "null" : o.toString())); 60 61 } 62 } 63 64 return null; 65 } 66 67 private <T> Set<ConstraintViolation<T>> createResultFromViolation(ConstraintViolation<T> c) { 68 69 Set<ConstraintViolation<T>> result = new HashSet<ConstraintViolation<T>>(); 70 71 result.add(c); 72 return result; 73 74 } 75 76 }