View Javadoc
1   package org.kuali.common.util.validate;
2   
3   import java.lang.reflect.Field;
4   import java.util.Collection;
5   import java.util.Map;
6   
7   import org.kuali.common.util.CollectionUtils;
8   import org.kuali.common.util.ReflectionUtils;
9   
10  import com.google.common.base.Optional;
11  
12  public class NoBlankMapKeysValidator extends AbstractFieldsValidator<NoBlankMapKeys, Object> {
13  
14  	@Override
15  	protected Optional<String> validate(Field field, Object instance) {
16  
17  		// This field may not be a Map<String,?>
18  		if (!ReflectionUtils.isStringKeyedMap(field)) {
19  			return Optional.absent();
20  		}
21  
22  		// Extract the value of the field into an optional
23  		Optional<?> fieldValue = ReflectionUtils.get(field, instance);
24  
25  		// If there is no value for this field, we are done
26  		if (!fieldValue.isPresent()) {
27  			return Optional.absent();
28  		}
29  
30  		// We know the field is a map that uses strings for it's keys at this point
31  		@SuppressWarnings("unchecked")
32  		Map<String, ?> map = (Map<String, ?>) fieldValue.get();
33  
34  		// Extract any entries with a blank key
35  		Collection<String> blanks = CollectionUtils.getBlanks(map.keySet());
36  		if (blanks.size() > 0) {
37  			return Validation.errorMessage(field, "contains " + blanks.size() + " blank keys");
38  		} else {
39  			return Optional.absent();
40  		}
41  	}
42  }