1 package org.kuali.common.util.bind.test;
2
3 import java.lang.reflect.Field;
4 import java.util.List;
5 import java.util.Set;
6 import java.util.SortedSet;
7
8 import org.kuali.common.util.Annotations;
9 import org.kuali.common.util.ReflectionUtils;
10 import org.kuali.common.util.bind.api.Bind;
11 import org.kuali.common.util.bind.api.BindingAlias;
12 import org.kuali.common.util.function.PrefixFunction;
13
14 import com.google.common.base.Function;
15 import com.google.common.base.Optional;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Sets;
19
20 public class BindKeys {
21
22 public static Set<String> get(Class<?> type) {
23 return get(Optional.<String> absent(), type);
24 }
25
26 public static Set<String> get(Optional<String> prefix, Class<?> type) {
27 SortedSet<String> keys = Sets.newTreeSet();
28
29 Optional<String> actualPrefix = null;
30 Set<Field> fields = ReflectionUtils.getAllFields(type);
31 for (Field field : fields) {
32 Set<String> fieldKeys = getKeys(field, actualPrefix);
33 keys.addAll(fieldKeys);
34 }
35 return keys;
36 }
37
38 protected static Set<String> getKeys(Field field, Optional<String> prefix) {
39
40 if (field.isAnnotationPresent(Bind.class)) {
41
42 Optional<String> fieldPrefix = null;
43 Optional<String> newPrefix = combine(prefix, fieldPrefix, ".");
44
45 return get(newPrefix, field.getType());
46 } else {
47
48 List<String> fieldKeys = getKeys(field);
49 return Sets.newHashSet(transform(fieldKeys, prefix, "."));
50 }
51 }
52
53 protected static Optional<String> combine(Optional<String> s1, Optional<String> s2, String separator) {
54 StringBuilder sb = new StringBuilder();
55 if (s1.isPresent()) {
56 sb.append(s1.get());
57 }
58 if (s1.isPresent() && s2.isPresent()) {
59 sb.append(separator);
60 }
61 if (s2.isPresent()) {
62 sb.append(s2.get());
63 }
64 if (sb.length() == 0) {
65 return Optional.absent();
66 } else {
67 return Optional.of(sb.toString());
68 }
69 }
70
71 protected static List<String> transform(List<String> original, Optional<String> prefix, String separator) {
72 if (prefix.isPresent()) {
73 Function<String, String> prefixer = PrefixFunction.of(prefix.get(), separator);
74 return Lists.transform(original, prefixer);
75 } else {
76 return original;
77 }
78 }
79
80 protected static List<String> getKeys(Field field) {
81 Optional<BindingAlias> optional = Annotations.get(field, BindingAlias.class);
82 if (!optional.isPresent()) {
83 return ImmutableList.of(field.getName());
84 } else {
85 BindingAlias annotation = optional.get();
86 List<String> keys = Lists.newArrayList();
87 keys.addAll(ImmutableList.copyOf(annotation.value()));
88 if (annotation.includeFieldName()) {
89 keys.add(field.getName());
90 }
91 return keys;
92 }
93 }
94
95 }