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