Thomas Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | * or more contributor license agreements. See the NOTICE file |
| 4 | * distributed with this work for additional information |
| 5 | * regarding copyright ownership. The ASF licenses this file |
| 6 | * to you under the Apache License, Version 2.0 (the |
| 7 | * "License"); you may not use this file except in compliance |
| 8 | * with the License. You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, |
| 13 | * software distributed under the License is distributed on an |
| 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | * KIND, either express or implied. See the License for the |
| 16 | * specific language governing permissions and limitations |
| 17 | * under the License. |
| 18 | */ |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 19 | package org.onlab.osgi; |
| 20 | |
| 21 | import org.osgi.framework.BundleContext; |
| 22 | import org.osgi.framework.FrameworkUtil; |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 23 | import org.osgi.framework.ServiceReference; |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 24 | |
| 25 | /** |
| 26 | * Default implementation of the service directory using OSGi framework utilities. |
| 27 | */ |
| 28 | public class DefaultServiceDirectory implements ServiceDirectory { |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame] | 29 | |
| 30 | /** |
| 31 | * Returns the reference to the implementation of the specified service. |
| 32 | * |
| 33 | * @param serviceClass service class |
| 34 | * @param <T> type of service |
| 35 | * @return service implementation |
| 36 | */ |
| 37 | public static <T> T getService(Class<T> serviceClass) { |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 38 | BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext(); |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 39 | if (bc != null) { |
| 40 | ServiceReference<T> reference = bc.getServiceReference(serviceClass); |
| 41 | if (reference != null) { |
| 42 | T impl = bc.getService(reference); |
| 43 | if (impl != null) { |
| 44 | return impl; |
| 45 | } |
| 46 | } |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 47 | } |
tom | caf3bf7 | 2014-09-23 13:20:53 -0700 | [diff] [blame] | 48 | throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found"); |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 49 | } |
tom | 0872a17 | 2014-09-23 11:24:26 -0700 | [diff] [blame] | 50 | |
| 51 | @Override |
| 52 | public <T> T get(Class<T> serviceClass) { |
| 53 | return getService(serviceClass); |
| 54 | } |
| 55 | |
tom | 0eb04ca | 2014-08-25 14:34:51 -0700 | [diff] [blame] | 56 | } |