blob: 18565d7f396541958eeade8d45ac2e7e91ca2c50 [file] [log] [blame]
Simon Hunt4fc86852015-08-20 17:57:52 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18package org.onosproject.ui.impl.topo;
19
20import org.onosproject.net.Link;
21import org.onosproject.net.LinkKey;
22
23import java.util.Collection;
24import java.util.HashMap;
25import java.util.Map;
26
27import static com.google.common.base.Preconditions.checkNotNull;
28
29/**
30 * Represents a collection of {@link BiLink} concrete classes. These maps
31 * are used to collate a set of unidirectional {@link Link}s into a smaller
32 * set of bi-directional {@link BiLink} derivatives.
33 * <p>
34 * @param <B> the type of bi-link subclass
35 */
36public abstract class BiLinkMap<B extends BiLink> {
37
38 private final Map<LinkKey, B> map = new HashMap<>();
39
40 /**
41 * Creates a new instance of a bi-link. Concrete subclasses should
42 * instantiate and return the appropriate bi-link subclass.
43 *
44 * @param key the link key
45 * @param link the initial link
46 * @return a new instance
47 */
48 public abstract B create(LinkKey key, Link link);
49
50 /**
51 * Adds the given link to our collection, returning the corresponding
52 * bi-link (creating one if needed necessary).
53 *
54 * @param link the link to add to the collection
55 * @return the corresponding bi-link wrapper
56 */
57 public B add(Link link) {
58 LinkKey key = TopoUtils.canonicalLinkKey(checkNotNull(link));
59 B blink = map.get(key);
60 if (blink == null) {
61 // no bi-link yet exists for this link
62 blink = create(key, link);
63 map.put(key, blink);
64 } else {
65 // we have a bi-link for this link.
66 if (!blink.one().equals(link)) {
67 blink.setOther(link);
68 }
69 }
70 return blink;
71 }
72
73 /**
74 * Returns the bi-link instances in the collection.
75 *
76 * @return the bi-links in this map
77 */
78 public Collection<B> biLinks() {
79 return map.values();
80 }
81
82 /**
83 * Returns the number of bi-links in the collection.
84 *
85 * @return number of bi-links
86 */
87 public int size() {
88 return map.size();
89 }
90}