1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package motej;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.Properties;
23
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27
28
29
30
31
32 public class ExtensionProvider {
33
34 private static Map<String, Class<? extends Extension>> lookup;
35
36 private Logger log = LoggerFactory.getLogger(ExtensionProvider.class);
37
38 @SuppressWarnings("unchecked")
39 public ExtensionProvider() {
40 synchronized(ExtensionProvider.class) {
41 if (lookup == null) {
42 log.debug("Initializing lookup.");
43 lookup = new HashMap<String, Class<? extends Extension>>();
44 InputStream in = ExtensionProvider.class.getResourceAsStream("/motejx/extensions/extensions.properties");
45 Properties props = new Properties();
46
47 if (in == null) {
48 log.info("no extensions.properties found. as a result, no extensions will be available.");
49 return;
50 }
51
52 try {
53 props.load(in);
54 for (Object o : props.keySet()) {
55 String key = (String) o;
56 String value = props.getProperty(key);
57
58 if (log.isDebugEnabled()) {
59 log.debug("Adding extension (" + key + " / " + value + ").");
60 }
61
62 Class<? extends Extension> clazz = (Class<? extends Extension>) Class.forName(value);
63 lookup.put(key, clazz);
64 }
65 } catch (IOException ex) {
66 log.warn(ex.getMessage(), ex);
67 } catch (ClassNotFoundException ex) {
68 log.warn(ex.getMessage(), ex);
69 }
70 }
71 }
72 log.debug("Lookup initialized.");
73 }
74
75 public Extension getExtension(byte[] id) {
76 String id0 = Integer.toHexString(id[0] & 0xff);
77 if (id0.length() == 1) {
78 id0 = "0" + id0;
79 }
80 String id1 = Integer.toHexString(id[1] & 0xff);
81 if (id1.length() == 1) {
82 id1 = "0" + id1;
83 }
84 String key = id0 + id1;
85 Class<? extends Extension> clazz = lookup.get(key);
86
87 if (clazz == null) {
88 log.warn("No matching extension found for key: " + key);
89 return null;
90 }
91
92 Extension extension = null;
93 try {
94 extension = clazz.newInstance();
95 } catch (InstantiationException ex) {
96 log.error(ex.getMessage(), ex);
97 } catch (IllegalAccessException ex) {
98 log.error(ex.getMessage(), ex);
99 }
100 return extension;
101 }
102 }