blob: bc401fb4ffad6a3580168c63dd9bc1a262184b1c [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001package org.onlab.osgi;
2
3import org.osgi.framework.BundleContext;
4import org.osgi.framework.FrameworkUtil;
tomcaf3bf72014-09-23 13:20:53 -07005import org.osgi.framework.ServiceReference;
tom0eb04ca2014-08-25 14:34:51 -07006
7/**
8 * Default implementation of the service directory using OSGi framework utilities.
9 */
10public class DefaultServiceDirectory implements ServiceDirectory {
tom0872a172014-09-23 11:24:26 -070011
12 /**
13 * Returns the reference to the implementation of the specified service.
14 *
15 * @param serviceClass service class
16 * @param <T> type of service
17 * @return service implementation
18 */
19 public static <T> T getService(Class<T> serviceClass) {
tom0eb04ca2014-08-25 14:34:51 -070020 BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext();
tomcaf3bf72014-09-23 13:20:53 -070021 if (bc != null) {
22 ServiceReference<T> reference = bc.getServiceReference(serviceClass);
23 if (reference != null) {
24 T impl = bc.getService(reference);
25 if (impl != null) {
26 return impl;
27 }
28 }
tom0eb04ca2014-08-25 14:34:51 -070029 }
tomcaf3bf72014-09-23 13:20:53 -070030 throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found");
tom0eb04ca2014-08-25 14:34:51 -070031 }
tom0872a172014-09-23 11:24:26 -070032
33 @Override
34 public <T> T get(Class<T> serviceClass) {
35 return getService(serviceClass);
36 }
37
tom0eb04ca2014-08-25 14:34:51 -070038}