Notion of config operators:

Added operator for combining configuration info for Optical ports
from various sources. Also includes minor tweaks to OpticalPortConfig,
and javadoc fixes.

Change-Id: I754b2e29f560b473d1f791025f8b8b18c8d75a13
diff --git a/core/net/src/main/java/org/onosproject/net/device/impl/OpticalPortOperator.java b/core/net/src/main/java/org/onosproject/net/device/impl/OpticalPortOperator.java
new file mode 100644
index 0000000..9fa452a
--- /dev/null
+++ b/core/net/src/main/java/org/onosproject/net/device/impl/OpticalPortOperator.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2014-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.net.device.impl;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+import org.onosproject.incubator.net.config.ConfigOperator;
+import org.onosproject.incubator.net.config.basics.OpticalPortConfig;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.SparseAnnotations;
+import org.onosproject.net.device.DefaultPortDescription;
+import org.onosproject.net.device.OchPortDescription;
+import org.onosproject.net.device.OduCltPortDescription;
+import org.onosproject.net.device.OmsPortDescription;
+import org.onosproject.net.device.PortDescription;
+import org.slf4j.Logger;
+
+/**
+ * Implementations of merge policies for various sources of optical port
+ * configuration information. This includes applications, provides, and network
+ * configurations.
+ */
+public final class OpticalPortOperator implements ConfigOperator {
+
+    private static final Logger log = getLogger(OpticalPortOperator.class);
+
+    private OpticalPortOperator() {
+    }
+
+    /**
+     * Generates a PortDescription containing fields from a PortDescription and
+     * an OpticalPortConfig.
+     *
+     * @param opc the port config entity from network config
+     * @param descr a PortDescription
+     * @return PortDescription based on both sources
+     */
+    public static PortDescription combine(OpticalPortConfig opc, PortDescription descr) {
+        if (opc == null) {
+            return descr;
+        }
+
+        PortNumber port = descr.portNumber();
+        final String name = opc.name();
+        final String numName = opc.numberName();
+        // if the description is null, or the current description port name != config name,
+        // create a new PortNumber.
+        PortNumber newPort = null;
+        if (port == null) {
+            // try to get the portNumber from the numName.
+            if (!numName.isEmpty()) {
+                final long pn = Long.valueOf(numName);
+                newPort = (!name.isEmpty()) ? PortNumber.portNumber(pn, name) : PortNumber.portNumber(pn);
+            } else {
+                // we don't have defining info (a port number value)
+                throw new RuntimeException("Possible misconfig, bailing on handling for: \n\t" + descr);
+            }
+        } else if ((!name.isEmpty()) && !name.equals(port.name())) {
+            final long pn = (numName.isEmpty()) ? port.toLong() : Long.valueOf(numName);
+            newPort = PortNumber.portNumber(pn, name);
+        }
+
+        // Port type won't change unless we're overwriting a port completely.
+        // Watch out for overwrites to avoid class cast craziness.
+        boolean noOwrite = (opc.type() == descr.type()) ? true : false;
+
+        SparseAnnotations sa = combine(opc, descr.annotations());
+        if (noOwrite) {
+            return updateDescription((newPort == null) ? port : newPort, sa, descr);
+        } else {
+            // TODO: must reconstruct a different type of PortDescription.
+            log.info("Type rewrite from {} to {} required", descr.type(), opc.type());
+        }
+        return descr;
+    }
+
+    // updates a port description whose port type has not changed.
+    private static PortDescription updateDescription(
+            PortNumber port, SparseAnnotations sa, PortDescription descr) {
+        switch (descr.type()) {
+            case OMS:
+                OmsPortDescription oms = (OmsPortDescription) descr;
+                return new OmsPortDescription(port, oms.isEnabled(), oms.minFrequency(),
+                        oms.maxFrequency(), oms.grid(), sa);
+            case OCH:
+            // We might need to update lambda below with STATIC_LAMBDA.
+                OchPortDescription och = (OchPortDescription) descr;
+                return new OchPortDescription(port, och.isEnabled(), och.signalType(),
+                        och.isTunable(), och.lambda(), sa);
+            case ODUCLT:
+                OduCltPortDescription odu = (OduCltPortDescription) descr;
+                return new OduCltPortDescription(port, odu.isEnabled(), odu.signalType(), sa);
+            case PACKET:
+            case FIBER:
+                return new DefaultPortDescription(port, descr.isEnabled(), descr.type(),
+                        descr.portSpeed(), sa);
+            default:
+                // this includes copper ports.
+                log.warn("Unsupported optical port type {} - can't update", descr.type());
+                return descr;
+        }
+    }
+
+    /**
+     * Generates an annotation from an existing annotation and OptcalPortConfig.
+     *
+     * @param opc the port config entity from network config
+     * @param an the annotation
+     * @return annotation combining both sources
+     */
+    public static SparseAnnotations combine(OpticalPortConfig opc, SparseAnnotations an) {
+        DefaultAnnotations.Builder b = DefaultAnnotations.builder();
+        if (!opc.staticPort().isEmpty()) {
+            b.set(AnnotationKeys.STATIC_PORT, opc.staticPort());
+        }
+        if (opc.staticLambda().isPresent()) {
+            b.set(AnnotationKeys.STATIC_LAMBDA, String.valueOf(opc.staticLambda().get()));
+        }
+        // The following may not need to be carried.
+        if (!opc.name().isEmpty()) {
+            b.set(AnnotationKeys.PORT_NAME, opc.name());
+        }
+        return DefaultAnnotations.union(an, b.build());
+    }
+}
diff --git a/core/net/src/test/java/org/onosproject/net/device/impl/OpticalPortOperatorTest.java b/core/net/src/test/java/org/onosproject/net/device/impl/OpticalPortOperatorTest.java
new file mode 100644
index 0000000..c798be3
--- /dev/null
+++ b/core/net/src/test/java/org/onosproject/net/device/impl/OpticalPortOperatorTest.java
@@ -0,0 +1,80 @@
+package org.onosproject.net.device.impl;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onosproject.incubator.net.config.Config;
+import org.onosproject.incubator.net.config.ConfigApplyDelegate;
+import org.onosproject.incubator.net.config.basics.OpticalPortConfig;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.OduCltPort;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.SparseAnnotations;
+import org.onosproject.net.device.OduCltPortDescription;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+
+import static org.junit.Assert.assertEquals;
+
+public class OpticalPortOperatorTest {
+    private static final DeviceId DID = DeviceId.deviceId("op-test");
+    private static final String TPNAME = "test-port-100";
+    private static final String SPNAME = "out-port-200";
+    private static final String CFGNAME = "cfg-name";
+
+    private static final PortNumber NAMED = PortNumber.portNumber(100, TPNAME);
+    private static final PortNumber UNNAMED = PortNumber.portNumber(101);
+    private static final ConnectPoint NCP = new ConnectPoint(DID, UNNAMED);
+
+    private static final SparseAnnotations SA = DefaultAnnotations.builder()
+                                                    .set(AnnotationKeys.STATIC_PORT, SPNAME)
+                                                    .build();
+
+    private static final OduCltPortDescription N_DESC = new OduCltPortDescription(
+            NAMED, true, OduCltPort.SignalType.CLT_100GBE, SA);
+    private static final OduCltPortDescription FAULTY = new OduCltPortDescription(
+            null, true, OduCltPort.SignalType.CLT_100GBE);
+
+    private final ConfigApplyDelegate delegate = new MockCfgDelegate();
+    private final ObjectMapper mapper = new ObjectMapper();
+
+    private static final OpticalPortConfig N_OPC = new OpticalPortConfig();
+    private static final OpticalPortConfig UNN_OPC = new OpticalPortConfig();
+
+    @Before
+    public void setUp() {
+        N_OPC.init(NCP, TPNAME, JsonNodeFactory.instance.objectNode(), mapper, delegate);
+        UNN_OPC.init(NCP, TPNAME, JsonNodeFactory.instance.objectNode(), mapper, delegate);
+
+        N_OPC.portName(CFGNAME).portNumberName(101L).portType(Port.Type.ODUCLT).staticLambda(300L);
+        UNN_OPC.portType(Port.Type.ODUCLT);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testDescOps() {
+        // port-null desc + opc with port number name
+        OduCltPortDescription res = (OduCltPortDescription) OpticalPortOperator.combine(N_OPC, FAULTY);
+        assertEquals(CFGNAME, res.portNumber().name());
+        // full desc + opc with name
+        assertEquals(TPNAME, N_DESC.portNumber().name());
+        res = (OduCltPortDescription) OpticalPortOperator.combine(N_OPC, N_DESC);
+        long sl = Long.valueOf(res.annotations().value(AnnotationKeys.STATIC_LAMBDA));
+        assertEquals(CFGNAME, res.portNumber().name());
+        assertEquals(300L, sl);
+        // port-null desc + opc without port number name - throws RE
+        res = (OduCltPortDescription) OpticalPortOperator.combine(UNN_OPC, FAULTY);
+    }
+
+    private class MockCfgDelegate implements ConfigApplyDelegate {
+
+        @Override
+        public void onApply(@SuppressWarnings("rawtypes") Config config) {
+            config.apply();
+        }
+
+    }
+}
diff --git a/incubator/api/src/main/java/org/onosproject/incubator/net/config/ConfigOperator.java b/incubator/api/src/main/java/org/onosproject/incubator/net/config/ConfigOperator.java
new file mode 100644
index 0000000..ab02e88
--- /dev/null
+++ b/incubator/api/src/main/java/org/onosproject/incubator/net/config/ConfigOperator.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2014-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.incubator.net.config;
+
+/**
+ * An interface signifying a class that implements network configuration
+ * information from multiple sources. There is a natural ordering to the
+ * precedence of information, depending on its source:
+ * <ol>
+ * <li>Intents (from applications), which override</li>
+ * <li>Configs (from the network configuration subsystem), which override</li>
+ * <li>Descriptions (from southbound)</li>
+ * </ol>
+ * i.e., for a field representing the same attribute, the value from a Config
+ * entity will be used over that from the Description.
+ */
+public interface ConfigOperator {
+}
\ No newline at end of file
diff --git a/incubator/api/src/main/java/org/onosproject/incubator/net/config/basics/OpticalPortConfig.java b/incubator/api/src/main/java/org/onosproject/incubator/net/config/basics/OpticalPortConfig.java
index 3757e7c..e9aad7a 100644
--- a/incubator/api/src/main/java/org/onosproject/incubator/net/config/basics/OpticalPortConfig.java
+++ b/incubator/api/src/main/java/org/onosproject/incubator/net/config/basics/OpticalPortConfig.java
@@ -3,7 +3,6 @@
 import java.util.Optional;
 
 import org.onosproject.incubator.net.config.Config;
-import org.onosproject.net.AnnotationKeys;
 import org.onosproject.net.ConnectPoint;
 import org.onosproject.net.Port;
 
@@ -19,9 +18,11 @@
 
     // port name. "name" is the alphanumeric name of the port, but "port" refers
     // to the port number used as a name string (i.e., for ports without
-    // alphanumeric names). this should be linked to ConnectPoint.
+    // alphanumeric names).
     public static final String NAME = "name";
     public static final String PORT = "port";
+    public static final String STATIC_PORT = "staticPort";
+    public static final String STATIC_LAMBDA = "staticLambda";
 
     /**
      * Returns the Enum value representing the type of port.
@@ -38,14 +39,22 @@
 
     /**
      * Returns the port name associated with this port configuration. The Name
-     * may either be an alphanumeric string, or a string representation of the
-     * port number, falling back on the latter if the former doesn't exist.
+     * is an alphanumeric string.
      *
      * @return the name of this port, else, an empty string
      */
     public String name() {
-        String name = getStringValue(NAME);
-        return name.isEmpty() ? getStringValue(PORT) : name;
+        return getStringValue(NAME);
+    }
+
+    /**
+     * Returns a stringified representation of the port number, configured in
+     * some port types without an alphanumeric name as the port name.
+     *
+     * @return A string representation of the port number
+     */
+    public String numberName() {
+        return getStringValue(PORT);
     }
 
     /**
@@ -56,7 +65,7 @@
      * @return the name of this port, else, an empty string
      */
     public String staticPort() {
-        return getStringValue(AnnotationKeys.STATIC_PORT);
+        return getStringValue(STATIC_PORT);
     }
 
     private String getStringValue(String field) {
@@ -71,7 +80,7 @@
      * @return an Optional that may contain a frequency value.
      */
     public Optional<Long> staticLambda() {
-        JsonNode sl = node.path(AnnotationKeys.STATIC_LAMBDA);
+        JsonNode sl = node.path(STATIC_LAMBDA);
         if (sl.isMissingNode()) {
             return Optional.empty();
         }
@@ -121,7 +130,7 @@
      * @return this OpticalPortConfig instance
      */
     public OpticalPortConfig staticPort(String name) {
-        return (OpticalPortConfig) setOrClear(AnnotationKeys.STATIC_PORT, name);
+        return (OpticalPortConfig) setOrClear(STATIC_PORT, name);
     }
 
     /**
@@ -132,7 +141,7 @@
      * @return this OpticalPortConfig instance
      */
     public OpticalPortConfig staticLambda(Long index) {
-        return (OpticalPortConfig) setOrClear(AnnotationKeys.STATIC_LAMBDA, index);
+        return (OpticalPortConfig) setOrClear(STATIC_LAMBDA, index);
     }
 
 }
diff --git a/incubator/api/src/test/java/org/onosproject/incubator/net/config/basics/OpticalPortConfigTest.java b/incubator/api/src/test/java/org/onosproject/incubator/net/config/basics/OpticalPortConfigTest.java
index a30582e..9a9a8b3 100644
--- a/incubator/api/src/test/java/org/onosproject/incubator/net/config/basics/OpticalPortConfigTest.java
+++ b/incubator/api/src/test/java/org/onosproject/incubator/net/config/basics/OpticalPortConfigTest.java
@@ -5,6 +5,8 @@
 import static org.onosproject.incubator.net.config.basics.OpticalPortConfig.TYPE;
 import static org.onosproject.incubator.net.config.basics.OpticalPortConfig.NAME;
 import static org.onosproject.incubator.net.config.basics.OpticalPortConfig.PORT;
+import static org.onosproject.incubator.net.config.basics.OpticalPortConfig.STATIC_LAMBDA;
+import static org.onosproject.incubator.net.config.basics.OpticalPortConfig.STATIC_PORT;
 
 import java.io.IOException;
 import java.util.Iterator;
@@ -14,7 +16,6 @@
 import org.junit.Test;
 import org.onosproject.incubator.net.config.Config;
 import org.onosproject.incubator.net.config.ConfigApplyDelegate;
-import org.onosproject.net.AnnotationKeys;
 import org.onosproject.net.ConnectPoint;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.Port;
@@ -103,7 +104,8 @@
 
         assertEquals(Port.Type.OMS, op0.type());
         assertEquals(jn0.path(NAME).asText(), op0.name());
-        assertEquals(jn1.path(PORT).asText(), op1.name());
+        assertEquals(jn1.path(PORT).asText(), op1.numberName());
+        assertEquals("", op1.name());
         assertEquals("", op2.name());
     }
 
@@ -116,8 +118,8 @@
         Long sl = 1L;
 
         // see config entity 2 in DEMOTREE
-        op2.staticLambda(jn2.path("annotations").path(AnnotationKeys.STATIC_LAMBDA).asLong());
-        op2.staticPort(jn2.path("annotations").path(AnnotationKeys.STATIC_PORT).asText());
+        op2.staticLambda(jn2.path("annotations").path(STATIC_LAMBDA).asLong());
+        op2.staticPort(jn2.path("annotations").path(STATIC_PORT).asText());
 
         assertEquals(sl, op2.staticLambda().get());
         assertFalse(op1.staticLambda().isPresent());