1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package nextgrid.api.pom;
19
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24
25 import org.apache.commons.discovery.ResourceNameIterator;
26 import org.apache.commons.discovery.resource.ClassLoaders;
27 import org.apache.commons.discovery.resource.names.DiscoverServiceNames;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31
32
33
34
35
36 public final class GroundingFactoryFinder {
37
38
39
40
41 private static final Log LOG = LogFactory.getLog(GroundingFactoryFinder.class);
42
43
44
45
46 private static final int INITIAL_CAPACITY = 5;
47
48
49
50
51 private static final float LOAD_FACTOR = 0.75f;
52
53
54
55
56 private static final int CONCURRENCY_LEVEL = 2;
57
58
59
60
61 private static final ConcurrentMap<URI, GroundingFactory> REGISTRY;
62
63 static {
64 REGISTRY = new ConcurrentHashMap<URI, GroundingFactory>(
65 INITIAL_CAPACITY, LOAD_FACTOR, CONCURRENCY_LEVEL);
66
67
68 ClassLoaders loaders = new ClassLoaders();
69 loaders.put(Thread.currentThread().getContextClassLoader());
70 DiscoverServiceNames dsn = new DiscoverServiceNames(loaders);
71
72 ResourceNameIterator it = dsn.findResourceNames(GroundingFactory.class.getName());
73 while (it.hasNext()) {
74 String name = it.nextResourceName();
75 try {
76 Class<?> c = Class.forName(name);
77 if (GroundingFactory.class.isAssignableFrom(c)) {
78 GroundingFactory factory = (GroundingFactory)c.newInstance();
79
80
81
82 register(factory, false);
83 }
84
85 } catch (Exception e) {
86
87 LOG.warn("Could not load builder '" + name + "'", e);
88 }
89 }
90 }
91
92
93
94
95 private GroundingFactoryFinder() { }
96
97
98
99
100
101
102 public static void register(GroundingFactory factory) {
103 register(factory, true);
104 }
105
106
107
108
109
110
111
112 private static void register(GroundingFactory factory, boolean override) {
113 if (factory == null) {
114 return;
115 }
116
117 URI type = factory.getType();
118 if (override) {
119 REGISTRY.put(type, factory);
120 } else {
121 REGISTRY.putIfAbsent(type, factory);
122 }
123 }
124
125
126
127
128
129
130
131 public static GroundingFactory findFactory(URI type) {
132 return REGISTRY.get(type);
133 }
134
135
136
137
138
139
140
141 public static GroundingFactory findFactory(String type) {
142 if (type == null) {
143 return null;
144 }
145
146 try {
147 return findFactory(new URI(type));
148 } catch (URISyntaxException e) {
149 e.printStackTrace();
150 return null;
151 }
152 }
153
154
155
156
157
158
159 public URI[] getAvailableTypes() {
160 return REGISTRY.keySet().toArray(new URI[REGISTRY.size()]);
161 }
162 }