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.BundleContext;
10 import org.osgi.framework.InvalidSyntaxException;
11 import org.osgi.framework.ServiceReference;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 import com.google.common.base.Function;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.Lists;
18
19 class OsgiServiceAccessor<S>
20 {
21 private static final String FILTER = "(plugin=com.atlassian.plugins.rest)";
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 {
33 this.serviceType = Preconditions.checkNotNull(serviceType);
34 this.bundleContext = Preconditions.checkNotNull(bundleContext);
35 this.factory = Preconditions.checkNotNull(factory);
36 }
37
38 Collection<? extends S> get()
39 {
40 try
41 {
42 references = bundleContext.getServiceReferences(serviceType.getName(), FILTER);
43 if (references == null)
44 {
45 return Collections.emptySet();
46 }
47 else
48 {
49 return Lists.transform(Arrays.asList(references), new Function<ServiceReference, S>()
50 {
51 public S apply(@Nullable ServiceReference serviceReference)
52 {
53 return factory.getInstance(bundleContext, serviceReference);
54 }
55 });
56 }
57 }
58 catch (InvalidSyntaxException e)
59 {
60 logger.error("Could not get service references", e);
61 return Collections.emptyList();
62 }
63 }
64
65 void release()
66 {
67 if (references != null)
68 {
69 for (ServiceReference reference : references)
70 {
71 bundleContext.ungetService(reference);
72 }
73 }
74 }
75 }