View Javadoc
1   package com.atlassian.sal.core.component;
2   
3   import com.atlassian.sal.api.component.ComponentLocator;
4   import com.atlassian.sal.spi.HostContextAccessor;
5   import org.slf4j.Logger;
6   import org.slf4j.LoggerFactory;
7   
8   import java.util.Collection;
9   import java.util.Map;
10  
11  public class DefaultComponentLocator extends ComponentLocator {
12      private static final Logger log = LoggerFactory.getLogger(DefaultComponentLocator.class);
13  
14      private final HostContextAccessor hostContextAccessor;
15  
16      public DefaultComponentLocator(final HostContextAccessor accessor) {
17          this.hostContextAccessor = accessor;
18          ComponentLocator.setComponentLocator(this);
19      }
20  
21      @Override
22      protected <T> T getComponentInternal(final Class<T> iface) {
23          final Map<String, T> beansOfType = hostContextAccessor.getComponentsOfType(iface);
24  
25          if (beansOfType == null || beansOfType.isEmpty()) {
26              return null;
27          } else if (beansOfType.size() > 1) {
28              // we have multiple implementations of this interface, choose one with name that looks like iface name
29              final String shortClassName = convertClassToName(iface);
30              final T implementation = beansOfType.get(shortClassName);
31              if (implementation == null) {
32                  log.warn("More than one instance of " + iface.getName() + " found but none of them has key " + shortClassName);
33              }
34              return implementation;
35          }
36          return beansOfType.values().iterator().next();
37      }
38  
39      @Override
40      protected <T> T getComponentInternal(final Class<T> iface, final String componentId) {
41          final Map<String, T> beansOfType = hostContextAccessor.getComponentsOfType(iface);
42  
43          return beansOfType.get(componentId);
44      }
45  
46      @Override
47      protected <T> Collection<T> getComponentsInternal(final Class<T> iface) {
48          final Map<String, T> beansOfType = hostContextAccessor.getComponentsOfType(iface);
49          return (beansOfType != null ? beansOfType.values() : null);
50      }
51  }