tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 1 | package org.onlab.osgi; |
| 2 | |
| 3 | import org.osgi.framework.BundleContext; |
| 4 | import org.osgi.framework.FrameworkUtil; |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 5 | import org.osgi.framework.ServiceReference; |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 6 | |
| 7 | /** |
| 8 | * Default implementation of the service directory using OSGi framework utilities. |
| 9 | */ |
| 10 | public class DefaultServiceDirectory implements ServiceDirectory { |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame] | 11 | |
| 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) { |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 20 | BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext(); |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 21 | 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 | } |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 29 | } |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 30 | throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found"); |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 31 | } |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame] | 32 | |
| 33 | @Override |
| 34 | public <T> T get(Class<T> serviceClass) { |
| 35 | return getService(serviceClass); |
| 36 | } |
| 37 | |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 38 | } |