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