d7ba47c3425363a5fd93e8764efb13b9c817f888
[openflowplugin.git] / extension / openflowplugin-extension-api / src / main / java / org / opendaylight / openflowplugin / extension / api / GroupingLooseResolver.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.openflowplugin.extension.api;
9
10 import java.util.HashSet;
11 import java.util.Set;
12
13 import org.opendaylight.yangtools.yang.binding.Augmentable;
14 import org.opendaylight.yangtools.yang.binding.Augmentation;
15 import org.opendaylight.yangtools.yang.binding.DataObject;
16
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19
20 /**
21  * Provides augmentation resolving upon given {@link Augmentable}. 
22  * Used {@link Augmentation}s do not share {@link Augmentable}.
23  * <br/>
24  * <b>Usage:</b> in case there are multiple {@link Augmentable} classes which might contain
25  * corresponding {@link Augmentation}s (1:1..n binding). And those {@link Augmentation}s 
26  * are sharing the same grouping so that they could be processed in the same way.
27  * 
28  * @param <GROUPING>
29  */
30 public class GroupingLooseResolver<GROUPING> {
31
32     Class<GROUPING> commonInterface;
33     Set<Class<? extends Augmentation<?>>> classes;
34
35     /**
36      * @param commonInterface
37      * @param common grouping Interface
38      */
39     public GroupingLooseResolver(Class<GROUPING> commonInterface) {
40         this.commonInterface = commonInterface;
41         classes = new HashSet<>();
42     }
43
44     /**
45      * @param cls equivalent augmentation class
46      * @return this for chaining
47      */
48     public GroupingLooseResolver<GROUPING> add(Class<? extends Augmentation<?>> cls) {
49         Preconditions.checkArgument(commonInterface.isAssignableFrom(cls),
50                 "oh man! I got " + cls);
51         classes.add(cls);
52         return this;
53     }
54
55     /**
56      * @param data expected to match <tt>&lt;T extends Augmentable&lt;T&gt;&gt;</tt>
57      * @return shared grouping
58      */
59     @SuppressWarnings("unchecked")
60     public <T extends Augmentable<T>> Optional<GROUPING> getExtension(DataObject data) {
61         T guessData = (T) data;
62
63         for (Class<? extends Augmentation<?>> cls : classes) {
64             Augmentation<T> potential = guessData
65                     .getAugmentation((Class<Augmentation<T>>) cls);
66             if (potential != null) {
67                 return Optional.of((GROUPING) potential);
68             }
69         }
70
71         return Optional.absent();
72     }
73 }