1   package com.atlassian.plugin.osgi.external;
2   
3   import com.atlassian.plugin.ModuleDescriptor;
4   import com.atlassian.plugin.PluginParseException;
5   import com.atlassian.plugin.hostcontainer.HostContainer;
6   import com.atlassian.plugin.hostcontainer.DefaultHostContainer;
7   
8   import java.util.Collections;
9   import java.util.Set;
10  
11  /**
12   * A single module descriptor factory for plugins to use when they want to expose just one plugin.  Uses
13   * {@link HostContainer} to optionally provide autowiring for new descriptor instances.
14   *
15   * @since 2.1
16   */
17  public class SingleModuleDescriptorFactory<T extends ModuleDescriptor<?>> implements ListableModuleDescriptorFactory
18  {
19      private final String type;
20      private final Class<T> moduleDescriptorClass;
21      private final HostContainer hostContainer;
22  
23      /**
24       * Constructs an instance using a specific host container
25       * @param hostContainer The host container to use to create descriptor instances
26       * @param type The type of module
27       * @param moduleDescriptorClass The descriptor class
28       * @since 2.2.0
29       */
30      public SingleModuleDescriptorFactory(final HostContainer hostContainer, final String type, final Class<T> moduleDescriptorClass)
31      {
32          this.moduleDescriptorClass = moduleDescriptorClass;
33          this.type = type;
34          this.hostContainer = hostContainer;
35      }
36  
37      public ModuleDescriptor getModuleDescriptor(final String type) throws PluginParseException, IllegalAccessException, InstantiationException, ClassNotFoundException
38      {
39          T result = null;
40          if (this.type.equals(type))
41          {
42              // We can't use an autowired bean factory to create the instance because it would be loaded by this class's
43              // classloader, which will not have access to the spring instance in bundle space.
44              result = hostContainer.create(moduleDescriptorClass);
45          }
46          return result;
47      }
48  
49      public boolean hasModuleDescriptor(final String type)
50      {
51          return (this.type.equals(type));
52      }
53  
54      @SuppressWarnings("unchecked")
55      public Class<? extends ModuleDescriptor<?>> getModuleDescriptorClass(final String type)
56      {
57          return (this.type.equals(type) ? moduleDescriptorClass : null);
58      }
59  
60      @SuppressWarnings("unchecked")
61      public Set<Class<ModuleDescriptor<?>>> getModuleDescriptorClasses()
62      {
63          return Collections.singleton((Class<ModuleDescriptor<?>>) moduleDescriptorClass);
64      }
65  }