2 * Copyright (c) 2013, 2017 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 final class OsgiRegistrationUtil {
24 private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
26 private OsgiRegistrationUtil() {
30 public static <T> AutoCloseable registerService(final BundleContext bundleContext, final T service,
31 final Class<? super T>... interfaces) {
32 checkNotNull(service);
33 checkNotNull(interfaces);
34 List<AutoCloseable> autoCloseableList = new ArrayList<>();
35 for (Class<? super T> ifc : interfaces) {
36 ServiceRegistration<? super T> serviceRegistration = bundleContext.registerService(ifc, service, null);
37 autoCloseableList.add(wrap(serviceRegistration));
39 return aggregate(autoCloseableList);
42 public static AutoCloseable wrap(final ServiceRegistration<?> reg) {
44 return reg::unregister;
47 public static AutoCloseable wrap(final BundleTracker<?> bundleTracker) {
48 checkNotNull(bundleTracker);
49 return bundleTracker::close;
52 public static AutoCloseable wrap(final ServiceTracker<?, ?> serviceTracker) {
53 checkNotNull(serviceTracker);
54 return serviceTracker::close;
57 @SuppressWarnings("IllegalCatch")
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 (final Exception e) {
68 LOG.warn("Exception while closing {}", ac, e);
69 if (firstException == null) {
72 firstException.addSuppressed(e);
76 if (firstException != null) {