View Javadoc

1   package com.atlassian.plugin.spring.pluginns;
2   
3   import com.atlassian.plugin.osgi.hostcomponents.HostComponentProvider;
4   import com.atlassian.plugin.osgi.hostcomponents.ComponentRegistrar;
5   
6   import java.util.List;
7   import java.util.ArrayList;
8   
9   import org.springframework.beans.factory.BeanFactoryAware;
10  import org.springframework.beans.factory.BeanFactory;
11  import org.springframework.beans.factory.HierarchicalBeanFactory;
12  import org.springframework.beans.factory.support.BeanDefinitionRegistry;
13  import org.springframework.beans.BeansException;
14  
15  /**
16   * Host component provider that uses <code>plugin:available="true"</code> attributes in Spring XML bean configuration
17   * elements to determine which host components to provide to plugins.
18   */
19  public class SpringXmlHostComponentProvider implements HostComponentProvider, BeanFactoryAware
20  {
21      public static final String HOST_COMPONENT_PROVIDER = "hostComponentProvider";
22      private BeanFactory beanFactory;
23      private List<String> beans;
24  
25      public void setRegistrations(List<String> names)
26      {
27          this.beans = names;
28      }
29  
30      public void provide(ComponentRegistrar registrar)
31      {
32          for (String name : beans)
33          {
34              Object bean = beanFactory.getBean(name);
35              registrar.register(findInterfaces(bean.getClass())).forInstance(bean)
36                      .withName(name);
37          }
38          if (beanFactory instanceof HierarchicalBeanFactory)
39          {
40              HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) beanFactory;
41              if (hbf.getParentBeanFactory() != null)
42              {
43                  HostComponentProvider provider = (HostComponentProvider) hbf.getParentBeanFactory().getBean(HOST_COMPONENT_PROVIDER);
44                  if (provider != null)
45                      provider.provide(registrar);
46              }
47          }
48      }
49  
50      public void setBeanFactory(BeanFactory beanFactory) throws BeansException
51      {
52          this.beanFactory = beanFactory;
53      }
54  
55      Class[] findInterfaces(Class cls)
56      {
57          List<Class> validInterfaces = new ArrayList<Class>();
58          Class[] allInterfaces = cls.getInterfaces();
59          for (Class inf : allInterfaces)
60          {
61              if (!inf.getName().startsWith("org.springframework") && !inf.getName().startsWith("java."))
62                  validInterfaces.add(inf);
63          }
64          return validInterfaces.toArray(new Class[0]);
65      }
66  
67  }