blob: 88eafb24b49aab0b6be301a6348c420058eba1ef [file] [log] [blame]
tomf5d85d42014-10-02 05:27:56 -07001package org.onlab.onos.net;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.Objects;
6import java.util.Set;
7
8/**
9 * Represents a set of simple annotations that can be used to add arbitrary
10 * attributes to various parts of the data model.
11 */
12public final class DefaultAnnotations implements SparseAnnotations {
13
14 private final Map<String, String> map;
15
16 // For serialization
17 private DefaultAnnotations() {
18 this.map = null;
19 }
20
21 /**
22 * Creates a new set of annotations using the specified immutable map.
23 *
24 * @param map immutable map of key/value pairs
25 */
26 private DefaultAnnotations(Map<String, String> map) {
27 this.map = map;
28 }
29
30 /**
31 * Creates a new annotations builder.
32 *
33 * @return new annotations builder
34 */
35 public static Builder builder() {
36 return new Builder();
37 }
38
39
40 @Override
41 public Set<String> keys() {
42 return map.keySet();
43 }
44
45 @Override
46 public String value(String key) {
47 String value = map.get(key);
48 return Objects.equals(Builder.REMOVED, value) ? null : value;
49 }
50
51 @Override
52 public boolean isRemoved(String key) {
53 return Objects.equals(Builder.REMOVED, map.get(key));
54 }
55
56 /**
57 * Facility for gradually building model annotations.
58 */
59 public static final class Builder {
60
61 private static final String REMOVED = "~rEmOvEd~";
62
63 // FIXME: Figure out whether and how to make this immutable and serializable
64// private final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
65 private final Map<String, String> builder = new HashMap<>();
66
67 // Private construction is forbidden.
68 private Builder() {
69 }
70
71 /**
72 * Adds the specified annotation. Any previous value associated with
73 * the given annotation key will be overwritten.
74 *
75 * @param key annotation key
76 * @param value annotation value
77 * @return self
78 */
79 public Builder set(String key, String value) {
80 builder.put(key, value);
81 return this;
82 }
83
84 /**
85 * Adds the specified annotation. Any previous value associated with
86 * the given annotation key will be tagged for removal.
87 *
88 * @param key annotation key
89 * @return self
90 */
91 public Builder remove(String key) {
92 builder.put(key, REMOVED);
93 return this;
94 }
95
96 /**
97 * Returns immutable annotations built from the accrued key/values pairs.
98 *
99 * @return annotations
100 */
101 public DefaultAnnotations build() {
102// return new DefaultAnnotations(builder.build());
103 return new DefaultAnnotations(builder);
104 }
105 }
106}