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