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; |
| 5 | |
| 6 | /** |
| 7 | * Default implementation of the service directory using OSGi framework utilities. |
| 8 | */ |
| 9 | public class DefaultServiceDirectory implements ServiceDirectory { |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame^] | 10 | |
| 11 | /** |
| 12 | * Returns the reference to the implementation of the specified service. |
| 13 | * |
| 14 | * @param serviceClass service class |
| 15 | * @param <T> type of service |
| 16 | * @return service implementation |
| 17 | */ |
| 18 | public static <T> T getService(Class<T> serviceClass) { |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 19 | BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext(); |
| 20 | T impl = bc.getService(bc.getServiceReference(serviceClass)); |
| 21 | if (impl == null) { |
| 22 | throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found"); |
| 23 | } |
| 24 | return impl; |
| 25 | } |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame^] | 26 | |
| 27 | @Override |
| 28 | public <T> T get(Class<T> serviceClass) { |
| 29 | return getService(serviceClass); |
| 30 | } |
| 31 | |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 32 | } |