Merge "Initial implementation of the ClusteredDataStore"
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / sal / dom / broker / osgi / AbstractBrokerServiceProxy.java
1 package org.opendaylight.controller.sal.dom.broker.osgi;
2
3 import java.util.Collections;
4 import java.util.HashSet;
5 import java.util.Set;
6
7 import org.opendaylight.controller.sal.core.api.BrokerService;
8 import org.opendaylight.yangtools.concepts.Registration;
9 import org.osgi.framework.ServiceReference;
10 import static com.google.common.base.Preconditions.*;
11
12 public abstract class AbstractBrokerServiceProxy<T extends BrokerService> implements AutoCloseable, BrokerService {
13
14     private T delegate;
15     private final ServiceReference<T> reference;
16
17     public AbstractBrokerServiceProxy(ServiceReference<T> ref, T delegate) {
18         this.delegate = checkNotNull(delegate, "Delegate should not be null.");
19         this.reference = checkNotNull(ref, "Reference should not be null.");
20     }
21
22     protected final T getDelegate() {
23         checkState(delegate != null, "Proxy was closed and unregistered.");
24         return delegate;
25     }
26
27     protected final ServiceReference<T> getReference() {
28         return reference;
29     }
30
31     private Set<Registration<?>> registrations = Collections.synchronizedSet(new HashSet<Registration<?>>());
32
33     protected <R extends Registration<?>> R addRegistration(R registration) {
34         if (registration != null) {
35             registrations.add(registration);
36         }
37         return registration;
38     }
39
40     protected void closeBeforeUnregistrations() {
41         // NOOP
42     }
43
44     protected void closeAfterUnregistrations() {
45         // NOOP
46     }
47
48     @Override
49     public void close() {
50         if (delegate != null) {
51             delegate = null;
52             RuntimeException potentialException = new RuntimeException(
53                     "Uncaught exceptions occured during unregistration");
54             boolean hasSuppressed = false;
55             for (Registration<?> registration : registrations) {
56                 try {
57                     registration.close();
58                 } catch (Exception e) {
59                     potentialException.addSuppressed(e);
60                     hasSuppressed = true;
61                 }
62             }
63             if (hasSuppressed) {
64                 throw potentialException;
65             }
66         }
67     }
68 }