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;
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.ListIterator;
15 import org.osgi.framework.BundleContext;
16 import org.osgi.framework.ServiceRegistration;
17 import org.osgi.util.tracker.BundleTracker;
18 import org.osgi.util.tracker.ServiceTracker;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 public class OsgiRegistrationUtil {
23 private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
25 private OsgiRegistrationUtil() {
29 public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service, final Class<? super T> ... interfaces) {
30 checkNotNull(service);
31 checkNotNull(interfaces);
32 List<AutoCloseable> autoCloseableList = new ArrayList<>();
33 for (Class<? super T> ifc : interfaces) {
34 ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
35 autoCloseableList.add(wrap(serviceRegistration));
37 return aggregate(autoCloseableList);
40 public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
42 return reg::unregister;
45 public static AutoCloseable wrap(final BundleTracker<?> bundleTracker) {
46 checkNotNull(bundleTracker);
47 return bundleTracker::close;
50 public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
51 checkNotNull(serviceTracker);
52 return serviceTracker::close;
56 * Close list of auto closeables in reverse order
58 public static AutoCloseable aggregate(final List<? extends AutoCloseable> list) {
62 Exception firstException = null;
63 for (ListIterator<? extends AutoCloseable> it = list.listIterator(list.size()); it.hasPrevious();) {
64 AutoCloseable ac = it.previous();
67 } catch (Exception e) {
68 LOG.warn("Exception while closing {}", ac, e);
69 if (firstException == null) {
72 firstException.addSuppressed(e);
76 if (firstException != null) {