001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.camel.impl.osgi; 018 019import java.io.BufferedInputStream; 020import java.io.BufferedReader; 021import java.io.IOException; 022import java.io.InputStreamReader; 023import java.lang.reflect.Method; 024import java.net.URL; 025import java.util.ArrayList; 026import java.util.Collection; 027import java.util.Dictionary; 028import java.util.Enumeration; 029import java.util.HashMap; 030import java.util.Hashtable; 031import java.util.LinkedHashSet; 032import java.util.List; 033import java.util.Map; 034import java.util.Properties; 035import java.util.Set; 036import java.util.StringTokenizer; 037import java.util.concurrent.ConcurrentHashMap; 038 039import org.apache.camel.CamelContext; 040import org.apache.camel.Component; 041import org.apache.camel.Converter; 042import org.apache.camel.TypeConverter; 043import org.apache.camel.TypeConverterLoaderException; 044import org.apache.camel.impl.converter.AnnotationTypeConverterLoader; 045import org.apache.camel.impl.osgi.tracker.BundleTracker; 046import org.apache.camel.impl.osgi.tracker.BundleTrackerCustomizer; 047import org.apache.camel.impl.scan.AnnotatedWithPackageScanFilter; 048import org.apache.camel.model.DataFormatDefinition; 049import org.apache.camel.spi.ComponentResolver; 050import org.apache.camel.spi.DataFormat; 051import org.apache.camel.spi.DataFormatResolver; 052import org.apache.camel.spi.Injector; 053import org.apache.camel.spi.Language; 054import org.apache.camel.spi.LanguageResolver; 055import org.apache.camel.spi.PackageScanFilter; 056import org.apache.camel.spi.TypeConverterLoader; 057import org.apache.camel.spi.TypeConverterRegistry; 058import org.apache.camel.util.IOHelper; 059import org.apache.camel.util.ObjectHelper; 060import org.apache.camel.util.StringHelper; 061import org.osgi.framework.Bundle; 062import org.osgi.framework.BundleActivator; 063import org.osgi.framework.BundleContext; 064import org.osgi.framework.BundleEvent; 065import org.osgi.framework.Constants; 066import org.osgi.framework.ServiceRegistration; 067import org.osgi.framework.wiring.BundleCapability; 068import org.osgi.framework.wiring.BundleWire; 069import org.osgi.framework.wiring.BundleWiring; 070import org.slf4j.Logger; 071import org.slf4j.LoggerFactory; 072 073import static org.osgi.framework.wiring.BundleRevision.PACKAGE_NAMESPACE; 074 075public class Activator implements BundleActivator, BundleTrackerCustomizer { 076 077 public static final String META_INF_COMPONENT = "META-INF/services/org/apache/camel/component/"; 078 public static final String META_INF_LANGUAGE = "META-INF/services/org/apache/camel/language/"; 079 public static final String META_INF_LANGUAGE_RESOLVER = "META-INF/services/org/apache/camel/language/resolver/"; 080 public static final String META_INF_DATAFORMAT = "META-INF/services/org/apache/camel/dataformat/"; 081 public static final String META_INF_TYPE_CONVERTER = "META-INF/services/org/apache/camel/TypeConverter"; 082 public static final String META_INF_FALLBACK_TYPE_CONVERTER = "META-INF/services/org/apache/camel/FallbackTypeConverter"; 083 084 private static final Logger LOG = LoggerFactory.getLogger(Activator.class); 085 086 private BundleTracker tracker; 087 private final Map<Long, List<BaseService>> resolvers = new ConcurrentHashMap<Long, List<BaseService>>(); 088 private long bundleId; 089 090 // Map from package name to the capability we export for this package 091 private final Map<String, BundleCapability> packageCapabilities = new HashMap<String, BundleCapability>(); 092 093 public void start(BundleContext context) throws Exception { 094 LOG.info("Camel activator starting"); 095 bundleId = context.getBundle().getBundleId(); 096 tracker = new BundleTracker(context, Bundle.ACTIVE, this); 097 cachePackageCapabilities(context); 098 tracker.open(); 099 LOG.info("Camel activator started"); 100 } 101 102 public void stop(BundleContext context) throws Exception { 103 LOG.info("Camel activator stopping"); 104 tracker.close(); 105 packageCapabilities.clear(); 106 LOG.info("Camel activator stopped"); 107 } 108 109 /** 110 * Caches the package capabilities that are needed for a set of interface classes 111 */ 112 private void cachePackageCapabilities(BundleContext context) { 113 BundleWiring ourWiring = context.getBundle().adapt(BundleWiring.class); 114 List<BundleCapability> ourExports = ourWiring.getCapabilities(PACKAGE_NAMESPACE); 115 for (BundleCapability ourExport : ourExports) { 116 String ourPkgName = (String) ourExport.getAttributes().get(PACKAGE_NAMESPACE); 117 packageCapabilities.put(ourPkgName, ourExport); 118 } 119 } 120 121 public Object addingBundle(Bundle bundle, BundleEvent event) { 122 LOG.debug("Bundle started: {}", bundle.getSymbolicName()); 123 List<BaseService> r = new ArrayList<BaseService>(); 124 registerComponents(bundle, r); 125 registerLanguages(bundle, r); 126 registerDataFormats(bundle, r); 127 registerTypeConverterLoader(bundle, r); 128 for (BaseService service : r) { 129 service.register(); 130 } 131 resolvers.put(bundle.getBundleId(), r); 132 return bundle; 133 } 134 135 public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) { 136 } 137 138 public void removedBundle(Bundle bundle, BundleEvent event, Object object) { 139 LOG.debug("Bundle stopped: {}", bundle.getSymbolicName()); 140 List<BaseService> r = resolvers.remove(bundle.getBundleId()); 141 if (r != null) { 142 for (BaseService service : r) { 143 service.unregister(); 144 } 145 } 146 } 147 148 protected void registerComponents(Bundle bundle, List<BaseService> resolvers) { 149 if (canSee(bundle, Component.class)) { 150 Map<String, String> components = new HashMap<String, String>(); 151 for (Enumeration<?> e = bundle.getEntryPaths(META_INF_COMPONENT); e != null && e.hasMoreElements();) { 152 String path = (String) e.nextElement(); 153 LOG.debug("Found entry: {} in bundle {}", path, bundle.getSymbolicName()); 154 String name = path.substring(path.lastIndexOf("/") + 1); 155 components.put(name, path); 156 } 157 if (!components.isEmpty()) { 158 resolvers.add(new BundleComponentResolver(bundle, components)); 159 } 160 } 161 } 162 163 protected void registerLanguages(Bundle bundle, List<BaseService> resolvers) { 164 if (canSee(bundle, Language.class)) { 165 Map<String, String> languages = new HashMap<String, String>(); 166 for (Enumeration<?> e = bundle.getEntryPaths(META_INF_LANGUAGE); e != null && e.hasMoreElements();) { 167 String path = (String) e.nextElement(); 168 LOG.debug("Found entry: {} in bundle {}", path, bundle.getSymbolicName()); 169 String name = path.substring(path.lastIndexOf("/") + 1); 170 languages.put(name, path); 171 } 172 if (!languages.isEmpty()) { 173 resolvers.add(new BundleLanguageResolver(bundle, languages)); 174 } 175 for (Enumeration<?> e = bundle.getEntryPaths(META_INF_LANGUAGE_RESOLVER); e != null && e.hasMoreElements();) { 176 String path = (String) e.nextElement(); 177 LOG.debug("Found entry: {} in bundle {}", path, bundle.getSymbolicName()); 178 String name = path.substring(path.lastIndexOf("/") + 1); 179 resolvers.add(new BundleMetaLanguageResolver(bundle, name, path)); 180 } 181 } 182 } 183 184 protected void registerDataFormats(Bundle bundle, List<BaseService> resolvers) { 185 if (canSee(bundle, DataFormat.class)) { 186 Map<String, String> dataformats = new HashMap<String, String>(); 187 for (Enumeration<?> e = bundle.getEntryPaths(META_INF_DATAFORMAT); e != null && e.hasMoreElements();) { 188 String path = (String) e.nextElement(); 189 LOG.debug("Found entry: {} in bundle {}", path, bundle.getSymbolicName()); 190 String name = path.substring(path.lastIndexOf("/") + 1); 191 dataformats.put(name, path); 192 } 193 if (!dataformats.isEmpty()) { 194 resolvers.add(new BundleDataFormatResolver(bundle, dataformats)); 195 } 196 } 197 } 198 199 protected void registerTypeConverterLoader(Bundle bundle, List<BaseService> resolvers) { 200 if (canSee(bundle, TypeConverter.class)) { 201 URL url1 = bundle.getEntry(META_INF_TYPE_CONVERTER); 202 URL url2 = bundle.getEntry(META_INF_FALLBACK_TYPE_CONVERTER); 203 if (url1 != null || url2 != null) { 204 LOG.debug("Found TypeConverter in bundle {}", bundle.getSymbolicName()); 205 resolvers.add(new BundleTypeConverterLoader(bundle, url2 != null)); 206 } 207 } 208 } 209 210 /** 211 * Check if bundle can see the given class 212 */ 213 protected boolean canSee(Bundle bundle, Class<?> clazz) { 214 if (bundle.getBundleId() == bundleId) { 215 // Need extra handling of camel core as it does not import the api 216 return true; 217 } 218 BundleCapability packageCap = packageCapabilities.get(clazz.getPackage().getName()); 219 BundleWiring wiring = bundle.adapt(BundleWiring.class); 220 List<BundleWire> imports = wiring.getRequiredWires(PACKAGE_NAMESPACE); 221 for (BundleWire importWire : imports) { 222 if (packageCap.equals(importWire.getCapability())) { 223 return true; 224 } 225 } 226 return false; 227 } 228 229 protected static class BundleComponentResolver extends BaseResolver<Component> implements ComponentResolver { 230 231 private final Map<String, String> components; 232 233 public BundleComponentResolver(Bundle bundle, Map<String, String> components) { 234 super(bundle, Component.class); 235 this.components = components; 236 } 237 238 public Component resolveComponent(String name, CamelContext context) throws Exception { 239 return createInstance(name, components.get(name), context); 240 } 241 242 public void register() { 243 doRegister(ComponentResolver.class, "component", components.keySet()); 244 } 245 } 246 247 protected static class BundleLanguageResolver extends BaseResolver<Language> implements LanguageResolver { 248 249 private final Map<String, String> languages; 250 251 public BundleLanguageResolver(Bundle bundle, Map<String, String> languages) { 252 super(bundle, Language.class); 253 this.languages = languages; 254 } 255 256 public Language resolveLanguage(String name, CamelContext context) { 257 return createInstance(name, languages.get(name), context); 258 } 259 260 public void register() { 261 doRegister(LanguageResolver.class, "language", languages.keySet()); 262 } 263 } 264 265 protected static class BundleMetaLanguageResolver extends BaseResolver<LanguageResolver> implements LanguageResolver { 266 267 private final String name; 268 private final String path; 269 270 public BundleMetaLanguageResolver(Bundle bundle, String name, String path) { 271 super(bundle, LanguageResolver.class); 272 this.name = name; 273 this.path = path; 274 } 275 276 public Language resolveLanguage(String name, CamelContext context) { 277 LanguageResolver resolver = createInstance(this.name, path, context); 278 return resolver.resolveLanguage(name, context); 279 } 280 281 public void register() { 282 doRegister(LanguageResolver.class, "resolver", name); 283 } 284 } 285 286 protected static class BundleDataFormatResolver extends BaseResolver<DataFormat> implements DataFormatResolver { 287 288 private final Map<String, String> dataformats; 289 290 public BundleDataFormatResolver(Bundle bundle, Map<String, String> dataformats) { 291 super(bundle, DataFormat.class); 292 this.dataformats = dataformats; 293 } 294 295 public DataFormat resolveDataFormat(String name, CamelContext context) { 296 return createInstance(name, dataformats.get(name), context); 297 } 298 299 public DataFormatDefinition resolveDataFormatDefinition(String name, CamelContext context) { 300 return null; 301 } 302 303 public void register() { 304 doRegister(DataFormatResolver.class, "dataformat", dataformats.keySet()); 305 } 306 } 307 308 protected static class BundleTypeConverterLoader extends BaseResolver<TypeConverter> implements TypeConverterLoader { 309 310 private final AnnotationTypeConverterLoader loader = new Loader(); 311 private final Bundle bundle; 312 private final boolean hasFallbackTypeConverter; 313 314 public BundleTypeConverterLoader(Bundle bundle, boolean hasFallbackTypeConverter) { 315 super(bundle, TypeConverter.class); 316 ObjectHelper.notNull(bundle, "bundle"); 317 this.bundle = bundle; 318 this.hasFallbackTypeConverter = hasFallbackTypeConverter; 319 } 320 321 public synchronized void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { 322 // must be synchronized to ensure we don't load type converters concurrently 323 // which cause Camel apps to fails in OSGi thereafter 324 try { 325 loader.load(registry); 326 } catch (Exception e) { 327 throw new TypeConverterLoaderException("Cannot load type converters using OSGi bundle: " + bundle.getBundleId(), e); 328 } 329 } 330 331 public void register() { 332 if (hasFallbackTypeConverter) { 333 // The FallbackTypeConverter should have a higher ranking 334 doRegister(TypeConverterLoader.class, Constants.SERVICE_RANKING, 100); 335 } else { 336 // The default service ranking is Integer(0); 337 doRegister(TypeConverterLoader.class); 338 } 339 } 340 341 class Loader extends AnnotationTypeConverterLoader { 342 343 Loader() { 344 super(null); 345 } 346 347 public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { 348 PackageScanFilter test = new AnnotatedWithPackageScanFilter(Converter.class, true); 349 Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); 350 Set<String> packages = getConverterPackages(bundle.getEntry(META_INF_TYPE_CONVERTER)); 351 352 if (LOG.isTraceEnabled()) { 353 LOG.trace("Found {} {} packages: {}", new Object[]{packages.size(), META_INF_TYPE_CONVERTER, packages}); 354 } 355 // if we only have camel-core on the classpath then we have already pre-loaded all its type converters 356 // but we exposed the "org.apache.camel.core" package in camel-core. This ensures there is at least one 357 // packageName to scan, which triggers the scanning process. That allows us to ensure that we look for 358 // META-INF/services in all the JARs. 359 if (packages.size() == 1 && "org.apache.camel.core".equals(packages.iterator().next())) { 360 LOG.debug("No additional package names found in classpath for annotated type converters."); 361 // no additional package names found to load type converters so break out 362 return; 363 } 364 365 // now filter out org.apache.camel.core as its not needed anymore (it was just a dummy) 366 packages.remove("org.apache.camel.core"); 367 368 for (String pkg : packages) { 369 370 if (StringHelper.isClassName(pkg)) { 371 // its a FQN class name so load it directly 372 LOG.trace("Loading {} class", pkg); 373 try { 374 Class<?> clazz = bundle.loadClass(pkg); 375 if (test.matches(clazz)) { 376 classes.add(clazz); 377 } 378 // the class could be found and loaded so continue to next 379 continue; 380 } catch (Throwable t) { 381 // Ignore 382 LOG.trace("Failed to load " + pkg + " class due " + t.getMessage() + ". This exception will be ignored.", t); 383 } 384 } 385 386 // its not a FQN but a package name so scan for classes in the bundle 387 Enumeration<URL> e = bundle.findEntries("/" + pkg.replace('.', '/'), "*.class", true); 388 while (e != null && e.hasMoreElements()) { 389 String path = e.nextElement().getPath(); 390 String externalName = path.substring(path.charAt(0) == '/' ? 1 : 0, path.indexOf('.')).replace('/', '.'); 391 LOG.trace("Loading {} class", externalName); 392 try { 393 Class<?> clazz = bundle.loadClass(externalName); 394 if (test.matches(clazz)) { 395 classes.add(clazz); 396 } 397 } catch (Throwable t) { 398 // Ignore 399 LOG.trace("Failed to load " + externalName + " class due " + t.getMessage() + ". This exception will be ignored.", t); 400 } 401 } 402 } 403 404 // load the classes into type converter registry 405 LOG.debug("Found {} @Converter classes to load", classes.size()); 406 for (Class<?> type : classes) { 407 if (LOG.isTraceEnabled()) { 408 LOG.trace("Loading converter class: {}", ObjectHelper.name(type)); 409 } 410 loadConverterMethods(registry, type); 411 } 412 413 // register fallback converters 414 URL fallbackUrl = bundle.getEntry(META_INF_FALLBACK_TYPE_CONVERTER); 415 if (fallbackUrl != null) { 416 LOG.debug("Found {} to load the FallbackTypeConverter", META_INF_FALLBACK_TYPE_CONVERTER); 417 TypeConverter tc = createInstance("FallbackTypeConverter", fallbackUrl, registry.getInjector()); 418 registry.addFallbackTypeConverter(tc, false); 419 } 420 421 // now clear the maps so we do not hold references 422 visitedClasses.clear(); 423 visitedURIs.clear(); 424 } 425 } 426 427 } 428 429 protected abstract static class BaseResolver<T> extends BaseService { 430 431 private final Class<T> type; 432 433 public BaseResolver(Bundle bundle, Class<T> type) { 434 super(bundle); 435 this.type = type; 436 } 437 438 protected T createInstance(String name, String path, CamelContext context) { 439 if (path == null) { 440 return null; 441 } 442 URL url = bundle.getEntry(path); 443 LOG.trace("The entry {}'s url is {}", name, url); 444 //Setup the TCCL with Camel context application class loader 445 ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); 446 try { 447 ClassLoader newClassLoader = context.getApplicationContextClassLoader(); 448 if (newClassLoader != null) { 449 Thread.currentThread().setContextClassLoader(newClassLoader); 450 } 451 T answer = createInstance(name, url, context.getInjector()); 452 if (answer != null) { 453 initBundleContext(answer); 454 } 455 return answer; 456 } finally { 457 Thread.currentThread().setContextClassLoader(oldClassLoader); 458 } 459 } 460 461 private void initBundleContext(T answer) { 462 try { 463 Method method = answer.getClass().getMethod("setBundleContext", BundleContext.class); 464 if (method != null) { 465 method.invoke(answer, bundle.getBundleContext()); 466 } 467 } catch (Exception e) { 468 // ignore 469 } 470 } 471 472 @SuppressWarnings("unchecked") 473 protected T createInstance(String name, URL url, Injector injector) { 474 try { 475 Properties properties = loadProperties(url); 476 String classname = (String) properties.get("class"); 477 Class<?> type = bundle.loadClass(classname); 478 if (!this.type.isAssignableFrom(type)) { 479 throw new IllegalArgumentException("Type is not a " + this.type.getName() + " implementation. Found: " + type.getName()); 480 } 481 return injector.newInstance((Class<T>) type); 482 } catch (ClassNotFoundException e) { 483 throw new IllegalArgumentException("Invalid URI, no " + this.type.getName() + " registered for scheme : " + name, e); 484 } 485 } 486 487 } 488 489 protected abstract static class BaseService { 490 491 protected final Bundle bundle; 492 private ServiceRegistration<?> reg; 493 494 protected BaseService(Bundle bundle) { 495 this.bundle = bundle; 496 } 497 498 public abstract void register(); 499 500 protected void doRegister(Class<?> type, String key, Collection<String> value) { 501 doRegister(type, key, value.toArray(new String[value.size()])); 502 } 503 504 protected void doRegister(Class<?> type, String key, Object value) { 505 Dictionary<String, Object> props = new Hashtable<String, Object>(); 506 props.put(key, value); 507 doRegister(type, props); 508 } 509 510 protected void doRegister(Class<?> type) { 511 doRegister(type, null); 512 } 513 514 protected void doRegister(Class<?> type, Dictionary<String, ?> props) { 515 reg = bundle.getBundleContext().registerService(type.getName(), this, props); 516 } 517 518 public void unregister() { 519 reg.unregister(); 520 } 521 } 522 523 protected static Properties loadProperties(URL url) { 524 Properties properties = new Properties(); 525 BufferedInputStream reader = null; 526 try { 527 reader = IOHelper.buffered(url.openStream()); 528 properties.load(reader); 529 } catch (IOException e) { 530 throw new RuntimeException(e); 531 } finally { 532 IOHelper.close(reader, "properties", LOG); 533 } 534 return properties; 535 } 536 537 protected static Set<String> getConverterPackages(URL resource) { 538 Set<String> packages = new LinkedHashSet<String>(); 539 if (resource != null) { 540 BufferedReader reader = null; 541 try { 542 reader = IOHelper.buffered(new InputStreamReader(resource.openStream())); 543 while (true) { 544 String line = reader.readLine(); 545 if (line == null) { 546 break; 547 } 548 line = line.trim(); 549 if (line.startsWith("#") || line.length() == 0) { 550 continue; 551 } 552 StringTokenizer iter = new StringTokenizer(line, ","); 553 while (iter.hasMoreTokens()) { 554 String name = iter.nextToken().trim(); 555 if (name.length() > 0) { 556 packages.add(name); 557 } 558 } 559 } 560 } catch (Exception ignore) { 561 // Do nothing here 562 } finally { 563 IOHelper.close(reader, null, LOG); 564 } 565 } 566 return packages; 567 } 568 569} 570