Migrate DataTreeModification method users
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / AdapterBuilder.java
1 /*
2  * Copyright (c) 2015 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.mdsal.binding.dom.adapter;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.collect.ClassToInstanceMap;
13 import com.google.common.collect.ImmutableClassToInstanceMap;
14 import com.google.common.collect.MutableClassToInstanceMap;
15 import java.util.Set;
16 import org.eclipse.jdt.annotation.NonNull;
17
18 public abstract class AdapterBuilder<T, D> {
19
20     private final ClassToInstanceMap<D> delegates = MutableClassToInstanceMap.create();
21
22     public abstract Set<? extends Class<? extends D>> getRequiredDelegates();
23
24     protected abstract @NonNull T createInstance(@NonNull ClassToInstanceMap<D> immutableDelegates);
25
26     private void checkAllRequiredServices() {
27         for (final Class<? extends D> type : getRequiredDelegates()) {
28             checkState(delegates.get(type) != null, "Requires service %s is not defined.", type);
29         }
30     }
31
32     public final <V extends D> void addDelegate(final Class<V> type,final D impl) {
33         delegates.put(type,impl);
34     }
35
36     /**
37      * Check that all required {@code delegates} are present and return an instance of type {@code T}.
38      *
39      * @return Instance of {@code T}
40      * @throws IllegalStateException if a required delegate instance is missing
41      */
42     public final @NonNull T build() {
43         checkAllRequiredServices();
44         return createInstance(ImmutableClassToInstanceMap.copyOf(delegates));
45     }
46 }