View Javadoc

1   package com.atlassian.plugin.osgi.factory;
2   
3   import com.atlassian.plugin.ModuleDescriptor;
4   import com.atlassian.plugin.event.PluginEventManager;
5   import com.atlassian.plugin.event.events.PluginModuleAvailableEvent;
6   import com.atlassian.plugin.event.events.PluginModuleUnavailableEvent;
7   import org.osgi.framework.Bundle;
8   import org.osgi.framework.ServiceReference;
9   import org.osgi.util.tracker.ServiceTrackerCustomizer;
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  import static com.google.common.base.Preconditions.checkNotNull;
14  
15  /**
16   * Tracks module descriptors registered as services, then updates the descriptors map accordingly
17   *
18   * @since 2.2.0
19   */
20  class ModuleDescriptorServiceTrackerCustomizer implements ServiceTrackerCustomizer
21  {
22      private static final Logger log = LoggerFactory.getLogger(ModuleDescriptorServiceTrackerCustomizer.class);
23  
24      private final Bundle bundle;
25      private final OsgiPlugin plugin;
26      private final PluginEventManager pluginEventManager;
27  
28      public ModuleDescriptorServiceTrackerCustomizer(OsgiPlugin plugin, PluginEventManager pluginEventManager)
29      {
30          this.plugin = checkNotNull(plugin);
31          this.bundle = checkNotNull(plugin.getBundle());
32          this.pluginEventManager = checkNotNull(pluginEventManager);
33      }
34  
35      public Object addingService(final ServiceReference serviceReference)
36      {
37          ModuleDescriptor<?> descriptor = null;
38          if (serviceReference.getBundle() == bundle)
39          {
40              descriptor = (ModuleDescriptor<?>) bundle.getBundleContext().getService(serviceReference);
41              plugin.addModuleDescriptor(descriptor);
42              if (log.isInfoEnabled())
43              {
44                  log.info("Dynamically registered new module descriptor: " + descriptor.getCompleteKey());
45              }
46              pluginEventManager.broadcast(new PluginModuleAvailableEvent(descriptor));
47          }
48          return descriptor;
49      }
50  
51      public void modifiedService(final ServiceReference serviceReference, final Object o)
52      {
53          // Don't bother doing anything as it only represents a change in properties
54      }
55  
56      public void removedService(final ServiceReference serviceReference, final Object o)
57      {
58          if (serviceReference.getBundle() == bundle)
59          {
60              final ModuleDescriptor<?> descriptor = (ModuleDescriptor<?>) o;
61              plugin.clearModuleDescriptor(descriptor.getKey());
62              if (log.isInfoEnabled())
63              {
64                  log.info("Dynamically removed module descriptor: " + descriptor.getCompleteKey());
65              }
66              pluginEventManager.broadcast(new PluginModuleUnavailableEvent(descriptor));
67          }
68      }
69  }