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 static com.google.common.base.Preconditions.checkNotNull;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.ListIterator;
16 import org.osgi.framework.BundleContext;
17 import org.osgi.framework.ServiceRegistration;
18 import org.osgi.util.tracker.BundleTracker;
19 import org.osgi.util.tracker.ServiceTracker;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 public class OsgiRegistrationUtil {
24 private static final Logger logger = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
27 public static <T> AutoCloseable registerService(BundleContext bundleContext, T service, Class<? super T> ... interfaces) {
28 checkNotNull(service);
29 checkNotNull(interfaces);
30 List<AutoCloseable> autoCloseableList = new ArrayList<>();
31 for (Class<? super T> ifc : interfaces) {
32 ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
33 autoCloseableList.add(wrap(serviceRegistration));
35 return aggregate(autoCloseableList);
38 public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
40 return new AutoCloseable() {
42 public void close() throws Exception {
48 public static AutoCloseable wrap(final BundleTracker bundleTracker) {
49 checkNotNull(bundleTracker);
50 return new AutoCloseable() {
52 public void close() throws Exception {
53 bundleTracker.close();
58 public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
59 checkNotNull(serviceTracker);
60 return new AutoCloseable() {
62 public void close() throws Exception {
63 serviceTracker.close();
69 * Close list of auto closeables in reverse order
71 public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
74 return new AutoCloseable() {
76 public void close() throws Exception {
77 Exception firstException = null;
78 for (ListIterator<? extends AutoCloseable> it = list.listIterator(list.size()); it.hasPrevious();) {
79 AutoCloseable ac = it.previous();
82 } catch (Exception e) {
83 logger.warn("Exception while closing {}", ac, e);
84 if (firstException == null) {
87 firstException.addSuppressed(e);
91 if (firstException != null) {