blob: aa1e6e72b89acacd72601e8ca5646e71aa591ae3 [file] [log] [blame]
Stuart McCulloch4b9de8e2012-07-22 00:19:13 +00001package aQute.bnd.component;
2
3import java.util.ArrayList;
4import java.util.Arrays;
5import java.util.Collection;
6import java.util.HashMap;
7import java.util.HashSet;
8import java.util.List;
9import java.util.Map;
10import java.util.Set;
11import java.util.StringTokenizer;
12import java.util.regex.Matcher;
13import java.util.regex.Pattern;
14
15import org.osgi.service.component.annotations.ConfigurationPolicy;
16import org.osgi.service.component.annotations.ReferenceCardinality;
17import org.osgi.service.component.annotations.ReferencePolicy;
18import org.osgi.service.component.annotations.ReferencePolicyOption;
19
20import aQute.bnd.osgi.*;
21import aQute.bnd.osgi.Clazz.MethodDef;
22import aQute.bnd.osgi.Descriptors.TypeRef;
23import aQute.lib.tag.Tag;
24import aQute.bnd.version.Version;
25
26public class HeaderReader extends Processor {
27 final static Pattern PROPERTY_PATTERN = Pattern
28 .compile("([^=]+([:@](Boolean|Byte|Char|Short|Integer|Long|Float|Double|String))?)\\s*=(.*)");
29 private final static Set<String> LIFECYCLE_METHODS = new HashSet<String>(Arrays.asList("activate", "deactivate", "modified"));
30
31 private final Analyzer analyzer;
32
33 private final static String ComponentContextTR = "org.osgi.service.component.ComponentContext";
34 private final static String BundleContextTR = "org.osgi.framework.BundleContext";
35 private final static String MapTR = Map.class.getName();
36 private final static String IntTR = int.class.getName();
37 private final static Set<String> allowed = new HashSet<String>(Arrays.asList(ComponentContextTR, BundleContextTR, MapTR));
38 private final static Set<String> allowedDeactivate = new HashSet<String>(Arrays.asList(ComponentContextTR, BundleContextTR, MapTR, IntTR));
39
40 private final static String ServiceReferenceTR = "org.osgi.framework.ServiceReference";
41
42 public HeaderReader(Analyzer analyzer) {
43 this.analyzer = analyzer;
44 }
45
46 public Tag createComponentTag(String name, String impl, Map<String, String> info)
47 throws Exception {
48 final ComponentDef cd = new ComponentDef();
49 cd.name = name;
50 if (info.get(COMPONENT_ENABLED) != null)
51 cd.enabled = Boolean.valueOf(info.get(COMPONENT_ENABLED));
52 cd.factory = info.get(COMPONENT_FACTORY);
53 if (info.get(COMPONENT_IMMEDIATE) != null)
54 cd.immediate = Boolean.valueOf(info.get(COMPONENT_IMMEDIATE));
55 if (info.get(COMPONENT_CONFIGURATION_POLICY) != null)
56 cd.configurationPolicy = ConfigurationPolicy.valueOf(info.get(COMPONENT_CONFIGURATION_POLICY).toUpperCase());
57 cd.activate = checkIdentifier(COMPONENT_ACTIVATE, info.get(COMPONENT_ACTIVATE));
58 cd.deactivate = checkIdentifier(COMPONENT_DEACTIVATE, info.get(COMPONENT_DEACTIVATE));
59 cd.modified = checkIdentifier(COMPONENT_MODIFIED, info.get(COMPONENT_MODIFIED));
60
61 cd.implementation = analyzer.getTypeRefFromFQN(impl == null? name: impl);
62
63
64 String provides = info.get(COMPONENT_PROVIDE);
65 if (info.get(COMPONENT_SERVICEFACTORY) != null) {
66 if (provides != null)
67 cd.servicefactory = Boolean.valueOf(info.get(COMPONENT_SERVICEFACTORY));
68 else
69 warning("The servicefactory:=true directive is set but no service is provided, ignoring it");
70 }
71
72 if (cd.servicefactory != null && cd.servicefactory && cd.immediate != null && cd.immediate) {
73 // TODO can become error() if it is up to me
74 warning("For a Service Component, the immediate option and the servicefactory option are mutually exclusive for %(%s)",
75 name, impl);
76 }
77
78 //analyze the class for suitable methods.
79 final Map<String, MethodDef> lifecycleMethods = new HashMap<String, MethodDef>();
80 final Map<String, MethodDef> bindmethods = new HashMap<String, MethodDef>();
81 TypeRef typeRef = analyzer.getTypeRefFromFQN(impl);
82 Clazz clazz = analyzer.findClass(typeRef);
83 boolean privateAllowed = true;
84 boolean defaultAllowed = true;
85 String topPackage = typeRef.getPackageRef().getFQN();
86 while (clazz != null) {
87 final boolean pa = privateAllowed;
88 final boolean da = defaultAllowed;
89 final Map<String, MethodDef> classLifecyclemethods = new HashMap<String, MethodDef>();
90 final Map<String, MethodDef> classBindmethods = new HashMap<String, MethodDef>();
91
92 clazz.parseClassFileWithCollector(new ClassDataCollector() {
93
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000094 @Override
Stuart McCulloch4b9de8e2012-07-22 00:19:13 +000095 public void method(MethodDef md) {
96 Set<String> allowedParams = allowed;
97 String lifecycleName = null;
98
99 boolean isLifecycle = (cd.activate == null? "activate": cd.activate).equals(md.getName()) ||
100 md.getName().equals(cd.modified);
101 if (!isLifecycle && (cd.deactivate == null? "deactivate": cd.deactivate).equals(md.getName())) {
102 isLifecycle = true;
103 allowedParams = allowedDeactivate;
104 }
105 if (isLifecycle && !lifecycleMethods.containsKey(md.getName()) &&
106 (md.isPublic() ||
107 md.isProtected() ||
108 (md.isPrivate() && pa) ||
109 (!md.isPrivate()) && da) &&
110 isBetter(md, classLifecyclemethods.get(md.getName()), allowedParams)) {
111 classLifecyclemethods.put(md.getName(), md);
112 }
113 if (!bindmethods.containsKey(md.getName()) &&
114 (md.isPublic() ||
115 md.isProtected() ||
116 (md.isPrivate() && pa) ||
117 (!md.isPrivate()) && da) &&
118 isBetterBind(md, classBindmethods.get(md.getName()))) {
119 classBindmethods.put(md.getName(), md);
120 }
121 }
122
123 private boolean isBetter(MethodDef test, MethodDef existing, Set<String> allowedParams) {
124 int testRating = rateLifecycle(test, allowedParams);
125 if (existing == null)
126 return testRating < 6;// ignore invalid methods
127 if (testRating < rateLifecycle(existing, allowedParams))
128 return true;
129
130 return false;
131 }
132
133 private boolean isBetterBind(MethodDef test, MethodDef existing) {
134 int testRating = rateBind(test);
135 if (existing == null)
136 return testRating < 6;// ignore invalid methods
137 if (testRating < rateBind(existing))
138 return true;
139
140 return false;
141 }
142
143 });
144 lifecycleMethods.putAll(classLifecyclemethods);
145 bindmethods.putAll(classBindmethods);
146 typeRef = clazz.getSuper();
147 if (typeRef == null)
148 break;
149 clazz = analyzer.findClass(typeRef);
150 privateAllowed = false;
151 defaultAllowed = defaultAllowed && topPackage.equals(typeRef.getPackageRef().getFQN());
152 }
153
154
155 if (cd.activate != null && !lifecycleMethods.containsKey(cd.activate)) {
156 error("in component %s, activate method %s specified but not found", cd.implementation.getFQN(), cd.activate);
157 cd.activate = null;
158 }
159 if (cd.deactivate != null && !lifecycleMethods.containsKey(cd.deactivate)) {
160 error("in component %s, deactivate method %s specified but not found", cd.implementation.getFQN(), cd.deactivate);
161 cd.activate = null;
162 }
163 if (cd.modified != null && !lifecycleMethods.containsKey(cd.modified)) {
164 error("in component %s, modified method %s specified but not found", cd.implementation.getFQN(), cd.modified);
165 cd.activate = null;
166 }
167
168 provide(cd, provides, impl);
169 properties(cd, info, name);
170 reference(info, impl, cd, bindmethods);
171 //compute namespace after references, an updated method means ds 1.2.
172 cd.xmlns = getNamespace(info, cd, lifecycleMethods);
173 cd.prepare(analyzer);
174 return cd.getTag();
175
176 }
177
178 private String checkIdentifier(String name, String value) {
179 if (value != null) {
180 if (!Verifier.isIdentifier(value)) {
181 error("Component attribute %s has value %s but is not a Java identifier",
182 name, value);
183 return null;
184 }
185 }
186 return value;
187 }
188
189 /**
190 * Check if we need to use the v1.1 namespace (or later).
191 *
192 * @param info
193 * @param cd TODO
194 * @param descriptors TODO
195 * @return
196 */
197 private String getNamespace(Map<String, String> info, ComponentDef cd, Map<String,MethodDef> descriptors) {
198 String namespace = info.get(COMPONENT_NAMESPACE);
199 if (namespace != null) {
200 return namespace;
201 }
202 String version = info.get(COMPONENT_VERSION);
203 if (version != null) {
204 try {
205 Version v = new Version(version);
206 return NAMESPACE_STEM + "/v" + v;
207 } catch (Exception e) {
208 error("version: specified on component header but not a valid version: "
209 + version);
210 return null;
211 }
212 }
213 for (String key : info.keySet()) {
214 if (SET_COMPONENT_DIRECTIVES_1_2.contains(key)) {
215 return NAMESPACE_STEM + "/v1.2.0";
216 }
217 }
218 for (ReferenceDef rd: cd.references.values()) {
219 if (rd.updated != null) {
220 return NAMESPACE_STEM + "/v1.2.0";
221 }
222 }
223 //among other things this picks up any specified lifecycle methods
224 for (String key : info.keySet()) {
225 if (SET_COMPONENT_DIRECTIVES_1_1.contains(key)) {
226 return NAMESPACE_STEM + "/v1.1.0";
227 }
228 }
229 for (String lifecycle: LIFECYCLE_METHODS) {
230 //lifecycle methods were not specified.... check for non 1.0 signatures.
Stuart McCulloch61c61eb2012-07-24 21:37:47 +0000231 MethodDef test = descriptors.get(lifecycle);
232 if (descriptors.containsKey(lifecycle) && (!(test.isPublic() || test.isProtected()) ||
233 rateLifecycle(test, "deactivate".equals(lifecycle)? allowedDeactivate: allowed) > 1)) {
Stuart McCulloch4b9de8e2012-07-22 00:19:13 +0000234 return NAMESPACE_STEM + "/v1.1.0";
235 }
236 }
237 return null;
238 }
239
240 /**
241 * Print the Service-Component properties element
242 *
243 * @param cd
244 * @param info
245 */
246 void properties(ComponentDef cd, Map<String, String> info, String name) {
247 Collection<String> properties = split(info.get(COMPONENT_PROPERTIES));
248 for (String p : properties) {
249 Matcher m = PROPERTY_PATTERN.matcher(p);
250
251 if (m.matches()) {
252 String key = m.group(1).replaceAll("@", ":");
253 String value = m.group(4);
254 String parts[] = value.split("\\s*(\\||\\n)\\s*");
255 for (String part: parts) {
256 cd.property.add(key, part);
257 }
258 } else
259 throw new IllegalArgumentException("Malformed property '" + p
260 + "' on component: " + name);
261 }
262 }
263
264 /**
265 * @param cd
266 * @param provides
267 */
268 void provide(ComponentDef cd, String provides, String impl) {
269 if (provides != null) {
270 StringTokenizer st = new StringTokenizer(provides, ",");
271 List<TypeRef> provide = new ArrayList<TypeRef>();
272 while (st.hasMoreTokens()) {
273 String interfaceName = st.nextToken();
274 TypeRef ref = analyzer.getTypeRefFromFQN(interfaceName);
275 provide.add(ref);
276 analyzer.referTo(ref);
277
278 // TODO verifies the impl. class extends or implements the
279 // interface
280 }
281 cd.service = provide.toArray(new TypeRef[provide.size()]);
282 }
283 }
284
285 public final static Pattern REFERENCE = Pattern.compile("([^(]+)(\\(.+\\))?");
286
287 /**
288 * rates the methods according to the scale in 112.5.8 (compendium 4.3, ds 1.2), also returning "6" for invalid methods
289 * We don't look at return values yet due to proposal to all them for setting service properties.
290 * @param test methodDef to examine for suitability as a DS lifecycle method
291 * @param allowedParams TODO
292 * @return rating; 6 if invalid, lower is better
293 */
294 private int rateLifecycle(MethodDef test, Set<String> allowedParams) {
295 TypeRef[] prototype = test.getDescriptor().getPrototype();
296 if (prototype.length == 1 && ComponentContextTR.equals(prototype[0].getFQN()))
Stuart McCulloch61c61eb2012-07-24 21:37:47 +0000297 return 1;
Stuart McCulloch4b9de8e2012-07-22 00:19:13 +0000298 if (prototype.length == 1 && BundleContextTR.equals(prototype[0].getFQN()))
299 return 2;
300 if (prototype.length == 1 && MapTR.equals(prototype[0].getFQN()))
301 return 3;
302 if (prototype.length > 1) {
303 for (TypeRef tr: prototype) {
304 if (!allowedParams.contains(tr.getFQN()))
305 return 6;
306 }
307 return 5;
308 }
309 if (prototype.length == 0)
310 return 5;
311
312 return 6;
313 }
314
315 /**
316 * see 112.3.2. We can't distinguish the bind type, so we just accept anything.
317 * @param test
318 * @return
319 */
320 private int rateBind(MethodDef test) {
321 TypeRef[] prototype = test.getDescriptor().getPrototype();
322 if (prototype.length == 1 && ServiceReferenceTR.equals(prototype[0].getFQN()))
323 return 1;
324 if (prototype.length == 1)
325 return 2;
326 if (prototype.length == 2 && MapTR.equals(prototype[1].getFQN()))
327 return 3;
328 return 6;
329 }
330
331 /**
332 * @param info
333 * @param impl TODO
334 * @param descriptors TODO
335 * @param pw
336 * @throws Exception
337 */
338 void reference(Map<String, String> info, String impl, ComponentDef cd, Map<String,MethodDef> descriptors) throws Exception {
339 Collection<String> dynamic = new ArrayList<String>(split(info.get(COMPONENT_DYNAMIC)));
340 Collection<String> optional = new ArrayList<String>(split(info.get(COMPONENT_OPTIONAL)));
341 Collection<String> multiple = new ArrayList<String>(split(info.get(COMPONENT_MULTIPLE)));
342 Collection<String> greedy = new ArrayList<String>(split(info.get(COMPONENT_GREEDY)));
343
344
345 for (Map.Entry<String, String> entry : info.entrySet()) {
346
347 // Skip directives
348 String referenceName = entry.getKey();
349 if (referenceName.endsWith(":")) {
350 if (!SET_COMPONENT_DIRECTIVES.contains(referenceName))
351 error("Unrecognized directive in Service-Component header: "
352 + referenceName);
353 continue;
354 }
355
356 // Parse the bind/unbind methods from the name
357 // if set. They are separated by '/'
358 String bind = null;
359 String unbind = null;
360 String updated = null;
361
362 boolean bindCalculated = true;
363 boolean unbindCalculated = true;
364 boolean updatedCalculated = true;
365
366 if (referenceName.indexOf('/') >= 0) {
367 String parts[] = referenceName.split("/");
368 referenceName = parts[0];
369 if (parts[1].length() > 0) {
370 bind = parts[1];
371 bindCalculated = false;
372 } else {
373 bind = calculateBind(referenceName);
374 }
375 bind = parts[1].length() == 0? calculateBind(referenceName): parts[1];
376 if (parts.length > 2 && parts[2].length() > 0) {
377 unbind = parts[2] ;
378 unbindCalculated = false;
379 } else {
380 if (bind.startsWith("add"))
381 unbind = bind.replaceAll("add(.+)", "remove$1");
382 else
383 unbind = "un" + bind;
384 }
385 if (parts.length > 3) {
386 updated = parts[3];
387 updatedCalculated = false;
388 }
389 } else if (Character.isLowerCase(referenceName.charAt(0))) {
390 bind = calculateBind(referenceName);
391 unbind = "un" + bind;
392 updated = "updated" + Character.toUpperCase(referenceName.charAt(0))
393 + referenceName.substring(1);
394 }
395
396 String interfaceName = entry.getValue();
397 if (interfaceName == null || interfaceName.length() == 0) {
398 error("Invalid Interface Name for references in Service Component: "
399 + referenceName + "=" + interfaceName);
400 continue;
401 }
402
403 // If we have descriptors, we have analyzed the component.
404 // So why not check the methods
405 if (descriptors.size() > 0) {
406 // Verify that the bind method exists
407 if (!descriptors.containsKey(bind))
408 if (bindCalculated)
409 bind = null;
410 else
411 error("In component %s, the bind method %s for %s not defined", cd.name, bind, referenceName);
412
413 // Check if the unbind method exists
414 if (!descriptors.containsKey(unbind)) {
415 if (unbindCalculated)
416 // remove it
417 unbind = null;
418 else
419 error("In component %s, the unbind method %s for %s not defined", cd.name, unbind, referenceName);
420 }
421 if (!descriptors.containsKey(updated)) {
422 if (updatedCalculated)
423 //remove it
424 updated = null;
425 else
426 error("In component %s, the updated method %s for %s is not defined", cd.name, updated, referenceName);
427 }
428 }
429 // Check the cardinality by looking at the last
430 // character of the value
431 char c = interfaceName.charAt(interfaceName.length() - 1);
432 if ("?+*~".indexOf(c) >= 0) {
433 if (c == '?' || c == '*' || c == '~')
434 optional.add(referenceName);
435 if (c == '+' || c == '*')
436 multiple.add(referenceName);
437 if (c == '+' || c == '*' || c == '?')
438 dynamic.add(referenceName);
439 interfaceName = interfaceName.substring(0, interfaceName.length() - 1);
440 }
441
442 // Parse the target from the interface name
443 // The target is a filter.
444 String target = null;
445 Matcher m = REFERENCE.matcher(interfaceName);
446 if (m.matches()) {
447 interfaceName = m.group(1);
448 target = m.group(2);
449 }
450 TypeRef ref = analyzer.getTypeRefFromFQN(interfaceName);
451 analyzer.referTo(ref);
452 ReferenceDef rd = new ReferenceDef();
453 rd.name = referenceName;
454 rd.service = interfaceName;
455
456 if (optional.contains(referenceName)) {
457 if (multiple.contains(referenceName)) {
458 rd.cardinality = ReferenceCardinality.MULTIPLE;
459 } else {
460 rd.cardinality = ReferenceCardinality.OPTIONAL;
461 }
462 } else {
463 if (multiple.contains(referenceName)) {
464 rd.cardinality = ReferenceCardinality.AT_LEAST_ONE;
465 } else {
466 rd.cardinality = ReferenceCardinality.MANDATORY;
467 }
468 }
469 if (bind != null) {
470 rd.bind = bind;
471 if (unbind != null) {
472 rd.unbind = unbind;
473 }
474 if (updated != null) {
475 rd.updated = updated;
476 }
477 }
478
479 if (dynamic.contains(referenceName)) {
480 rd.policy = ReferencePolicy.DYNAMIC;
481 }
482
483 if (greedy.contains(referenceName)) {
484 rd.policyOption = ReferencePolicyOption.GREEDY;
485 }
486
487 if (target != null) {
488 rd.target = target;
489 }
490 cd.references.put(referenceName, rd);
491 }
492 }
493
494 private String calculateBind(String referenceName) {
495 return "set" + Character.toUpperCase(referenceName.charAt(0))
496 + referenceName.substring(1);
497 }
498
499}