Introduce common directory
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / CompositeObjectRegistration.java
1 /*
2  * Copyright (c) 2013 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.yangtools.concepts;
9
10 import java.util.Collection;
11 import java.util.Collections;
12 import java.util.HashSet;
13 import java.util.Set;
14
15 public final class CompositeObjectRegistration<T> extends AbstractObjectRegistration<T> {
16
17     private final Set<Registration<? super T>> registrations;
18
19     public CompositeObjectRegistration(T instance, Collection<? extends Registration<? super T>> registrations) {
20         super(instance);
21         if (registrations == null) {
22             throw new IllegalArgumentException();
23         }
24         this.registrations = Collections.unmodifiableSet(new HashSet<>(registrations));
25     }
26
27     @Override
28     protected void removeRegistration() {
29         for (Registration<? super T> registration : registrations) {
30             try {
31                 registration.close();
32             } catch (Exception e) {
33                 e.printStackTrace();
34             }
35         }
36     }
37
38     public static <T> CompositeObjectRegistrationBuilder<T> builderFor(T instance) {
39         return new CompositeObjectRegistrationBuilder<>(instance);
40     }
41
42     public static final class CompositeObjectRegistrationBuilder<T> implements //
43             Builder<CompositeObjectRegistration<T>> {
44
45         private final T instance;
46         private final Set<Registration<? super T>> registrations;
47
48         public CompositeObjectRegistrationBuilder(T instance) {
49             this.instance = instance;
50             registrations = new HashSet<>();
51         }
52
53         public CompositeObjectRegistrationBuilder<T> add(Registration<? super T> registration) {
54             if (registration.getInstance() != instance) {
55                 throw new IllegalArgumentException("Instance must be same.");
56             }
57             registrations.add(registration);
58             return this;
59         }
60
61         public CompositeObjectRegistrationBuilder<T> remove(Registration<? super T> registration) {
62             if (registration.getInstance() != instance) {
63                 throw new IllegalArgumentException("Instance must be same.");
64             }
65             registrations.remove(registration);
66             return this;
67         }
68         
69         @Override
70         public CompositeObjectRegistration<T> toInstance() {
71             return new CompositeObjectRegistration<>(instance, registrations);
72         }
73     }
74 }