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