blob: ab61359d5bdd7c5f96862cde4113dee5d07eb0bd [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
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 */
tom0eb04ca2014-08-25 14:34:51 -070019package org.onlab.osgi;
20
21import org.osgi.framework.BundleContext;
22import org.osgi.framework.FrameworkUtil;
tomcaf3bf72014-09-23 13:20:53 -070023import org.osgi.framework.ServiceReference;
tom0eb04ca2014-08-25 14:34:51 -070024
25/**
26 * Default implementation of the service directory using OSGi framework utilities.
27 */
28public class DefaultServiceDirectory implements ServiceDirectory {
tom0872a172014-09-23 11:24:26 -070029
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) {
tom0eb04ca2014-08-25 14:34:51 -070038 BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext();
tomcaf3bf72014-09-23 13:20:53 -070039 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 }
tom0eb04ca2014-08-25 14:34:51 -070047 }
tomcaf3bf72014-09-23 13:20:53 -070048 throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found");
tom0eb04ca2014-08-25 14:34:51 -070049 }
tom0872a172014-09-23 11:24:26 -070050
51 @Override
52 public <T> T get(Class<T> serviceClass) {
53 return getService(serviceClass);
54 }
55
tom0eb04ca2014-08-25 14:34:51 -070056}