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