2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.config.manager.impl.util;
11 import org.osgi.framework.BundleContext;
12 import org.osgi.framework.ServiceRegistration;
13 import org.osgi.util.tracker.BundleTracker;
14 import org.osgi.util.tracker.ServiceTracker;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.ListIterator;
22 import static com.google.common.base.Preconditions.checkNotNull;
24 public class OsgiRegistrationUtil {
25 private static final Logger logger = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
28 public static <T> AutoCloseable registerService(BundleContext bundleContext, T service, Class<? super T> ... interfaces) {
29 checkNotNull(service);
30 checkNotNull(interfaces);
31 List<AutoCloseable> autoCloseableList = new ArrayList<>();
32 for (Class<? super T> ifc : interfaces) {
33 ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
34 autoCloseableList.add(wrap(serviceRegistration));
36 return aggregate(autoCloseableList);
39 public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
41 return new AutoCloseable() {
43 public void close() throws Exception {
49 public static AutoCloseable wrap(final BundleTracker bundleTracker) {
50 checkNotNull(bundleTracker);
51 return new AutoCloseable() {
53 public void close() throws Exception {
54 bundleTracker.close();
59 public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
60 checkNotNull(serviceTracker);
61 return new AutoCloseable() {
63 public void close() throws Exception {
64 serviceTracker.close();
70 * Close list of auto closeables in reverse order
72 public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
75 return new AutoCloseable() {
77 public void close() throws Exception {
78 Exception firstException = null;
79 for (ListIterator<? extends AutoCloseable> it = list.listIterator(list.size()); it.hasPrevious();) {
80 AutoCloseable ac = it.previous();
83 } catch (Exception e) {
84 logger.warn("Exception while closing {}", ac, e);
85 if (firstException == null) {
88 firstException.addSuppressed(e);
92 if (firstException != null) {