View Javadoc

1   package com.atlassian.plugins.rest.module;
2   
3   import java.util.Arrays;
4   import java.util.Collection;
5   import java.util.Collections;
6   
7   import javax.annotation.Nullable;
8   
9   import org.osgi.framework.*;
10  import org.slf4j.Logger;
11  import org.slf4j.LoggerFactory;
12  
13  import com.google.common.base.Function;
14  import com.google.common.base.Preconditions;
15  import com.google.common.collect.Iterables;
16  import com.google.common.collect.Lists;
17  
18  import static com.google.common.collect.ImmutableList.copyOf;
19  
20  class OsgiServiceAccessor<S> {
21      private static final String FILTER = "(|(plugin=com.atlassian.plugins.rest)(" + Constants.BUNDLE_SYMBOLICNAME + "=%s))";
22  
23      private final Logger logger = LoggerFactory.getLogger(this.getClass());
24  
25      private final Class<S> serviceType;
26      private final BundleContext bundleContext;
27  
28      private ServiceReference[] references;
29      private final OsgiFactory<? extends S> factory;
30  
31      OsgiServiceAccessor(final Class<S> serviceType, final BundleContext bundleContext, final OsgiFactory<? extends S> factory) {
32          this.serviceType = Preconditions.checkNotNull(serviceType);
33          this.bundleContext = Preconditions.checkNotNull(bundleContext);
34          this.factory = Preconditions.checkNotNull(factory);
35      }
36  
37      Collection<? extends S> get() {
38          try {
39              references = bundleContext.getServiceReferences(serviceType.getName(), createFilterString(bundleContext.getBundle()));
40              if (references == null) // no service found
41              {
42                  return Collections.emptySet();
43              } else {
44                  return copyOf(Iterables.transform(Arrays.asList(references), new Function<ServiceReference, S>() {
45                      public S apply(@Nullable ServiceReference serviceReference) {
46                          return factory.getInstance(bundleContext, serviceReference);
47                      }
48                  }));
49              }
50          } catch (InvalidSyntaxException e) {
51              logger.error("Could not get service references", e);
52              return Collections.emptyList();
53          }
54      }
55  
56      void release() {
57          if (references != null) {
58              for (ServiceReference reference : references) {
59                  bundleContext.ungetService(reference);
60              }
61          }
62      }
63  
64      private String createFilterString(Bundle currentBundle) {
65          return String.format(FILTER, currentBundle.getSymbolicName());
66      }
67  }