ONOS-6950 Annotate device through network configuration

Change-Id: I39d5ca39667bb1478a090408ff3c1af33220a0b2
diff --git a/cli/src/main/java/org/onosproject/cli/net/AnnotateDeviceCommand.java b/cli/src/main/java/org/onosproject/cli/net/AnnotateDeviceCommand.java
index 76252b8..0680d59 100644
--- a/cli/src/main/java/org/onosproject/cli/net/AnnotateDeviceCommand.java
+++ b/cli/src/main/java/org/onosproject/cli/net/AnnotateDeviceCommand.java
@@ -17,19 +17,11 @@
 
 import org.apache.karaf.shell.commands.Argument;
 import org.apache.karaf.shell.commands.Command;
+import org.apache.karaf.shell.commands.Option;
 import org.onosproject.cli.AbstractShellCommand;
-import org.onosproject.net.DefaultAnnotations;
-import org.onosproject.net.Device;
 import org.onosproject.net.DeviceId;
-import org.onosproject.net.MastershipRole;
-import org.onosproject.net.PortNumber;
-import org.onosproject.net.device.DefaultDeviceDescription;
-import org.onosproject.net.device.DeviceDescription;
-import org.onosproject.net.device.DeviceProvider;
-import org.onosproject.net.device.DeviceProviderRegistry;
-import org.onosproject.net.device.DeviceProviderService;
-import org.onosproject.net.device.DeviceService;
-import org.onosproject.net.provider.AbstractProvider;
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.config.basics.DeviceAnnotationConfig;
 import org.onosproject.net.provider.ProviderId;
 
 /**
@@ -54,57 +46,30 @@
             required = false, multiValued = false)
     String value = null;
 
+    @Option(name = "--remove-config",
+            description = "Remove annotation config")
+    private boolean removeCfg = false;
+
     @Override
     protected void execute() {
-        DeviceService service = get(DeviceService.class);
-        Device device = service.getDevice(DeviceId.deviceId(uri));
+        NetworkConfigService netcfgService = get(NetworkConfigService.class);
+        DeviceId deviceId = DeviceId.deviceId(uri);
 
-        DeviceProviderRegistry registry = get(DeviceProviderRegistry.class);
-        DeviceProvider provider = new AnnotationProvider();
-        try {
-            DeviceProviderService providerService = registry.register(provider);
-            providerService.deviceConnected(device.id(), description(device, key, value));
-        } finally {
-            registry.unregister(provider);
+        if (key == null) {
+            print("[ERROR] Annotation key not specified.");
+            return;
         }
-    }
-
-    private DeviceDescription description(Device device, String key, String value) {
-        DefaultAnnotations.Builder builder = DefaultAnnotations.builder();
-        if (value != null) {
-            builder.set(key, value);
+        DeviceAnnotationConfig cfg = netcfgService.getConfig(deviceId, DeviceAnnotationConfig.class);
+        if (cfg == null) {
+            cfg = new DeviceAnnotationConfig(deviceId);
+        }
+        if (removeCfg) {
+            // remove config about entry
+            cfg.annotation(key);
         } else {
-            builder.remove(key);
+            // add remove request config
+            cfg.annotation(key, value);
         }
-        return new DefaultDeviceDescription(device.id().uri(), device.type(),
-                                            device.manufacturer(), device.hwVersion(),
-                                            device.swVersion(), device.serialNumber(),
-                                            device.chassisId(), false, builder.build());
-    }
-
-    // Token provider entity
-    private static final class AnnotationProvider
-            extends AbstractProvider implements DeviceProvider {
-        private AnnotationProvider() {
-            super(PID);
-        }
-
-        @Override
-        public void triggerProbe(DeviceId deviceId) {
-        }
-
-        @Override
-        public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
-        }
-
-        @Override
-        public boolean isReachable(DeviceId deviceId) {
-            return false;
-        }
-
-        @Override
-        public void changePortState(DeviceId deviceId, PortNumber portNumber,
-                                    boolean enable) {
-        }
+        netcfgService.applyConfig(deviceId, DeviceAnnotationConfig.class, cfg.node());
     }
 }
diff --git a/core/api/src/main/java/org/onosproject/net/config/DeviceConfigOperator.java b/core/api/src/main/java/org/onosproject/net/config/DeviceConfigOperator.java
new file mode 100644
index 0000000..f01abf4
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/config/DeviceConfigOperator.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2016-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.net.config;
+
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceDescription;
+
+import com.google.common.annotations.Beta;
+
+import java.util.Optional;
+
+
+/**
+ * {@link ConfigOperator} for Device.
+ * <p>
+ * Note: We currently assume {@link DeviceConfigOperator}s are commutative.
+ */
+@Beta
+public interface DeviceConfigOperator extends ConfigOperator {
+
+    /**
+     * Binds {@link NetworkConfigService} to use for retrieving configuration.
+     *
+     * @param networkConfigService the service to use
+     */
+    void bindService(NetworkConfigService networkConfigService);
+
+
+    /**
+     * Generates a DeviceDescription containing fields from a DeviceDescription and
+     * configuration.
+     *
+     * @param deviceId {@link DeviceId} representing the port.
+     * @param descr input {@link DeviceDescription}
+     * @param prevConfig previous config {@link Config}
+     * @return Combined {@link DeviceDescription}
+     */
+    DeviceDescription combine(DeviceId deviceId, DeviceDescription descr,
+                              Optional<Config> prevConfig);
+}
diff --git a/core/api/src/main/java/org/onosproject/net/config/basics/DeviceAnnotationConfig.java b/core/api/src/main/java/org/onosproject/net/config/basics/DeviceAnnotationConfig.java
new file mode 100644
index 0000000..14e6712
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/config/basics/DeviceAnnotationConfig.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.net.config.basics;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.util.HashMap;
+import java.util.Map;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.BaseConfig;
+import org.onosproject.net.config.InvalidFieldException;
+import org.slf4j.Logger;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Configuration to add extra annotations to a device via netcfg subsystem.
+ */
+public class DeviceAnnotationConfig
+        extends BaseConfig<DeviceId> {
+
+    /**
+     * {@value #CONFIG_KEY} : a netcfg ConfigKey for {@link DeviceAnnotationConfig}.
+     */
+    public static final String CONFIG_KEY = "annotations";
+
+    /**
+     * JSON key for annotation entries.
+     * Value is a String.
+     */
+    private static final String ENTRIES = "entries";
+
+    private final Logger log = getLogger(getClass());
+
+    private static final int KEY_MAX_LENGTH = 1024;
+    private static final int VALUE_MAX_LENGTH = 1024;
+
+    @Override
+    public boolean isValid() {
+        JsonNode jsonNode = object.path(ENTRIES);
+        if (jsonNode.isObject()) {
+            jsonNode.fields().forEachRemaining(entry -> {
+                if (entry.getKey().length() > KEY_MAX_LENGTH) {
+                    throw new InvalidFieldException(entry.getKey(),
+                                                    entry.getKey() + " exceeds maximum length " + KEY_MAX_LENGTH);
+                }
+                if (entry.getValue().asText("").length() > VALUE_MAX_LENGTH) {
+                    throw new InvalidFieldException(entry.getKey(),
+                                                    entry.getKey() + " exceeds maximum length " + VALUE_MAX_LENGTH);
+                }
+            });
+        }
+        return hasField(ENTRIES) && object.get(ENTRIES).isObject();
+    }
+
+    /**
+     * Returns annotations to add to a Device.
+     *
+     * @return annotations as a map. null value represent key removal request
+     */
+    public Map<String, String> annotations() {
+        Map<String, String> map = new HashMap<>();
+
+        JsonNode jsonNode = object.path(ENTRIES);
+        if (!jsonNode.isObject()) {
+            return map;
+        }
+
+        jsonNode.fields().forEachRemaining(entry -> {
+            String key = entry.getKey();
+            JsonNode value = entry.getValue();
+            if (value.isTextual()) {
+                map.put(key, value.asText());
+            } else if (value.isNull()) {
+                map.put(key, null);
+            } else {
+                try {
+                    map.put(key, mapper().writeValueAsString(value));
+                } catch (JsonProcessingException e) {
+                    log.warn("Error processing JSON value for {}.", key, e);
+                }
+            }
+        });
+        return map;
+    }
+
+    /**
+     * Sets annotations to add to a Device.
+     *
+     * @param replace annotations to be added by this configuration.
+     *                null value represent key removal request
+     * @return self
+     */
+    public DeviceAnnotationConfig annotations(Map<String, String> replace) {
+        ObjectNode anns = object.objectNode();
+        if (replace != null) {
+            replace.forEach((k, v) -> {
+                anns.put(k, v);
+            });
+        }
+        object.set(ENTRIES, anns);
+        return this;
+    }
+
+    /**
+     * Add configuration to set or remove annotation entry.
+     *
+     * @param key annotations key
+     * @param value annotations value. specifying null removes the entry.
+     * @return self
+     */
+    public DeviceAnnotationConfig annotation(String key, String value) {
+        JsonNode ent = object.path(ENTRIES);
+        ObjectNode obj = (ent.isObject()) ? (ObjectNode) ent : object.objectNode();
+
+        obj.put(key, value);
+
+        object.set(ENTRIES, obj);
+        return this;
+    }
+
+    /**
+     * Remove configuration about specified key.
+     *
+     * @param key annotations key
+     * @return self
+     */
+    public DeviceAnnotationConfig annotation(String key) {
+        JsonNode ent = object.path(ENTRIES);
+        ObjectNode obj = (ent.isObject()) ? (ObjectNode) ent : object.objectNode();
+
+        obj.remove(key);
+
+        object.set(ENTRIES, obj);
+        return this;
+    }
+
+    /**
+     * Create a detached {@link DeviceAnnotationConfig}.
+     * <p>
+     * Note: created instance needs to be initialized by #init(..) before using.
+     */
+    public DeviceAnnotationConfig() {
+        super();
+    }
+
+    /**
+     * Create a detached {@link DeviceAnnotationConfig} for specified device.
+     * <p>
+     * Note: created instance is not bound to NetworkConfigService,
+     * thus cannot use {@link #apply()}. Must be passed to the service
+     * using NetworkConfigService#applyConfig
+     *
+     * @param deviceId Device id
+     */
+    public DeviceAnnotationConfig(DeviceId deviceId) {
+        ObjectMapper mapper = new ObjectMapper();
+        init(deviceId, CONFIG_KEY, mapper.createObjectNode(), mapper, null);
+    }
+}
diff --git a/core/api/src/main/java/org/onosproject/net/device/DefaultDeviceDescription.java b/core/api/src/main/java/org/onosproject/net/device/DefaultDeviceDescription.java
index 577a2ec..a331f69 100644
--- a/core/api/src/main/java/org/onosproject/net/device/DefaultDeviceDescription.java
+++ b/core/api/src/main/java/org/onosproject/net/device/DefaultDeviceDescription.java
@@ -154,6 +154,18 @@
              base.chassisId(), defaultAvailable, annotations);
     }
 
+    /**
+     * Creates a device description using the supplied information.
+     *
+     * @param base base
+     * @param annotations annotations
+     * @return device description
+     */
+    public static DefaultDeviceDescription copyReplacingAnnotation(DeviceDescription base,
+                                                                   SparseAnnotations annotations) {
+        return new DefaultDeviceDescription(base, annotations);
+    }
+
     @Override
     public URI deviceUri() {
         return uri;
diff --git a/core/net/src/main/java/org/onosproject/net/config/impl/BasicNetworkConfigs.java b/core/net/src/main/java/org/onosproject/net/config/impl/BasicNetworkConfigs.java
index ff4c5de..0e2ad0d 100644
--- a/core/net/src/main/java/org/onosproject/net/config/impl/BasicNetworkConfigs.java
+++ b/core/net/src/main/java/org/onosproject/net/config/impl/BasicNetworkConfigs.java
@@ -23,6 +23,7 @@
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.Service;
 import org.onosproject.core.CoreService;
+import org.onosproject.net.config.basics.DeviceAnnotationConfig;
 import org.onosproject.net.config.basics.InterfaceConfig;
 import org.onosproject.incubator.net.config.basics.PortDescriptionsConfig;
 import org.onosproject.net.ConnectPoint;
@@ -68,69 +69,77 @@
 
     private final Set<ConfigFactory> factories = ImmutableSet.of(
             new ConfigFactory<DeviceId, BasicDeviceConfig>(DEVICE_SUBJECT_FACTORY,
-                    BasicDeviceConfig.class,
-                    BASIC) {
+                                                           BasicDeviceConfig.class,
+                                                           BASIC) {
                 @Override
                 public BasicDeviceConfig createConfig() {
                     return new BasicDeviceConfig();
                 }
             },
             new ConfigFactory<ConnectPoint, InterfaceConfig>(CONNECT_POINT_SUBJECT_FACTORY,
-                    InterfaceConfig.class,
-                    INTERFACES,
-                    true) {
+                                                             InterfaceConfig.class,
+                                                             INTERFACES,
+                                                             true) {
                 @Override
                 public InterfaceConfig createConfig() {
                     return new InterfaceConfig();
                 }
             },
             new ConfigFactory<HostId, BasicHostConfig>(HOST_SUBJECT_FACTORY,
-                    BasicHostConfig.class,
-                    BASIC) {
+                                                       BasicHostConfig.class,
+                                                       BASIC) {
                 @Override
                 public BasicHostConfig createConfig() {
                     return new BasicHostConfig();
                 }
             },
             new ConfigFactory<LinkKey, BasicLinkConfig>(LINK_SUBJECT_FACTORY,
-                    BasicLinkConfig.class,
-                    BasicLinkConfig.CONFIG_KEY) {
+                                                        BasicLinkConfig.class,
+                                                        BasicLinkConfig.CONFIG_KEY) {
                 @Override
                 public BasicLinkConfig createConfig() {
                     return new BasicLinkConfig();
                 }
             },
             new ConfigFactory<RegionId, BasicRegionConfig>(REGION_SUBJECT_FACTORY,
-                    BasicRegionConfig.class,
-                    BASIC) {
+                                                           BasicRegionConfig.class,
+                                                           BASIC) {
                 @Override
                 public BasicRegionConfig createConfig() {
                     return new BasicRegionConfig();
                 }
             },
             new ConfigFactory<UiTopoLayoutId, BasicUiTopoLayoutConfig>(LAYOUT_SUBJECT_FACTORY,
-                    BasicUiTopoLayoutConfig.class,
-                    BASIC) {
+                                                                       BasicUiTopoLayoutConfig.class,
+                                                                       BASIC) {
                 @Override
                 public BasicUiTopoLayoutConfig createConfig() {
                     return new BasicUiTopoLayoutConfig();
                 }
             },
             new ConfigFactory<ConnectPoint, PortAnnotationConfig>(CONNECT_POINT_SUBJECT_FACTORY,
-                    PortAnnotationConfig.class,
-                    PortAnnotationConfig.CONFIG_KEY) {
+                                                                  PortAnnotationConfig.class,
+                                                                  PortAnnotationConfig.CONFIG_KEY) {
                 @Override
                 public PortAnnotationConfig createConfig() {
                     return new PortAnnotationConfig();
                 }
             },
             new ConfigFactory<DeviceId, PortDescriptionsConfig>(DEVICE_SUBJECT_FACTORY,
-                    PortDescriptionsConfig.class,
-                    PORTS) {
+                                                                PortDescriptionsConfig.class,
+                                                                PORTS) {
                 @Override
                 public PortDescriptionsConfig createConfig() {
                     return new PortDescriptionsConfig();
                 }
+            },
+            new ConfigFactory<DeviceId, DeviceAnnotationConfig>(DEVICE_SUBJECT_FACTORY,
+                                                                DeviceAnnotationConfig.class,
+                                                                DeviceAnnotationConfig.CONFIG_KEY) {
+                @Override
+                public DeviceAnnotationConfig createConfig() {
+                    return new DeviceAnnotationConfig();
+                }
             }
 
     );
diff --git a/core/net/src/main/java/org/onosproject/net/device/impl/DeviceAnnotationOperator.java b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceAnnotationOperator.java
new file mode 100644
index 0000000..c5d10ce
--- /dev/null
+++ b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceAnnotationOperator.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.net.device.impl;
+
+import java.util.Map;
+import java.util.Optional;
+
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DefaultAnnotations.Builder;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.Config;
+import org.onosproject.net.config.DeviceConfigOperator;
+import org.onosproject.net.config.NetworkConfigService;
+import org.onosproject.net.config.basics.DeviceAnnotationConfig;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.DeviceDescription;
+
+/**
+ * Implementations of {@link DeviceConfigOperator} to weave
+ * annotations added via {@link DeviceAnnotationConfig}.
+ */
+public class DeviceAnnotationOperator implements DeviceConfigOperator {
+
+    private NetworkConfigService networkConfigService;
+
+    /**
+     * Creates {@link DeviceAnnotationOperator} instance.
+     */
+    public DeviceAnnotationOperator() {
+    }
+
+    DeviceAnnotationOperator(NetworkConfigService networkConfigService) {
+        bindService(networkConfigService);
+    }
+
+    @Override
+    public void bindService(NetworkConfigService networkConfigService) {
+        this.networkConfigService = networkConfigService;
+    }
+
+    private DeviceAnnotationConfig lookupConfig(DeviceId deviceId) {
+        if (networkConfigService == null) {
+            return null;
+        }
+        return networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
+    }
+
+    @Override
+    public DeviceDescription combine(DeviceId deviceId, DeviceDescription descr,
+                                     Optional<Config> prevConfig) {
+        DeviceAnnotationConfig cfg = lookupConfig(deviceId);
+        if (cfg == null) {
+            return descr;
+        }
+        Map<String, String> annotations = cfg.annotations();
+
+        Builder builder = DefaultAnnotations.builder();
+        builder.putAll(descr.annotations());
+        if (prevConfig.isPresent()) {
+            DeviceAnnotationConfig prevDeviceAnnotationConfig = (DeviceAnnotationConfig) prevConfig.get();
+            for (String key : prevDeviceAnnotationConfig.annotations().keySet()) {
+                if (!annotations.containsKey(key)) {
+                    builder.remove(key);
+                }
+            }
+        }
+        builder.putAll(annotations);
+
+        return DefaultDeviceDescription.copyReplacingAnnotation(descr, builder.build());
+    }
+
+}
\ No newline at end of file
diff --git a/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
index 59129c7..c9b4154 100644
--- a/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
+++ b/core/net/src/main/java/org/onosproject/net/device/impl/DeviceManager.java
@@ -49,6 +49,7 @@
 import org.onosproject.net.config.PortConfigOperator;
 import org.onosproject.net.config.PortConfigOperatorRegistry;
 import org.onosproject.net.config.basics.BasicDeviceConfig;
+import org.onosproject.net.config.basics.DeviceAnnotationConfig;
 import org.onosproject.net.config.basics.PortAnnotationConfig;
 import org.onosproject.net.device.DefaultPortDescription;
 import org.onosproject.net.device.DeviceAdminService;
@@ -168,6 +169,7 @@
 
     // not part of portOps. must be executed at the end
     private PortAnnotationOperator portAnnotationOp;
+    private DeviceAnnotationOperator deviceAnnotationOp;
 
     private static final MessageSubject PORT_UPDOWN_SUBJECT =
             new MessageSubject("port-updown-req");
@@ -198,6 +200,7 @@
     @Activate
     public void activate() {
         portAnnotationOp = new PortAnnotationOperator(networkConfigService);
+        deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
         portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
 
         backgroundService = newSingleThreadScheduledExecutor(
@@ -986,7 +989,8 @@
                     || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
                     && (event.configClass().equals(BasicDeviceConfig.class)
                     || portOpsIndex.containsKey(event.configClass())
-                    || event.configClass().equals(PortDescriptionsConfig.class));
+                    || event.configClass().equals(PortDescriptionsConfig.class)
+                    || event.configClass().equals(DeviceAnnotationConfig.class));
         }
 
         @Override
@@ -1024,6 +1028,17 @@
                             .collect(Collectors.toList());
                     complete.addAll(portConfig.portDescriptions());
                     store.updatePorts(dp.id(), did, complete);
+            } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
+                DeviceId did = (DeviceId) event.subject();
+                DeviceProvider dp = getProvider(did);
+                Device dev = getDevice(did);
+                DeviceDescription desc =
+                        (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
+                Optional<Config> prevConfig = event.prevConfig();
+                desc = deviceAnnotationOp.combine(did, desc, prevConfig);
+                if (desc != null && dp != null) {
+                    de = store.createOrUpdateDevice(dp.id(), did, desc);
+                }
             } else if (portOpsIndex.containsKey(event.configClass())) {
                 ConnectPoint cpt = (ConnectPoint) event.subject();
                 DeviceId did = cpt.deviceId();
diff --git a/core/net/src/test/java/org/onosproject/net/config/basics/DeviceAnnotationConfigTest.java b/core/net/src/test/java/org/onosproject/net/config/basics/DeviceAnnotationConfigTest.java
new file mode 100644
index 0000000..b95f26d
--- /dev/null
+++ b/core/net/src/test/java/org/onosproject/net/config/basics/DeviceAnnotationConfigTest.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.net.config.basics;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.*;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onlab.junit.TestUtils.TestUtilsException;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.config.BaseConfig;
+import org.onosproject.net.config.ConfigApplyDelegate;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.NumericNode;
+import com.google.common.collect.ImmutableMap;
+
+public class DeviceAnnotationConfigTest {
+
+    private static final String SAMPLE_JSONFILE = "device_annotation_config.json";
+
+    private static TestServiceDirectory directory;
+    private static ServiceDirectory original;
+
+    private ObjectMapper mapper;
+
+    private final ConfigApplyDelegate noopDelegate = cfg -> { };
+
+    /**
+     * {@value #SAMPLE_JSONFILE} after parsing.
+     */
+    private JsonNode node;
+
+    // sample data
+    private final DeviceId deviceId = DeviceId.deviceId("of:0000000000000001");
+
+    private final String key = "foo";
+    private final String value = "bar";
+    private final String key1 = "foo1";
+    private final String value1 = "bar1";
+
+
+    // TODO consolidate code-clone in ProtectionConfigTest, and define constants for field name
+    @BeforeClass
+    public static void setUpClass() throws TestUtilsException {
+        directory = new TestServiceDirectory();
+
+        CodecManager codecService = new CodecManager();
+        codecService.activate();
+        directory.add(CodecService.class, codecService);
+
+        // replace service directory used by BaseConfig
+        original = TestUtils.getField(BaseConfig.class, "services");
+        TestUtils.setField(BaseConfig.class, "services", directory);
+    }
+
+    @AfterClass
+    public static void tearDownClass() throws TestUtilsException {
+        TestUtils.setField(BaseConfig.class, "services", original);
+    }
+
+    @Before
+    public void setUp() throws JsonProcessingException, IOException, TestUtilsException {
+
+        mapper = new ObjectMapper();
+        // Jackson configuration for ease of Numeric node comparison
+        // - treat integral number node as long node
+        mapper.enable(DeserializationFeature.USE_LONG_FOR_INTS);
+        mapper.setNodeFactory(new JsonNodeFactory(false) {
+            @Override
+            public NumericNode numberNode(int v) {
+                return super.numberNode((long) v);
+            }
+            @Override
+            public NumericNode numberNode(short v) {
+                return super.numberNode((long) v);
+            }
+        });
+
+        InputStream stream = DeviceAnnotationConfig.class
+                .getResourceAsStream(SAMPLE_JSONFILE);
+        JsonNode tree = mapper.readTree(stream);
+
+        node = tree.path("devices")
+                .path(deviceId.toString())
+                .path(DeviceAnnotationConfig.CONFIG_KEY);
+        assertTrue(node.isObject());
+    }
+
+    @Test
+    public void readTest() {
+        DeviceAnnotationConfig sut = new DeviceAnnotationConfig();
+        sut.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, node, mapper, noopDelegate);
+
+        assertThat(sut.subject(), is(deviceId));
+        Map<String, String> annotations = sut.annotations();
+        assertThat(annotations.size(), is(1));
+        assertThat(annotations.get(key), is(value));
+    }
+
+    @Test
+    public void writeEntryTest() throws JsonProcessingException, IOException {
+
+        DeviceAnnotationConfig w = new DeviceAnnotationConfig();
+        w.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
+
+        // write equivalent to sample
+        w.annotation(key, value);
+
+        // reparse JSON
+        JsonNode r = mapper.readTree(mapper.writeValueAsString(w.node()));
+
+        DeviceAnnotationConfig sut = new DeviceAnnotationConfig();
+        sut.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, r, mapper, noopDelegate);
+
+        assertThat(sut.subject(), is(deviceId));
+        Map<String, String> annotations = sut.annotations();
+        assertThat(annotations.size(), is(1));
+        assertThat(annotations.get(key), is(value));
+    }
+
+    @Test
+    public void writeMapTest() throws JsonProcessingException, IOException {
+
+        DeviceAnnotationConfig w = new DeviceAnnotationConfig();
+        w.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
+
+        // write equivalent to sample
+        w.annotations(ImmutableMap.of(key, value));
+
+        // reparse JSON
+        JsonNode r = mapper.readTree(mapper.writeValueAsString(w.node()));
+
+        DeviceAnnotationConfig sut = new DeviceAnnotationConfig();
+        sut.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, r, mapper, noopDelegate);
+
+        assertThat(sut.subject(), is(deviceId));
+        Map<String, String> annotations = sut.annotations();
+        assertThat(annotations.size(), is(1));
+        assertThat(annotations.get(key), is(value));
+    }
+
+    @Test
+    public void removeEntryTest() throws  JsonProcessingException, IOException {
+        DeviceAnnotationConfig w = new DeviceAnnotationConfig();
+        w.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
+
+        //write equivalent to sample
+        w.annotation(key, value);
+        w.annotation(key1, value1);
+
+        //reparse JSON
+        JsonNode r = mapper.readTree(mapper.writeValueAsString(w.node()));
+
+        DeviceAnnotationConfig sut = new DeviceAnnotationConfig();
+        sut.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, r, mapper, noopDelegate);
+
+        Map<String, String> annotations = sut.annotations();
+        assertThat(annotations.size(), is(2));
+
+
+        //remove entry
+        w.annotation(key);
+        r = mapper.readTree(mapper.writeValueAsString(w.node()));
+
+        sut = new DeviceAnnotationConfig();
+        sut.init(deviceId, DeviceAnnotationConfig.CONFIG_KEY, r, mapper, noopDelegate);
+        annotations = sut.annotations();
+        assertThat(annotations.size(), is(1));
+        assertThat(annotations.get(key1), is(value1));
+    }
+
+}
diff --git a/core/net/src/test/resources/org/onosproject/net/config/basics/device_annotation_config.json b/core/net/src/test/resources/org/onosproject/net/config/basics/device_annotation_config.json
new file mode 100644
index 0000000..b37e19b
--- /dev/null
+++ b/core/net/src/test/resources/org/onosproject/net/config/basics/device_annotation_config.json
@@ -0,0 +1,11 @@
+{
+  "devices" : {
+    "of:0000000000000001" : {
+      "annotations" : {
+        "entries" : {
+          "foo" : "bar"
+        }
+      }
+    }
+  }
+}
\ No newline at end of file