1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.eos.util.functions;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20
21 import java.lang.reflect.Field;
22 import java.lang.reflect.Modifier;
23
24 import net.sf.eos.Experimental;
25 import net.sf.eos.Function;
26 import net.sf.eos.Nullable;
27 import net.sf.eos.config.ConfigurationKey;
28
29 import net.sf.eos.util.functions.ConfigurationKeyIntrospectorFunction.ConfigurationKeySupport;
30
31
32
33
34
35
36
37
38
39
40
41 @Experimental
42 public class ConfigurationKeyIntrospectorFunction
43 implements Function<ConfigurationKeySupport, ConfigurationKey> {
44
45
46 static final Log LOG = LogFactory.getLog(ConfigurationKeyIntrospectorFunction.class.getName());
47
48
49
50
51
52
53 public static class ConfigurationKeySupport {
54
55
56 final Class<?> clazz;
57
58 final String configKeyValue;
59
60
61
62
63
64
65 public ConfigurationKeySupport(
66 @SuppressWarnings("hiding") @Nullable final Class<?> clazz,
67 @SuppressWarnings("hiding") @Nullable final String configKeyValue) {
68 this.clazz = clazz;
69 this.configKeyValue = configKeyValue;
70 }
71
72
73
74
75
76 public Class<?> getConfigKeyHolderClass() {
77 return this.clazz;
78 }
79
80
81
82
83
84 public String getConfigKeyValue() {
85 return this.configKeyValue;
86 }
87
88
89 @SuppressWarnings("nls")
90 @Override
91 public String toString() {
92 final StringBuilder sb = new StringBuilder();
93 sb.append("ConfigurationKeySupport[configKeyHolderClass=");
94 sb.append(this.getConfigKeyHolderClass());
95 sb.append("|configKeyValue=");
96 sb.append(this.getConfigKeyValue());
97 sb.append("]");
98
99 return sb.toString();
100 }
101 }
102
103
104
105
106
107
108
109
110
111 @SuppressWarnings("nls")
112 public ConfigurationKey apply(@Nullable ConfigurationKeySupport from) {
113 if (from == null
114 || from.getConfigKeyHolderClass() == null
115 || from.getConfigKeyValue() == null) {
116 if (LOG.isDebugEnabled()) {
117 LOG.debug("from value or values of from are null: " + from);
118 }
119 return null;
120 }
121
122 ConfigurationKey retval = null;
123
124 final Field[] fields = from.getConfigKeyHolderClass().getFields();
125 for (final Field field : fields) {
126
127 final ConfigurationKey fieldKey =
128 field.getAnnotation(ConfigurationKey.class);
129
130 if (fieldKey != null) {
131 final int modifiers = field.getModifiers();
132 if (Modifier.isStatic(modifiers)
133 && Modifier.isFinal(modifiers)
134 && Modifier.isPublic(modifiers)) {
135 try {
136 final Object o = field.get(null);
137 if (from.getConfigKeyValue().equals(o)) {
138 retval = fieldKey;
139
140 break;
141 }
142 } catch (final IllegalAccessException e) {
143
144
145 }
146 }
147 }
148 }
149
150 if (LOG.isDebugEnabled()) {
151 if (retval != null) {
152 LOG.debug("found configuration key " + retval + " for " + from);
153 } else {
154 LOG.debug("No configuration key found for " + from);
155 }
156 }
157
158 return retval;
159 }
160 }