Debian Codegraph @

src/aQute/bnd/annotation/metatype/Configurable.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 package aQute.bnd.annotation.metatype;
2
3 import static java.lang.invoke.MethodHandles.publicLookup;
4 import static java.lang.invoke.MethodType.methodType;
5 import static java.nio.charset.StandardCharsets.UTF_8;
6
7 import java.lang.annotation.Annotation;
8 import java.lang.invoke.MethodHandle;
9 import java.lang.invoke.MethodType;
10 import java.lang.reflect.Array;
11 import java.lang.reflect.GenericArrayType;
12 import java.lang.reflect.InvocationHandler;
13 import java.lang.reflect.InvocationTargetException;
14 import java.lang.reflect.Method;
15 import java.lang.reflect.ParameterizedType;
16 import java.lang.reflect.Proxy;
17 import java.lang.reflect.Type;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Dictionary;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.LinkedHashMap;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Queue;
29 import java.util.Set;
30 import java.util.SortedMap;
31 import java.util.SortedSet;
32 import java.util.TreeMap;
33 import java.util.TreeSet;
34 import java.util.regex.Pattern;
35
36 @SuppressWarnings({
37 "unchecked", "rawtypes"
38 })
39 public class Configurable<T> {
40 public static Pattern SPLITTER_P = Pattern.compile("(?<!\\\\)\\|");
41 private static final String BND_ANNOTATION_CLASS_NAME = "aQute.bnd.osgi.Annotation";
42 private static final String BND_ANNOTATION_METHOD_NAME = "getAnnotation";
43
44 public static <T> T createConfigurable(Class<T> c, Map<?, ?> properties) {
45 Object o = Proxy.newProxyInstance(c.getClassLoader(), new Class<?>[] {
46 c
47 }, new ConfigurableHandler(properties, c.getClassLoader()));
48 return c.cast(o);
49 }
50
51 public static <T> T createConfigurable(Class<T> c, Dictionary<?, ?> properties) {
52 Map<Object, Object> alt = new HashMap<>();
53 for (Enumeration<?> e = properties.keys(); e.hasMoreElements();) {
54 Object key = e.nextElement();
55 alt.put(key, properties.get(key));
56 }
57 return createConfigurable(c, alt);
58 }
59
60 static class ConfigurableHandler implements InvocationHandler {
61 final Map<?, ?> properties;
62 final ClassLoader loader;
63
64 ConfigurableHandler(Map<?, ?> properties, ClassLoader loader) {
65 this.properties = properties;
66 this.loader = loader;
67 }
68
69 @Override
70 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
71 Meta.AD ad = method.getAnnotation(Meta.AD.class);
72 String id = Configurable.mangleMethodName(method.getName());
73
74 if (ad != null && !ad.id()
75 .equals(Meta.NULL))
76 id = ad.id();
77
78 Object o = properties.get(id);
79
80 if (o == null) {
81 if (ad != null) {
82 if (ad.required())
83 throw new IllegalStateException("Attribute is required but not set " + method.getName());
84
85 o = ad.deflt();
86 if (o.equals(Meta.NULL))
87 o = null;
88 }
89 }
90 if (o == null) {
91 Class<?> rt = method.getReturnType();
92 if (rt == boolean.class)
93 return false;
94
95 if (method.getReturnType()
96 .isPrimitive()) {
97
98 o = "0";
99 } else
100 return null;
101 }
102
103 return convert(method.getGenericReturnType(), o);
104 }
105
106 public Object convert(Type type, Object o) throws Exception {
107 if (type instanceof ParameterizedType) {
108 ParameterizedType pType = (ParameterizedType) type;
109 return convert(pType, o);
110 }
111
112 if (type instanceof GenericArrayType) {
113 GenericArrayType gType = (GenericArrayType) type;
114 return convertArray(gType.getGenericComponentType(), o);
115 }
116
117 Class<?> resultType = (Class<?>) type;
118
119 if (resultType.isArray()) {
120 return convertArray(resultType.getComponentType(), o);
121 }
122
123 Class<?> actualType = o.getClass();
124 if (actualType.isAssignableFrom(resultType))
125 return o;
126
127 if (resultType == boolean.class || resultType == Boolean.class) {
128 if (actualType == boolean.class || actualType == Boolean.class)
129 return o;
130
131 if (Number.class.isAssignableFrom(actualType)) {
132 double b = ((Number) o).doubleValue();
133 if (b == 0)
134 return false;
135 return true;
136 }
137 if (o instanceof String) {
138 return Boolean.parseBoolean((String) o);
139 }
140 return true;
141
142 } else if (resultType == byte.class || resultType == Byte.class) {
143 if (Number.class.isAssignableFrom(actualType))
144 return ((Number) o).byteValue();
145 resultType = Byte.class;
146 } else if (resultType == char.class) {
147 resultType = Character.class;
148 } else if (resultType == short.class) {
149 if (Number.class.isAssignableFrom(actualType))
150 return ((Number) o).shortValue();
151 resultType = Short.class;
152 } else if (resultType == int.class) {
153 if (Number.class.isAssignableFrom(actualType))
154 return ((Number) o).intValue();
155 resultType = Integer.class;
156 } else if (resultType == long.class) {
157 if (Number.class.isAssignableFrom(actualType))
158 return ((Number) o).longValue();
159 resultType = Long.class;
160 } else if (resultType == float.class) {
161 if (Number.class.isAssignableFrom(actualType))
162 return ((Number) o).floatValue();
163 resultType = Float.class;
164 } else if (resultType == double.class) {
165 if (Number.class.isAssignableFrom(actualType))
166 return ((Number) o).doubleValue();
167 resultType = Double.class;
168 }
169
170 if (resultType.isPrimitive())
171 throw new IllegalArgumentException("Unknown primitive: " + resultType);
172
173 if (Number.class.isAssignableFrom(resultType) && actualType == Boolean.class) {
174 Boolean b = (Boolean) o;
175 o = b ? "1" : "0";
176 } else if (actualType == String.class) {
177 String input = (String) o;
178 if (Enum.class.isAssignableFrom(resultType)) {
179 return Enum.valueOf((Class<Enum>) resultType, input);
180 }
181 if (resultType == Class.class && loader != null) {
182 return loader.loadClass(input);
183 }
184 if (resultType == Pattern.class) {
185 return Pattern.compile(input);
186 }
187 } else if (resultType.isAnnotation() && actualType.getName()
188 .equals(BND_ANNOTATION_CLASS_NAME)) {
189 MethodHandle mh = publicLookup().findVirtual(actualType, BND_ANNOTATION_METHOD_NAME,
190 methodType(Annotation.class));
191 Annotation a;
192 try {
193 a = (Annotation) mh.invoke(o);
194 } catch (Error | Exception e) {
195 throw e;
196 } catch (Throwable e) {
197 throw new InvocationTargetException(e);
198 }
199 if (resultType.isAssignableFrom(a.getClass())) {
200 return a;
201 }
202 throw new IllegalArgumentException("Annotation " + o + " is not of expected type " + resultType);
203 }
204
205 try {
206 return newInstance(resultType, o.toString());
207 } catch (Throwable t) {
208 // handled on next line
209 }
210 throw new IllegalArgumentException(
211 "No conversion to " + resultType + " from " + actualType + " value " + o);
212 }
213
214 private Object convert(ParameterizedType pType, Object o)
215 throws InstantiationException, IllegalAccessException, Exception {
216 Class<?> resultType = (Class<?>) pType.getRawType();
217 if (Collection.class.isAssignableFrom(resultType)) {
218 Collection<?> input = toCollection(o);
219 if (resultType.isInterface()) {
220 if (resultType == Collection.class || resultType == List.class)
221 resultType = ArrayList.class;
222 else if (resultType == Set.class || resultType == SortedSet.class)
223 resultType = TreeSet.class;
224 else if (resultType == Queue.class /*
225 * || resultType ==
226 * Deque.class
227 */)
228 resultType = LinkedList.class;
229 else
230 throw new IllegalArgumentException(
231 "Unknown interface for a collection, no concrete class found: " + resultType);
232 }
233
234 Collection<Object> result = (Collection<Object>) newInstance(resultType);
235 Type componentType = pType.getActualTypeArguments()[0];
236
237 for (Object i : input) {
238 result.add(convert(componentType, i));
239 }
240 return result;
241 } else if (pType.getRawType() == Class.class) {
242 return loader.loadClass(o.toString());
243 }
244 if (Map.class.isAssignableFrom(resultType)) {
245 Map<?, ?> input = toMap(o);
246 if (resultType.isInterface()) {
247 if (resultType == SortedMap.class)
248 resultType = TreeMap.class;
249 else if (resultType == Map.class)
250 resultType = LinkedHashMap.class;
251 else
252 throw new IllegalArgumentException(
253 "Unknown interface for a collection, no concrete class found: " + resultType);
254 }
255 Map<Object, Object> result = (Map<Object, Object>) resultType.getConstructor()
256 .newInstance();
257 Type keyType = pType.getActualTypeArguments()[0];
258 Type valueType = pType.getActualTypeArguments()[1];
259
260 for (Map.Entry<?, ?> entry : input.entrySet()) {
261 result.put(convert(keyType, entry.getKey()), convert(valueType, entry.getValue()));
262 }
263 return result;
264 }
265 throw new IllegalArgumentException(
266 "cannot convert to " + pType + " because it uses generics and is not a Collection or a map");
267 }
268
269 Object convertArray(Type componentType, Object o) throws Exception {
270 if (o instanceof String) {
271 String s = (String) o;
272 if (componentType == Byte.class || componentType == byte.class)
273 return s.getBytes(UTF_8);
274 if (componentType == Character.class || componentType == char.class)
275 return s.toCharArray();
276 }
277 Collection<?> input = toCollection(o);
278 Class<?> componentClass = getRawClass(componentType);
279 Object array = Array.newInstance(componentClass, input.size());
280
281 int i = 0;
282 for (Object next : input) {
283 Array.set(array, i++, convert(componentType, next));
284 }
285 return array;
286 }
287
288 private Class<?> getRawClass(Type type) {
289 if (type instanceof Class)
290 return (Class<?>) type;
291
292 if (type instanceof ParameterizedType)
293 return (Class<?>) ((ParameterizedType) type).getRawType();
294
295 throw new IllegalArgumentException(
296 "For the raw type, type must be ParamaterizedType or Class but is " + type);
297 }
298
299 private Collection<?> toCollection(Object o) {
300 if (o instanceof Collection)
301 return (Collection<?>) o;
302
303 if (o.getClass()
304 .isArray()) {
305 if (o.getClass()
306 .getComponentType()
307 .isPrimitive()) {
308 int length = Array.getLength(o);
309 List<Object> result = new ArrayList<>(length);
310 for (int i = 0; i < length; i++) {
311 result.add(Array.get(o, i));
312 }
313 return result;
314 }
315 return Arrays.asList((Object[]) o);
316 }
317
318 if (o instanceof String) {
319 String s = (String) o;
320 if (SPLITTER_P.matcher(s)
321 .find())
322 return Arrays.asList(s.split("\\|"));
323 else
324 return unescape(s);
325
326 }
327 return Arrays.asList(o);
328 }
329
330 private Map<?, ?> toMap(Object o) {
331 if (o instanceof Map)
332 return (Map<?, ?>) o;
333
334 throw new IllegalArgumentException("Cannot convert " + o + " to a map as requested");
335 }
336
337 }
338
339 public static String mangleMethodName(String id) {
340 StringBuilder sb = new StringBuilder(id);
341 for (int i = 0; i < sb.length(); i++) {
342 char c = sb.charAt(i);
343 boolean twice = i < sb.length() - 1 && sb.charAt(i + 1) == c;
344 if (c == '$' || c == '_') {
345 if (twice)
346 sb.deleteCharAt(i + 1);
347 else if (c == '$')
348 sb.deleteCharAt(i--); // Remove dollars
349 else
350 sb.setCharAt(i, '.'); // Make _ into .
351 }
352 }
353 return sb.toString();
354 }
355
356 public static List<String> unescape(String s) {
357 // do it the OSGi way
358 List<String> tokens = new ArrayList<>();
359
360 String[] parts = s.split("(?<!\\\\),");
361
362 for (String p : parts) {
363 p = p.replaceAll("^\\s*", "");
364 p = p.replaceAll("(?!<\\\\)\\s*$", "");
365 p = p.replaceAll("\\\\([\\s,\\\\|])", "$1");
366 tokens.add(p);
367 }
368 return tokens;
369 }
370
371 private static final MethodType defaultConstructor = methodType(void.class);
372
373 static <T> T newInstance(Class<T> rawClass) throws Exception {
374 try {
375 return (T) publicLookup().findConstructor(rawClass, defaultConstructor)
376 .invoke();
377 } catch (Error | Exception e) {
378 throw e;
379 } catch (Throwable e) {
380 throw new RuntimeException(e);
381 }
382 }
383
384 private static final MethodType stringConstructor = methodType(void.class, String.class);
385
386 private static <T> T newInstance(Class<T> rawClass, String arg) throws Exception {
387 try {
388 return (T) publicLookup().findConstructor(rawClass, stringConstructor)
389 .invoke(arg);
390 } catch (Error | Exception e) {
391 throw e;
392 } catch (Throwable e) {
393 throw new RuntimeException(e);
394 }
395 }
396
397 }