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