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);
26 private OsgiRegistrationUtil() {
30 public static <T> AutoCloseable registerService(BundleContext bundleContext, T service, Class<? super T> ... interfaces) {
31 checkNotNull(service);
32 checkNotNull(interfaces);
33 List<AutoCloseable> autoCloseableList = new ArrayList<>();
34 for (Class<? super T> ifc : interfaces) {
35 ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
36 autoCloseableList.add(wrap(serviceRegistration));
38 return aggregate(autoCloseableList);
41 public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
43 return new AutoCloseable() {
45 public void close() throws Exception {
51 public static AutoCloseable wrap(final BundleTracker bundleTracker) {
52 checkNotNull(bundleTracker);
53 return new AutoCloseable() {
55 public void close() throws Exception {
56 bundleTracker.close();
61 public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
62 checkNotNull(serviceTracker);
63 return new AutoCloseable() {
65 public void close() throws Exception {
66 serviceTracker.close();
72 * Close list of auto closeables in reverse order
74 public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
77 return new AutoCloseable() {
79 public void close() throws Exception {
80 Exception firstException = null;
81 for (ListIterator<? extends AutoCloseable> it = list.listIterator(list.size()); it.hasPrevious();) {
82 AutoCloseable ac = it.previous();
85 } catch (Exception e) {
86 LOGGER.warn("Exception while closing {}", ac, e);
87 if (firstException == null) {
90 firstException.addSuppressed(e);
94 if (firstException != null) {