f4d379d437f71909d1ddcf3b63681320d2441472
[openflowplugin.git] / extension / openflowplugin-extension-api / src / main / java / org / opendaylight / openflowplugin / extension / api / GroupingResolver.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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import java.util.HashSet;
13 import java.util.Set;
14 import org.opendaylight.yangtools.yang.binding.Augmentable;
15 import org.opendaylight.yangtools.yang.binding.Augmentation;
16
17 /**
18  * Provides augmentation resolving upon given {@link Augmentable}.
19  * Used {@link #classes} share the same {@link Augmentable}.
20  * <br>
21  * <b>Usage:</b> in case there is {@link Augmentable} which might contain
22  * multiple {@link Augmentation}s depending on origin. And those {@link Augmentation}s
23  * are sharing the same grouping so that they could be processed in the same way.
24  *
25  * @param <G> grouping
26  * @param <T> Augmentable
27  */
28 public class GroupingResolver<G, T extends Augmentable<T>> {
29
30     Class<G> commonInterface;
31     Set<Class<? extends Augmentation<T>>> classes;
32
33     public GroupingResolver(Class<G> commonInterface) {
34         this.commonInterface = commonInterface;
35         classes = new HashSet<>();
36     }
37
38     /**
39      * Adds an augmentation class.
40      *
41      * @param cls equivalent augmentation class
42      * @return this for chaining
43      */
44     public <X extends Augmentation<T>> GroupingResolver<G, T> add(Class<X> cls) {
45         Preconditions.checkArgument(commonInterface.isAssignableFrom(cls));
46         classes.add(cls);
47         return this;
48     }
49
50     /**
51      * Sets the augmentation classes.
52      *
53      * @param clses set of equivalent augmentation classes
54      */
55     public void setAugmentations(Set<Class<? extends Augmentation<T>>> clses) {
56         for (Class<? extends Augmentation<T>> cls : clses) {
57             Preconditions.checkArgument(commonInterface.isAssignableFrom(cls));
58         }
59         classes = clses;
60     }
61
62     /**
63      * Gets the extension for the given data.
64      *
65      * @param data data
66      * @return shared grouping
67      */
68     @SuppressWarnings("unchecked")
69     public Optional<G> getExtension(T data) {
70         for (Class<? extends Augmentation<T>> cls : classes) {
71             Augmentation<T> potential = data.getAugmentation(cls);
72             if (potential != null) {
73                 return Optional.of((G) potential);
74             }
75         }
76         return Optional.absent();
77     }
78 }