blob: 17cafd09b2eae8a520a83bbbfaf3e36b0b5d8639 [file] [log] [blame]
Simon Hunt4fc86852015-08-20 17:57:52 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Simon Hunt4fc86852015-08-20 17:57:52 -07003 *
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.
Simon Hunt4fc86852015-08-20 17:57:52 -070015 */
16
Simon Hunt191c84a2015-08-21 08:24:48 -070017package org.onosproject.ui.topo;
Simon Hunt4fc86852015-08-20 17:57:52 -070018
19import org.onosproject.net.Link;
20import org.onosproject.net.LinkKey;
21
22import java.util.Collection;
23import java.util.HashMap;
24import java.util.Map;
25
26import static com.google.common.base.Preconditions.checkNotNull;
27
28/**
29 * Represents a collection of {@link BiLink} concrete classes. These maps
30 * are used to collate a set of unidirectional {@link Link}s into a smaller
31 * set of bi-directional {@link BiLink} derivatives.
32 * <p>
33 * @param <B> the type of bi-link subclass
34 */
35public abstract class BiLinkMap<B extends BiLink> {
36
37 private final Map<LinkKey, B> map = new HashMap<>();
38
39 /**
40 * Creates a new instance of a bi-link. Concrete subclasses should
41 * instantiate and return the appropriate bi-link subclass.
42 *
43 * @param key the link key
44 * @param link the initial link
45 * @return a new instance
46 */
Simon Huntd6685d02015-08-21 09:56:06 -070047 protected abstract B create(LinkKey key, Link link);
Simon Hunt4fc86852015-08-20 17:57:52 -070048
49 /**
50 * Adds the given link to our collection, returning the corresponding
51 * bi-link (creating one if needed necessary).
52 *
53 * @param link the link to add to the collection
54 * @return the corresponding bi-link wrapper
55 */
56 public B add(Link link) {
57 LinkKey key = TopoUtils.canonicalLinkKey(checkNotNull(link));
58 B blink = map.get(key);
59 if (blink == null) {
60 // no bi-link yet exists for this link
61 blink = create(key, link);
62 map.put(key, blink);
63 } else {
64 // we have a bi-link for this link.
65 if (!blink.one().equals(link)) {
66 blink.setOther(link);
67 }
68 }
69 return blink;
70 }
71
72 /**
73 * Returns the bi-link instances in the collection.
74 *
75 * @return the bi-links in this map
76 */
77 public Collection<B> biLinks() {
78 return map.values();
79 }
80
81 /**
82 * Returns the number of bi-links in the collection.
83 *
84 * @return number of bi-links
85 */
86 public int size() {
87 return map.size();
88 }
89}