ONOS-741 - JSON codecs for constraints

Change-Id: I6eebc2ef5f6c28956f0944524aa90f44cebfcc60
diff --git a/web/api/src/main/java/org/onosproject/codec/impl/CodecManager.java b/web/api/src/main/java/org/onosproject/codec/impl/CodecManager.java
index 592f6a8..10f2b57 100644
--- a/web/api/src/main/java/org/onosproject/codec/impl/CodecManager.java
+++ b/web/api/src/main/java/org/onosproject/codec/impl/CodecManager.java
@@ -15,7 +15,10 @@
  */
 package org.onosproject.codec.impl;
 
-import com.google.common.collect.ImmutableSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
@@ -36,15 +39,14 @@
 import org.onosproject.net.flow.criteria.Criterion;
 import org.onosproject.net.flow.instructions.Instruction;
 import org.onosproject.net.intent.ConnectivityIntent;
+import org.onosproject.net.intent.Constraint;
 import org.onosproject.net.intent.HostToHostIntent;
 import org.onosproject.net.intent.Intent;
 import org.onosproject.net.intent.PointToPointIntent;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
+import com.google.common.collect.ImmutableSet;
 
 /**
  * Implementation of the JSON codec brokering service.
@@ -77,6 +79,7 @@
         registerCodec(Instruction.class, new InstructionCodec());
         registerCodec(Criterion.class, new CriterionCodec());
         registerCodec(Ethernet.class, new EthernetCodec());
+        registerCodec(Constraint.class, new ConstraintCodec());
         log.info("Started");
     }
 
diff --git a/web/api/src/main/java/org/onosproject/codec/impl/ConnectivityIntentCodec.java b/web/api/src/main/java/org/onosproject/codec/impl/ConnectivityIntentCodec.java
index 3a7aa15..0591562 100644
--- a/web/api/src/main/java/org/onosproject/codec/impl/ConnectivityIntentCodec.java
+++ b/web/api/src/main/java/org/onosproject/codec/impl/ConnectivityIntentCodec.java
@@ -56,9 +56,12 @@
             final ArrayNode jsonConstraints = result.putArray("constraints");
 
             if (intent.constraints() != null) {
+                final JsonCodec<Constraint> constraintCodec =
+                        context.codec(Constraint.class);
                 for (final Constraint constraint : intent.constraints()) {
-                    // TODO: constraint should have its own codec
-                    jsonConstraints.add(constraint.toString());
+                    final ObjectNode constraintNode =
+                            constraintCodec.encode(constraint, context);
+                    jsonConstraints.add(constraintNode);
                 }
             }
         }
diff --git a/web/api/src/main/java/org/onosproject/codec/impl/ConstraintCodec.java b/web/api/src/main/java/org/onosproject/codec/impl/ConstraintCodec.java
new file mode 100644
index 0000000..4d60ea9
--- /dev/null
+++ b/web/api/src/main/java/org/onosproject/codec/impl/ConstraintCodec.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2015 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.codec.impl;
+
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
+import org.onosproject.net.intent.Constraint;
+import org.onosproject.net.intent.constraint.AnnotationConstraint;
+import org.onosproject.net.intent.constraint.BandwidthConstraint;
+import org.onosproject.net.intent.constraint.LambdaConstraint;
+import org.onosproject.net.intent.constraint.LatencyConstraint;
+import org.onosproject.net.intent.constraint.LinkTypeConstraint;
+import org.onosproject.net.intent.constraint.ObstacleConstraint;
+import org.onosproject.net.intent.constraint.WaypointConstraint;
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * Constraint JSON codec.
+ */
+public class ConstraintCodec extends JsonCodec<Constraint> {
+
+    /**
+     * Encodes a latency constraint.
+     *
+     * @param constraint latency constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeLatencyConstraint(Constraint constraint,
+                                                CodecContext context) {
+        checkNotNull(constraint, "Duration constraint cannot be null");
+        final LatencyConstraint latencyConstraint =
+                (LatencyConstraint) constraint;
+        return context.mapper().createObjectNode()
+                .put("latencyMillis", latencyConstraint.latency().toMillis());
+    }
+
+    /**
+     * Encodes an obstacle constraint.
+     *
+     * @param constraint obstacle constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeObstacleConstraint(Constraint constraint,
+                                                CodecContext context) {
+        checkNotNull(constraint, "Obstacle constraint cannot be null");
+        final ObstacleConstraint obstacleConstraint =
+                (ObstacleConstraint) constraint;
+
+        final ObjectNode result = context.mapper().createObjectNode();
+        final ArrayNode jsonObstacles = result.putArray("obstacles");
+
+        for (DeviceId did : obstacleConstraint.obstacles()) {
+            jsonObstacles.add(did.toString());
+        }
+
+        return result;
+    }
+
+    /**
+     * Encodes a waypoint constraint.
+     *
+     * @param constraint waypoint constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeWaypointConstraint(Constraint constraint,
+                                                CodecContext context) {
+        checkNotNull(constraint, "Waypoint constraint cannot be null");
+        final WaypointConstraint waypointConstraint =
+                (WaypointConstraint) constraint;
+
+        final ObjectNode result = context.mapper().createObjectNode();
+        final ArrayNode jsonWaypoints = result.putArray("waypoints");
+
+        for (DeviceId did : waypointConstraint.waypoints()) {
+            jsonWaypoints.add(did.toString());
+        }
+
+        return result;
+    }
+
+    /**
+     * Encodes a annotation constraint.
+     *
+     * @param constraint annotation constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeAnnotationConstraint(Constraint constraint,
+                                                  CodecContext context) {
+        checkNotNull(constraint, "Annotation constraint cannot be null");
+        final AnnotationConstraint annotationConstraint =
+                (AnnotationConstraint) constraint;
+        return context.mapper().createObjectNode()
+                .put("key", annotationConstraint.key())
+                .put("threshold", annotationConstraint.threshold());
+    }
+
+    /**
+     * Encodes a bandwidth constraint.
+     *
+     * @param constraint bandwidth constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeBandwidthConstraint(Constraint constraint,
+                                                 CodecContext context) {
+        checkNotNull(constraint, "Bandwidth constraint cannot be null");
+        final BandwidthConstraint bandwidthConstraint =
+                (BandwidthConstraint) constraint;
+        return context.mapper().createObjectNode()
+                .put("bandwidth", bandwidthConstraint.bandwidth().toDouble());
+    }
+
+    /**
+     * Encodes a lambda constraint.
+     *
+     * @param constraint lambda constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeLambdaConstraint(Constraint constraint,
+                                              CodecContext context) {
+        checkNotNull(constraint, "Lambda constraint cannot be null");
+        final LambdaConstraint lambdaConstraint =
+                (LambdaConstraint) constraint;
+
+        return context.mapper().createObjectNode()
+                .put("lambda", lambdaConstraint.lambda().toInt());
+    }
+
+    /**
+     * Encodes a link type constraint.
+     *
+     * @param constraint link type constraint to encode
+     * @param context code context
+     * @return JSON ObjectNode representing the constraint
+     */
+    private ObjectNode encodeLinkTypeConstraint(Constraint constraint,
+                                                        CodecContext context) {
+        checkNotNull(constraint, "Link type constraint cannot be null");
+
+        final LinkTypeConstraint linkTypeConstraint =
+                (LinkTypeConstraint) constraint;
+
+        final ObjectNode result = context.mapper().createObjectNode()
+                .put("inclusive", linkTypeConstraint.isInclusive());
+
+        final ArrayNode jsonTypes = result.putArray("types");
+
+        if (linkTypeConstraint.types() != null) {
+            for (Link.Type type : linkTypeConstraint.types()) {
+                jsonTypes.add(type.name());
+            }
+        }
+
+        return result;
+    }
+
+    @Override
+    public ObjectNode encode(Constraint constraint, CodecContext context) {
+        checkNotNull(constraint, "Constraint cannot be null");
+
+        final ObjectNode result;
+        if (constraint instanceof BandwidthConstraint) {
+            result = encodeBandwidthConstraint(constraint, context);
+        } else if (constraint instanceof LambdaConstraint) {
+            result = encodeLambdaConstraint(constraint, context);
+        } else if (constraint instanceof LinkTypeConstraint) {
+            result = encodeLinkTypeConstraint(constraint, context);
+        } else if (constraint instanceof AnnotationConstraint) {
+            result = encodeAnnotationConstraint(constraint, context);
+        } else if (constraint instanceof LatencyConstraint) {
+            result = encodeLatencyConstraint(constraint, context);
+        } else if (constraint instanceof ObstacleConstraint) {
+            result = encodeObstacleConstraint(constraint, context);
+        } else if (constraint instanceof WaypointConstraint) {
+            result = encodeWaypointConstraint(constraint, context);
+        } else {
+            result = context.mapper().createObjectNode();
+        }
+
+        result.put("type", constraint.getClass().getSimpleName());
+        return result;
+    }
+}
diff --git a/web/api/src/test/java/org/onosproject/codec/impl/IntentCodecTest.java b/web/api/src/test/java/org/onosproject/codec/impl/IntentCodecTest.java
index fd84f17..a230273 100644
--- a/web/api/src/test/java/org/onosproject/codec/impl/IntentCodecTest.java
+++ b/web/api/src/test/java/org/onosproject/codec/impl/IntentCodecTest.java
@@ -15,6 +15,7 @@
  */
 package org.onosproject.codec.impl;
 
+import java.time.Duration;
 import java.util.List;
 
 import org.junit.Test;
@@ -25,6 +26,7 @@
 import org.onosproject.core.ApplicationId;
 import org.onosproject.core.DefaultApplicationId;
 import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
 import org.onosproject.net.HostId;
 import org.onosproject.net.NetTestTools;
 import org.onosproject.net.PortNumber;
@@ -36,8 +38,13 @@
 import org.onosproject.net.intent.HostToHostIntent;
 import org.onosproject.net.intent.AbstractIntentTest;
 import org.onosproject.net.intent.PointToPointIntent;
+import org.onosproject.net.intent.constraint.AnnotationConstraint;
+import org.onosproject.net.intent.constraint.AsymmetricPathConstraint;
 import org.onosproject.net.intent.constraint.BandwidthConstraint;
 import org.onosproject.net.intent.constraint.LambdaConstraint;
+import org.onosproject.net.intent.constraint.LatencyConstraint;
+import org.onosproject.net.intent.constraint.ObstacleConstraint;
+import org.onosproject.net.intent.constraint.WaypointConstraint;
 import org.onosproject.net.resource.Bandwidth;
 import org.onosproject.net.resource.Lambda;
 
@@ -45,6 +52,7 @@
 import com.google.common.collect.ImmutableList;
 
 import static org.onosproject.codec.impl.IntentJsonMatcher.matchesIntent;
+import static org.onosproject.net.NetTestTools.did;
 import static org.onosproject.net.NetTestTools.hid;
 
 
@@ -111,6 +119,9 @@
     public void intentWithTreatmentSelectorAndConstraints() {
         ConnectPoint ingress = NetTestTools.connectPoint("ingress", 1);
         ConnectPoint egress = NetTestTools.connectPoint("egress", 2);
+        DeviceId did1 = did("device1");
+        DeviceId did2 = did("device2");
+        DeviceId did3 = did("device3");
         final TrafficSelector selector = DefaultTrafficSelector.builder()
                 .matchIPProtocol((byte) 3)
                 .matchMplsLabel(4)
@@ -125,9 +136,16 @@
                 .setOutput(PortNumber.CONTROLLER)
                 .setEthDst(MacAddress.BROADCAST)
                 .build();
-        final Constraint constraint1 = new BandwidthConstraint(Bandwidth.valueOf(1.0));
-        final Constraint constraint2 = new LambdaConstraint(Lambda.valueOf(3));
-        final List<Constraint> constraints = ImmutableList.of(constraint1, constraint2);
+
+        final List<Constraint> constraints =
+                ImmutableList.of(
+                    new BandwidthConstraint(Bandwidth.valueOf(1.0)),
+                    new LambdaConstraint(Lambda.valueOf(3)),
+                    new AnnotationConstraint("key", 33.0),
+                    new AsymmetricPathConstraint(),
+                    new LatencyConstraint(Duration.ofSeconds(2)),
+                    new ObstacleConstraint(did1, did2),
+                    new WaypointConstraint(did3));
 
         final PointToPointIntent intent =
                 new PointToPointIntent(appId, selector, treatment,
diff --git a/web/api/src/test/java/org/onosproject/codec/impl/IntentJsonMatcher.java b/web/api/src/test/java/org/onosproject/codec/impl/IntentJsonMatcher.java
index a49307b..9dddd4d 100644
--- a/web/api/src/test/java/org/onosproject/codec/impl/IntentJsonMatcher.java
+++ b/web/api/src/test/java/org/onosproject/codec/impl/IntentJsonMatcher.java
@@ -21,6 +21,8 @@
 import org.hamcrest.Description;
 import org.hamcrest.TypeSafeDiagnosingMatcher;
 import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
 import org.onosproject.net.NetworkResource;
 import org.onosproject.net.flow.TrafficSelector;
 import org.onosproject.net.flow.TrafficTreatment;
@@ -31,6 +33,13 @@
 import org.onosproject.net.intent.HostToHostIntent;
 import org.onosproject.net.intent.Intent;
 import org.onosproject.net.intent.PointToPointIntent;
+import org.onosproject.net.intent.constraint.AnnotationConstraint;
+import org.onosproject.net.intent.constraint.BandwidthConstraint;
+import org.onosproject.net.intent.constraint.LambdaConstraint;
+import org.onosproject.net.intent.constraint.LatencyConstraint;
+import org.onosproject.net.intent.constraint.LinkTypeConstraint;
+import org.onosproject.net.intent.constraint.ObstacleConstraint;
+import org.onosproject.net.intent.constraint.WaypointConstraint;
 
 import com.fasterxml.jackson.databind.JsonNode;
 
@@ -118,6 +127,208 @@
         return true;
     }
 
+
+    /**
+     * Matches a bandwidth constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param bandwidthConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchBandwidthConstraint(BandwidthConstraint bandwidthConstraint,
+                                             JsonNode constraintJson) {
+        final JsonNode bandwidthJson = constraintJson.get("bandwidth");
+        return bandwidthJson != null
+                && constraintJson.get("bandwidth").asDouble()
+                == bandwidthConstraint.bandwidth().toDouble();
+    }
+
+    /**
+     * Matches a lamdba constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param lambdaConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchLambdaConstraint(LambdaConstraint lambdaConstraint,
+                                          JsonNode constraintJson) {
+        final JsonNode lambdaJson = constraintJson.get("lambda");
+        return lambdaJson != null
+                && constraintJson.get("lambda").asInt()
+                == lambdaConstraint.lambda().toInt();
+    }
+
+    /**
+     * Matches a link type constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param linkTypeConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchLinkTypeConstraint(LinkTypeConstraint linkTypeConstraint,
+                                            JsonNode constraintJson) {
+        final JsonNode inclusiveJson = constraintJson.get("inclusive");
+        final JsonNode typesJson = constraintJson.get("types");
+
+        if (typesJson.size() != linkTypeConstraint.types().size()) {
+            return false;
+        }
+
+        int foundType = 0;
+        for (Link.Type type : linkTypeConstraint.types()) {
+            for (int jsonIndex = 0; jsonIndex < typesJson.size(); jsonIndex++) {
+                if (type.name().equals(typesJson.get(jsonIndex).asText())) {
+                    foundType++;
+                    break;
+                }
+            }
+        }
+        return (inclusiveJson != null &&
+                inclusiveJson.asBoolean() == linkTypeConstraint.isInclusive()) &&
+                foundType == typesJson.size();
+    }
+
+    /**
+     * Matches an annotation constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param annotationConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchAnnotationConstraint(AnnotationConstraint annotationConstraint,
+                                              JsonNode constraintJson) {
+        final JsonNode keyJson = constraintJson.get("key");
+        final JsonNode thresholdJson = constraintJson.get("threshold");
+        return (keyJson != null
+                && keyJson.asText().equals(annotationConstraint.key())) &&
+               (thresholdJson != null
+                && thresholdJson.asDouble() == annotationConstraint.threshold());
+    }
+
+    /**
+     * Matches a latency constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param latencyConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchLatencyConstraint(LatencyConstraint latencyConstraint,
+                                           JsonNode constraintJson) {
+        final JsonNode latencyJson = constraintJson.get("latencyMillis");
+        return (latencyJson != null
+                && latencyJson.asInt() == latencyConstraint.latency().toMillis());
+    }
+
+    /**
+     * Matches an obstacle constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param obstacleConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchObstacleConstraint(ObstacleConstraint obstacleConstraint,
+                                            JsonNode constraintJson) {
+        final JsonNode obstaclesJson = constraintJson.get("obstacles");
+
+        if (obstaclesJson.size() != obstacleConstraint.obstacles().size()) {
+            return false;
+        }
+
+        for (int obstaclesIndex = 0; obstaclesIndex < obstaclesJson.size();
+                 obstaclesIndex++) {
+            boolean obstacleFound = false;
+            final String obstacleJson = obstaclesJson.get(obstaclesIndex)
+                    .asText();
+            for (DeviceId obstacle : obstacleConstraint.obstacles()) {
+                if (obstacle.toString().equals(obstacleJson)) {
+                    obstacleFound = true;
+                }
+            }
+            if (!obstacleFound) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Matches a waypoint constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param waypointConstraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchWaypointConstraint(WaypointConstraint waypointConstraint,
+                                            JsonNode constraintJson) {
+        final JsonNode waypointsJson = constraintJson.get("waypoints");
+
+        if (waypointsJson.size() != waypointConstraint.waypoints().size()) {
+            return false;
+        }
+
+        for (int waypointsIndex = 0; waypointsIndex < waypointsJson.size();
+             waypointsIndex++) {
+            boolean waypointFound = false;
+            final String waypointJson = waypointsJson.get(waypointsIndex)
+                    .asText();
+            for (DeviceId waypoint : waypointConstraint.waypoints()) {
+                if (waypoint.toString().equals(waypointJson)) {
+                    waypointFound = true;
+                }
+            }
+            if (!waypointFound) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+
+    /**
+     * Matches a constraint against a JSON representation of the
+     * constraint.
+     *
+     * @param constraint constraint object to match
+     * @param constraintJson JSON representation of the constraint
+     * @return true if the constraint and JSON match, false otherwise.
+     */
+    private boolean matchConstraint(Constraint constraint, JsonNode constraintJson) {
+        final JsonNode typeJson = constraintJson.get("type");
+        if (!typeJson.asText().equals(constraint.getClass().getSimpleName())) {
+            return false;
+        }
+        if (constraint instanceof BandwidthConstraint) {
+            return matchBandwidthConstraint((BandwidthConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof LambdaConstraint) {
+            return matchLambdaConstraint((LambdaConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof LinkTypeConstraint) {
+            return matchLinkTypeConstraint((LinkTypeConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof AnnotationConstraint) {
+            return matchAnnotationConstraint((AnnotationConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof LatencyConstraint) {
+            return matchLatencyConstraint((LatencyConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof ObstacleConstraint) {
+            return matchObstacleConstraint((ObstacleConstraint) constraint,
+                    constraintJson);
+        } else if (constraint instanceof WaypointConstraint) {
+            return matchWaypointConstraint((WaypointConstraint) constraint,
+                    constraintJson);
+        }
+        return true;
+    }
+
     /**
      * Matches the JSON representation of a connectivity intent. Calls the
      * matcher for the connectivity intent subtype.
@@ -193,16 +404,16 @@
             }
             for (final Constraint constraint : connectivityIntent.constraints()) {
                 boolean constraintFound = false;
-                final String constraintString = constraint.toString();
                 for (int constraintIndex = 0; constraintIndex < jsonConstraints.size();
                      constraintIndex++) {
                     final JsonNode value = jsonConstraints.get(constraintIndex);
-                    if (value.asText().equals(constraintString)) {
+                    if (matchConstraint(constraint, value)) {
                         constraintFound = true;
                     }
                 }
                 if (!constraintFound) {
-                    description.appendText("resource missing " + constraintString);
+                    final String constraintString = constraint.toString();
+                    description.appendText("constraint missing " + constraintString);
                     return false;
                 }
             }