[ONOS-6170] Implement codec for MappingTreatment with unit test

Change-Id: Icd0e17863dac54f677f8e72d1007ea0d4dfbccaf
diff --git a/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/MappingCodecRegistrator.java b/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/MappingCodecRegistrator.java
index 9354cd8..7bebe43 100644
--- a/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/MappingCodecRegistrator.java
+++ b/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/MappingCodecRegistrator.java
@@ -21,12 +21,14 @@
 import org.apache.felix.scr.annotations.Reference;
 import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.onosproject.codec.CodecService;
+import org.onosproject.mapping.MappingTreatment;
 import org.onosproject.mapping.actions.MappingAction;
 import org.onosproject.mapping.addresses.MappingAddress;
 import org.onosproject.mapping.instructions.MappingInstruction;
 import org.onosproject.mapping.web.codec.MappingActionCodec;
 import org.onosproject.mapping.web.codec.MappingAddressCodec;
 import org.onosproject.mapping.web.codec.MappingInstructionCodec;
+import org.onosproject.mapping.web.codec.MappingTreatmentCodec;
 import org.slf4j.Logger;
 
 import static org.slf4j.LoggerFactory.getLogger;
@@ -47,6 +49,7 @@
         codecService.registerCodec(MappingAddress.class, new MappingAddressCodec());
         codecService.registerCodec(MappingInstruction.class, new MappingInstructionCodec());
         codecService.registerCodec(MappingAction.class, new MappingActionCodec());
+        codecService.registerCodec(MappingTreatment.class, new MappingTreatmentCodec());
 
         log.info("Started");
     }
@@ -56,6 +59,7 @@
         codecService.unregisterCodec(MappingAddress.class);
         codecService.unregisterCodec(MappingInstruction.class);
         codecService.unregisterCodec(MappingAction.class);
+        codecService.unregisterCodec(MappingTreatment.class);
 
         log.info("Stopped");
     }
diff --git a/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/codec/MappingTreatmentCodec.java b/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/codec/MappingTreatmentCodec.java
new file mode 100644
index 0000000..10ed6d7
--- /dev/null
+++ b/apps/mappingmanagement/web/src/main/java/org/onosproject/mapping/web/codec/MappingTreatmentCodec.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2017-present Open Networking Laboratory
+ *
+ * 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.mapping.web.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.mapping.DefaultMappingTreatment;
+import org.onosproject.mapping.MappingTreatment;
+import org.onosproject.mapping.addresses.MappingAddress;
+import org.onosproject.mapping.instructions.MappingInstruction;
+
+import java.util.stream.IntStream;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Mapping treatment codec.
+ */
+public final class MappingTreatmentCodec extends JsonCodec<MappingTreatment> {
+
+    private static final String INSTRUCTIONS = "instructions";
+    private static final String ADDRESS = "address";
+
+    @Override
+    public ObjectNode encode(MappingTreatment treatment, CodecContext context) {
+        checkNotNull(treatment, "Mapping treatment cannot be null");
+
+        final ObjectNode result = context.mapper().createObjectNode();
+        final ArrayNode jsonInstructions = result.putArray(INSTRUCTIONS);
+
+        final JsonCodec<MappingInstruction> instructionCodec =
+                context.codec(MappingInstruction.class);
+
+        final JsonCodec<MappingAddress> addressCodec =
+                context.codec(MappingAddress.class);
+
+        for (final MappingInstruction instruction : treatment.instructions()) {
+            jsonInstructions.add(instructionCodec.encode(instruction, context));
+        }
+
+        result.set(ADDRESS, addressCodec.encode(treatment.address(), context));
+
+        return result;
+    }
+
+    @Override
+    public MappingTreatment decode(ObjectNode json, CodecContext context) {
+        if (json == null || !json.isObject()) {
+            return null;
+        }
+
+        final JsonCodec<MappingInstruction> instructionCodec =
+                context.codec(MappingInstruction.class);
+
+        JsonNode instructionJson = json.get(INSTRUCTIONS);
+        MappingTreatment.Builder builder = DefaultMappingTreatment.builder();
+
+        if (instructionJson != null) {
+            IntStream.range(0, instructionJson.size())
+                    .forEach(i -> builder.add(
+                            instructionCodec.decode(get(instructionJson, i),
+                                    context)));
+        }
+
+        ObjectNode addressJson = get(json, ADDRESS);
+        if (addressJson != null) {
+            final JsonCodec<MappingAddress> addressCodec =
+                    context.codec(MappingAddress.class);
+            builder.withAddress(addressCodec.decode(addressJson, context));
+        }
+
+        return builder.build();
+    }
+}
diff --git a/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingAddressJsonMatcher.java b/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingAddressJsonMatcher.java
index ba496e9..b24d2d7 100644
--- a/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingAddressJsonMatcher.java
+++ b/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingAddressJsonMatcher.java
@@ -152,7 +152,7 @@
 
             default:
                 // Don't know how to format this type
-                description.appendText("unknown criterion type " + address.type());
+                description.appendText("unknown mapping address type " + address.type());
                 return false;
         }
     }
diff --git a/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingTreatmentCodecTest.java b/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingTreatmentCodecTest.java
new file mode 100644
index 0000000..ca8b2df
--- /dev/null
+++ b/apps/mappingmanagement/web/src/test/java/org/onosproject/mapping/web/codec/MappingTreatmentCodecTest.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2017-present Open Networking Laboratory
+ *
+ * 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.mapping.web.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.ImmutableSet;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.mapping.DefaultMappingTreatment;
+import org.onosproject.mapping.MappingTreatment;
+import org.onosproject.mapping.addresses.MappingAddress;
+import org.onosproject.mapping.addresses.MappingAddresses;
+import org.onosproject.mapping.instructions.MappingInstruction;
+import org.onosproject.mapping.instructions.MappingInstructions;
+import org.onosproject.mapping.web.MappingCodecRegistrator;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+
+/**
+ * Unit tests for MappingTreatmentCodec.
+ */
+public class MappingTreatmentCodecTest {
+
+    private static final String INSTRUCTIONS = "instructions";
+    private static final String TYPE = "type";
+
+    private static final int UNICAST_WEIGHT = 1;
+    private static final int UNICAST_PRIORITY = 1;
+    private static final int MULTICAST_WEIGHT = 2;
+    private static final int MULTICAST_PRIORITY = 2;
+    private static final String ASN_NUMBER = "ASN2000";
+
+    private CodecContext context;
+    private JsonCodec<MappingTreatment> treatmentCodec;
+    private MappingCodecRegistrator registrator;
+
+    /**
+     * Sets up for each test.
+     * Creates a context and fetches the mapping action codec.
+     */
+    @Before
+    public void setUp() {
+        CodecManager manager = new CodecManager();
+        registrator = new MappingCodecRegistrator();
+        registrator.codecService = manager;
+        registrator.activate();
+
+        context = new MappingTreatmentCodecTest.MappingTestContext(registrator.codecService);
+        treatmentCodec = context.codec(MappingTreatment.class);
+        assertThat(treatmentCodec, notNullValue());
+    }
+
+    /**
+     * Deactivates the codec registrator.
+     */
+    @After
+    public void tearDown() {
+        registrator.deactivate();
+    }
+
+    /**
+     * Tests encoding of a mapping treatment object.
+     */
+    @Test
+    public void testMappingTreatmentEncode() {
+        MappingInstruction unicastWeight = MappingInstructions.unicastWeight(UNICAST_WEIGHT);
+        MappingInstruction unicastPriority = MappingInstructions.unicastPriority(UNICAST_PRIORITY);
+        MappingInstruction multicastWeight = MappingInstructions.multicastWeight(MULTICAST_WEIGHT);
+        MappingInstruction multicastPriority = MappingInstructions.multicastPriority(MULTICAST_PRIORITY);
+
+        MappingAddress address = MappingAddresses.asMappingAddress(ASN_NUMBER);
+
+        MappingTreatment treatment = DefaultMappingTreatment.builder()
+                                                .add(unicastWeight)
+                                                .add(unicastPriority)
+                                                .add(multicastWeight)
+                                                .add(multicastPriority)
+                                                .withAddress(address)
+                                                .build();
+
+        ObjectNode treatmentJson = treatmentCodec.encode(treatment, context);
+        assertThat(treatmentJson, MappingTreatmentJsonMatcher.matchesMappingTreatment(treatment));
+    }
+
+    /**
+     * Tests decoding of a mapping treatment JSON object.
+     */
+    @Test
+    public void testMappingTreatmentDecode() throws IOException {
+        MappingTreatment treatment = getTreatment("MappingTreatment.json");
+
+        List<MappingInstruction> insts = treatment.instructions();
+        assertThat(insts.size(), is(2));
+
+        ImmutableSet<String> types = ImmutableSet.of("UNICAST", "MULTICAST");
+        assertThat(types.contains(insts.get(0).type().name()), is(true));
+        assertThat(types.contains(insts.get(1).type().name()), is(true));
+    }
+
+    /**
+     * Hamcrest matcher for mapping treatment.
+     */
+    public static final class MappingTreatmentJsonMatcher
+            extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+        private final MappingTreatment mappingTreatment;
+
+        /**
+         * A default constructor.
+         *
+         * @param mappingTreatment mapping treatment
+         */
+        private MappingTreatmentJsonMatcher(MappingTreatment mappingTreatment) {
+            this.mappingTreatment = mappingTreatment;
+        }
+
+        @Override
+        protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+
+            // check mapping instruction
+            final JsonNode jsonInstructions = jsonNode.get(INSTRUCTIONS);
+            if (mappingTreatment.instructions().size() != jsonInstructions.size()) {
+                description.appendText("mapping instructions array size of " +
+                        Integer.toString(mappingTreatment.instructions().size()));
+                return false;
+            }
+
+            for (final MappingInstruction instruction : mappingTreatment.instructions()) {
+                boolean instructionFound = false;
+                for (int instructionIdx = 0; instructionIdx < jsonInstructions.size();
+                        instructionIdx++) {
+                    final String jsonType =
+                            jsonInstructions.get(instructionIdx).get(TYPE).asText();
+                    final String instructionType = instruction.type().name();
+                    if (jsonType.equals(instructionType)) {
+                        instructionFound = true;
+                    }
+                }
+                if (!instructionFound) {
+                    description.appendText("mapping instruction " + instruction.toString());
+                    return false;
+                }
+            }
+
+            return true;
+        }
+
+        @Override
+        public void describeTo(Description description) {
+            description.appendText(mappingTreatment.toString());
+        }
+
+        /**
+         * Factory to allocate a mapping treatment.
+         *
+         * @param mappingTreatment mapping treatment object we are looking for
+         * @return matcher
+         */
+        static MappingTreatmentJsonMatcher matchesMappingTreatment(MappingTreatment mappingTreatment) {
+            return new MappingTreatmentJsonMatcher(mappingTreatment);
+        }
+    }
+
+    /**
+     * Test mapping codec context.
+     */
+    private class MappingTestContext implements CodecContext {
+        private final ObjectMapper mapper = new ObjectMapper();
+        private final CodecService manager;
+
+        /**
+         * Constructs a new mock codec context.
+         */
+        public MappingTestContext(CodecService manager) {
+            this.manager = manager;
+        }
+
+        @Override
+        public ObjectMapper mapper() {
+            return mapper;
+        }
+
+        @Override
+        public <T> JsonCodec<T> codec(Class<T> entityClass) {
+            return manager.getCodec(entityClass);
+        }
+
+        @Override
+        public <T> T getService(Class<T> serviceClass) {
+            return null;
+        }
+    }
+
+    /**
+     * Reads in a mapping treatment from the given resource and decodes it.
+     *
+     * @param resourceName resource to use to read the JSON for the rule
+     * @return decoded mappingTreatment
+     * @throws IOException if processing the resource fails
+     */
+    private MappingTreatment getTreatment(String resourceName) throws IOException {
+        InputStream jsonStream = MappingTreatmentCodecTest.class.getResourceAsStream(resourceName);
+        JsonNode json = context.mapper().readTree(jsonStream);
+        assertThat(json, notNullValue());
+        MappingTreatment treatment = treatmentCodec.decode((ObjectNode) json, context);
+        assertThat(treatment, notNullValue());
+        return treatment;
+    }
+}
diff --git a/apps/mappingmanagement/web/src/test/resources/org/onosproject/mapping/web/codec/MappingTreatment.json b/apps/mappingmanagement/web/src/test/resources/org/onosproject/mapping/web/codec/MappingTreatment.json
new file mode 100644
index 0000000..21e49a0
--- /dev/null
+++ b/apps/mappingmanagement/web/src/test/resources/org/onosproject/mapping/web/codec/MappingTreatment.json
@@ -0,0 +1,14 @@
+{
+  "instructions": [
+    {
+      "type": "UNICAST",
+      "subtype": "WEIGHT",
+      "unicastWeight": 1
+    },
+    {
+      "type": "MULTICAST",
+      "subtype": "WEIGHT",
+      "multicastWeight": 2
+    }
+  ]
+}