View Javadoc

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.xmlfield.validation.annotations.Size;
11  
12  public class SizeHandler implements IHandler {
13  
14      @Override
15      public boolean handles(Annotation a) {
16          return a instanceof Size;
17      }
18  
19      @Override
20      public Set<ConstraintViolation<Object>> validate(Annotation a, Method m, Object o, Class<?> group) throws IllegalArgumentException,
21              IllegalAccessException, InvocationTargetException {
22  
23          Size as = (Size) a;
24          if ((group == null && as.groups().length == 0) || ArrayUtils.contains(as.groups(), group)) {
25  
26          int currentValue = 0;
27  
28          Object result = m.invoke(o, new Object[] {});
29          if (result instanceof Object[]) {
30              Object[] array = (Object[]) result;
31              currentValue = array.length;
32          }
33  
34          if (result instanceof String) {
35              currentValue = ((String) result).length();
36          }
37  
38          if (currentValue > as.max() || currentValue < as.min())
39              return createResultFromViolation(new ConstraintViolation<Object>(m.getName(), "min/max",
40                      String.valueOf(currentValue)));
41  
42          }
43          return null;
44      }
45  
46      private <T> Set<ConstraintViolation<T>> createResultFromViolation(ConstraintViolation<T> c) {
47  
48          Set<ConstraintViolation<T>> result = new HashSet<ConstraintViolation<T>>();
49  
50          result.add(c);
51          return result;
52  
53      }
54  
55  }