fix deprecated openroadm interfaces/objects
[transportpce.git] / olm / src / main / java / org / opendaylight / transportpce / olm / service / OlmPowerServiceImpl.java
index c76401a8ee37d066034a2af2d04810b8511b6d13..b91fe7ccc4b96d46eb7d26b4935b241db6fb81d4 100644 (file)
@@ -9,7 +9,6 @@
 package org.opendaylight.transportpce.olm.service;
 
 import com.google.common.base.Strings;
-import com.google.common.util.concurrent.ListenableFuture;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.ArrayList;
@@ -21,22 +20,26 @@ import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.ReadTransaction;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
 import org.opendaylight.transportpce.common.InstanceIdentifiers;
 import org.opendaylight.transportpce.common.NetworkUtils;
+import org.opendaylight.transportpce.common.ResponseCodes;
+import org.opendaylight.transportpce.common.StringConstants;
 import org.opendaylight.transportpce.common.Timeouts;
-import org.opendaylight.transportpce.common.device.DeviceTransaction;
 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
+import org.opendaylight.transportpce.common.mapping.MappingUtils;
 import org.opendaylight.transportpce.common.mapping.PortMapping;
+import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
+import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
 import org.opendaylight.transportpce.olm.power.PowerMgmt;
 import org.opendaylight.transportpce.olm.util.OlmUtils;
 import org.opendaylight.transportpce.olm.util.OtsPmHolder;
+import org.opendaylight.transportpce.olm.util.RoadmLinks;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.CalculateSpanlossBaseInput;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.CalculateSpanlossBaseOutput;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.CalculateSpanlossBaseOutputBuilder;
@@ -58,31 +61,33 @@ import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev17
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.calculate.spanloss.base.output.Spans;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.calculate.spanloss.base.output.SpansBuilder;
 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.olm.rev170418.get.pm.output.Measurements;
-import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev170228.network.nodes.Mapping;
+import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev191115.network.nodes.Mapping;
+import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev191115.network.nodes.NodeInfo.OpenroadmVersion;
+import org.opendaylight.yang.gen.v1.http.org.openroadm.common.network.rev181130.Link1;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev161014.RatioDB;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.Interface;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceBuilder;
-import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.interfaces.grp.InterfaceKey;
-import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev170206.org.openroadm.device.container.OrgOpenroadmDevice;
-import org.opendaylight.yang.gen.v1.http.org.openroadm.network.topology.rev170929.Link1;
-import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev170929.OpenroadmLinkType;
+import org.opendaylight.yang.gen.v1.http.org.openroadm.network.types.rev181130.OpenroadmLinkType;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.Interface1;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.Interface1Builder;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.ots.container.Ots;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces.rev161014.ots.container.OtsBuilder;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.pm.types.rev161014.PmGranularity;
 import org.opendaylight.yang.gen.v1.http.org.openroadm.resource.types.rev161014.ResourceTypeEnum;
+import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev170907.PmNamesEnum;
 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev170907.olm.get.pm.input.ResourceIdentifierBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.Network;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.NetworkId;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.NetworkKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.NodeId;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.network.Node;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.network.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev150608.network.node.SupportingNode;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev150608.LinkId;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev150608.Network1;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev150608.network.Link;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NetworkId;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.Networks;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.NodeId;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.Network;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.NetworkKey;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.Node;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.NodeKey;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.rev180226.networks.network.node.SupportingNode;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.LinkId;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.Network1;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.Link;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.network.topology.rev180226.networks.network.LinkKey;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.slf4j.Logger;
@@ -90,19 +95,22 @@ import org.slf4j.LoggerFactory;
 
 public class OlmPowerServiceImpl implements OlmPowerService {
     private static final Logger LOG = LoggerFactory.getLogger(OlmPowerServiceImpl.class);
-    private static final String SUCCESS = "Success";
-    private static final String FAILED = "Failed";
+    private final MappingUtils mappingUtils;
+    private final OpenRoadmInterfaces openRoadmInterfaces;
     private final DataBroker dataBroker;
     private final PowerMgmt powerMgmt;
     private final DeviceTransactionManager deviceTransactionManager;
     private final PortMapping portMapping;
 
     public OlmPowerServiceImpl(DataBroker dataBroker, PowerMgmt powerMgmt,
-            DeviceTransactionManager deviceTransactionManager, PortMapping portMapping) {
+                               DeviceTransactionManager deviceTransactionManager, PortMapping portMapping,
+                               MappingUtils mappingUtils, OpenRoadmInterfaces openRoadmInterfaces) {
         this.dataBroker = dataBroker;
         this.powerMgmt = powerMgmt;
         this.portMapping = portMapping;
         this.deviceTransactionManager = deviceTransactionManager;
+        this.mappingUtils = mappingUtils;
+        this.openRoadmInterfaces = openRoadmInterfaces;
     }
 
     public void init() {
@@ -116,77 +124,107 @@ public class OlmPowerServiceImpl implements OlmPowerService {
 
     @Override
     public GetPmOutput getPm(GetPmInput pmInput) {
-        GetPmOutputBuilder pmOutputBuilder = OlmUtils.pmFetch(pmInput, this.deviceTransactionManager);
+        OpenroadmVersion openroadmVersion;
+        if (mappingUtils.getOpenRoadmVersion(pmInput.getNodeId())
+            .equals(StringConstants.OPENROADM_DEVICE_VERSION_1_2_1)) {
+            LOG.info("Device version is 1.2.1");
+            openroadmVersion = OpenroadmVersion._121;
+        } else {
+            openroadmVersion = OpenroadmVersion._221;
+            LOG.info("Device version is 2.2.1");
+        }
+        LOG.info("Now calling get pm data");
+        GetPmOutputBuilder pmOutputBuilder = OlmUtils.pmFetch(pmInput, deviceTransactionManager,
+            openroadmVersion);
         return pmOutputBuilder.build();
     }
 
     @Override
     public ServicePowerSetupOutput servicePowerSetup(ServicePowerSetupInput powerSetupInput) {
         ServicePowerSetupOutputBuilder powerSetupOutput = new ServicePowerSetupOutputBuilder();
-        boolean successValPowerCalculation = this.powerMgmt.setPower(powerSetupInput);
-
+        boolean successValPowerCalculation = powerMgmt.setPower(powerSetupInput);
         if (successValPowerCalculation) {
-            powerSetupOutput.setResult(SUCCESS);
+            powerSetupOutput.setResult(ResponseCodes.SUCCESS_RESULT);
         } else {
-            powerSetupOutput.setResult(FAILED);
+            powerSetupOutput.setResult(ResponseCodes.FAILED_RESULT);
         }
         return powerSetupOutput.build();
     }
 
     @Override
     public ServicePowerTurndownOutput servicePowerTurndown(
-            ServicePowerTurndownInput powerTurndownInput) {
+        ServicePowerTurndownInput powerTurndownInput) {
 
         ServicePowerTurndownOutputBuilder powerTurnDownOutput = new ServicePowerTurndownOutputBuilder();
         // TODO add flag or return failure instead of string
-        if (this.powerMgmt.powerTurnDown(powerTurndownInput)) {
-            powerTurnDownOutput.setResult(SUCCESS);
+        if (powerMgmt.powerTurnDown(powerTurndownInput)) {
+            powerTurnDownOutput.setResult(ResponseCodes.SUCCESS_RESULT);
         } else {
-            powerTurnDownOutput.setResult(FAILED);
+            powerTurnDownOutput.setResult(ResponseCodes.FAILED_RESULT);
         }
         return powerTurnDownOutput.build();
     }
 
     @Override
     public CalculateSpanlossBaseOutput calculateSpanlossBase(CalculateSpanlossBaseInput spanlossBaseInput) {
-
         LOG.info("CalculateSpanlossBase Request received for source type {}", spanlossBaseInput.getSrcType());
-        List<Link> networkLinks = getNetworkLinks();
-        if (networkLinks.isEmpty()) {
-            LOG.warn("Failed to get links form {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
-            return new CalculateSpanlossBaseOutputBuilder().setResult(FAILED).build();
-        }
-
-        if (! CalculateSpanlossBaseInput.SrcType.All.equals(spanlossBaseInput.getSrcType())) {
-            networkLinks = networkLinks.stream()
-                    .filter(link -> link.getLinkId().equals(spanlossBaseInput.getLinkId()))
-                    .collect(Collectors.toList());
-        }
-
-        List<Link> roadmLinks = new ArrayList<>();
-        for (Link link : networkLinks) {
-            Link1 roadmLinkAugmentation = link.augmentation(Link1.class);
-            if (roadmLinkAugmentation == null) {
-                LOG.debug("Missing OpenRoadm link augmentation in link {} from {} topology.",
-                        link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
-                continue;
-            }
-            if (OpenroadmLinkType.ROADMTOROADM.equals(roadmLinkAugmentation.getLinkType())) {
-                // Only calculate spanloss for Roadm-to-Roadm links
-                roadmLinks.add(link);
-            }
-        }
-
-        if (roadmLinks.isEmpty()) {
-            LOG.warn("Topology {} does not have any Roadm-to-Roadm links.", NetworkUtils.OVERLAY_NETWORK_ID);
-            return new CalculateSpanlossBaseOutputBuilder().setResult(FAILED).build();
-        }
-
-        Map<LinkId, BigDecimal> spanLossResult = getLinkSpanloss(roadmLinks);
+        List<RoadmLinks> roadmLinks = new ArrayList<>();
         CalculateSpanlossBaseOutputBuilder spanLossBaseBuilder = new CalculateSpanlossBaseOutputBuilder();
+        Map<LinkId, BigDecimal> spanLossResult = null;
+        //Depending on the source type do the calculation
+        switch (spanlossBaseInput.getSrcType()) {
+            case Link:
+                LOG.debug("Calculate SpanLossBase for a linkId: {}",spanlossBaseInput.getLinkId());
+                Link inputLink = getNetworkLinkById(spanlossBaseInput.getLinkId());
+                if (inputLink != null) {
+                    RoadmLinks roadmLink = new RoadmLinks();
+                    roadmLink.setSrcNodeId(inputLink.getSource().getSourceNode().getValue());
+                    roadmLink.setSrcTpId(inputLink.getSource().getSourceTp().toString());
+                    roadmLink.setDestNodeId(inputLink.getDestination().getDestNode().getValue());
+                    roadmLink.setDestTpid(inputLink.getDestination().getDestTp().toString());
+                    roadmLink.setLinkId(inputLink.getLinkId());
+                    roadmLinks.add(roadmLink);
+                    spanLossResult = getLinkSpanloss(roadmLinks);
+                }
+                break;
+            case All:
+                LOG.info("Do something for all");
+                List<Link> networkLinks = getNetworkLinks();
+                if (networkLinks.isEmpty()) {
+                    LOG.warn("Failed to get links form {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
+                    return new CalculateSpanlossBaseOutputBuilder().setResult(ResponseCodes.FAILED_RESULT).build();
+                }
+                //else for all other links
+                for (Link link : networkLinks) {
+                    Link1 roadmLinkAugmentation = link.augmentation(Link1.class);
+                    if (roadmLinkAugmentation == null) {
+                        LOG.debug("Missing OpenRoadm link augmentation in link {} from {} topology.",
+                            link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
+                        continue;
+                    }
+                    if (OpenroadmLinkType.ROADMTOROADM.equals(roadmLinkAugmentation.getLinkType())) {
+                        // Only calculate spanloss for Roadm-to-Roadm links
+                        RoadmLinks roadmLink = new RoadmLinks();
+                        roadmLink.setSrcNodeId(link.getSource().getSourceNode().getValue());
+                        roadmLink.setSrcTpId(link.getSource().getSourceTp().toString());
+                        roadmLink.setDestNodeId(link.getDestination().getDestNode().getValue());
+                        roadmLink.setDestTpid(link.getDestination().getDestTp().toString());
+                        roadmLink.setLinkId(link.getLinkId());
+                        roadmLinks.add(roadmLink);
+                    }
+                }
+                if (roadmLinks.isEmpty()) {
+                    LOG.warn("Topology {} does not have any Roadm-to-Roadm links.", NetworkUtils.OVERLAY_NETWORK_ID);
+                    return new CalculateSpanlossBaseOutputBuilder().setResult(ResponseCodes.FAILED_RESULT).build();
+                }
+                spanLossResult = getLinkSpanloss(roadmLinks);
+                break;
+            default:
+                LOG.info("Invalid input in request");
+        }
 
         if (spanLossResult != null && !spanLossResult.isEmpty()) {
-            spanLossBaseBuilder.setResult(SUCCESS);
+            spanLossBaseBuilder.setResult(ResponseCodes.SUCCESS_RESULT);
             List<Spans> listSpans = new ArrayList<>();
             Set<Entry<LinkId, BigDecimal>> spanLossResultSet = spanLossResult.entrySet();
             for (Entry<LinkId, BigDecimal> entry : spanLossResultSet) {
@@ -198,12 +236,13 @@ public class OlmPowerServiceImpl implements OlmPowerService {
             return spanLossBaseBuilder.build();
         } else {
             LOG.warn("Spanloss calculation failed");
-            spanLossBaseBuilder.setResult(FAILED);
+            spanLossBaseBuilder.setResult(ResponseCodes.FAILED_RESULT);
             return spanLossBaseBuilder.build();
         }
 
     }
 
+
     @Override
     public CalculateSpanlossCurrentOutput calculateSpanlossCurrent(CalculateSpanlossCurrentInput input) {
         LOG.info("calculateSpanlossCurrent Request received for all links in network model.");
@@ -212,17 +251,22 @@ public class OlmPowerServiceImpl implements OlmPowerService {
             LOG.warn("Failed to get links form {} topology.", NetworkUtils.OVERLAY_NETWORK_ID);
             return null;
         }
-        List<Link> roadmLinks = new ArrayList<>();
+        List<RoadmLinks> roadmLinks = new ArrayList<>();
         for (Link link : networkLinks) {
             Link1 roadmLinkAugmentation = link.augmentation(Link1.class);
             if (roadmLinkAugmentation == null) {
                 LOG.debug("Missing OpenRoadm link augmentation in link {} from {} topology.",
-                        link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
+                    link.getLinkId().getValue(), NetworkUtils.OVERLAY_NETWORK_ID);
                 continue;
             }
             if (OpenroadmLinkType.ROADMTOROADM.equals(roadmLinkAugmentation.getLinkType())) {
                 // Only calculate spanloss for Roadm-to-Roadm links
-                roadmLinks.add(link);
+                RoadmLinks roadmLink = new RoadmLinks();
+                roadmLink.setSrcNodeId(link.getSource().getSourceNode().getValue());
+                roadmLink.setSrcTpId(link.getSource().getSourceTp().toString());
+                roadmLink.setDestNodeId(link.getDestination().getDestNode().getValue());
+                roadmLink.setDestTpid(link.getDestination().getDestTp().toString());
+                roadmLinks.add(roadmLink);
             }
         }
 
@@ -234,11 +278,11 @@ public class OlmPowerServiceImpl implements OlmPowerService {
         Map<LinkId, BigDecimal> spanLossResult = getLinkSpanloss(roadmLinks);
         CalculateSpanlossCurrentOutputBuilder spanLossCurrentBuilder = new CalculateSpanlossCurrentOutputBuilder();
         if (spanLossResult != null && !spanLossResult.isEmpty()) {
-            spanLossCurrentBuilder.setResult(SUCCESS);
+            spanLossCurrentBuilder.setResult(ResponseCodes.SUCCESS_RESULT);
             return spanLossCurrentBuilder.build();
         } else {
             LOG.error("Spanloss Current calculation failed");
-            spanLossCurrentBuilder.setResult(FAILED);
+            spanLossCurrentBuilder.setResult(ResponseCodes.FAILED_RESULT);
             return spanLossCurrentBuilder.build();
         }
     }
@@ -252,14 +296,16 @@ public class OlmPowerServiceImpl implements OlmPowerService {
     private List<Link> getNetworkLinks() {
         NetworkKey overlayTopologyKey = new NetworkKey(new NetworkId(NetworkUtils.OVERLAY_NETWORK_ID));
 
-        InstanceIdentifier<Network1> networkIID = InstanceIdentifier.builder(Network.class, overlayTopologyKey)
+        InstanceIdentifier<Network1> networkIID = InstanceIdentifier.builder(Networks.class)
+            .child(Network.class, overlayTopologyKey)
                 .augmentation(Network1.class)
                 .build();
         Optional<Network1> networkOptional;
-        try (ReadOnlyTransaction rtx = this.dataBroker.newReadOnlyTransaction()) {
+        try (ReadTransaction rtx = this.dataBroker.newReadOnlyTransaction()) {
             //TODO change to constant from Timeouts class when it will be merged.
             networkOptional = rtx.read(LogicalDatastoreType.CONFIGURATION, networkIID).get(Timeouts.DATASTORE_READ,
-                    TimeUnit.MILLISECONDS).toJavaUtil();
+                TimeUnit.MILLISECONDS);
+
         } catch (InterruptedException | ExecutionException | TimeoutException e) {
             LOG.warn("Read of {} topology failed", NetworkUtils.OVERLAY_NETWORK_ID);
             return Collections.emptyList();
@@ -267,7 +313,8 @@ public class OlmPowerServiceImpl implements OlmPowerService {
 
         if (! networkOptional.isPresent()) {
             LOG.warn("Network augmentation with links data is not present in {} topology.",
-                    NetworkUtils.OVERLAY_NETWORK_ID);
+                NetworkUtils.OVERLAY_NETWORK_ID);
+
             return Collections.emptyList();
         }
 
@@ -294,15 +341,17 @@ public class OlmPowerServiceImpl implements OlmPowerService {
      */
     private OtsPmHolder getPmMeasurements(String nodeId, String tpID, String pmName) {
         String realNodeId = getRealNodeId(nodeId);
-        Mapping mapping = this.portMapping.getMapping(realNodeId, tpID);
+        Mapping mapping = portMapping.getMapping(realNodeId, tpID);
         if (mapping == null) {
             return null;
         }
         GetPmInput getPmInput = new GetPmInputBuilder().setNodeId(realNodeId)
-                .setResourceType(ResourceTypeEnum.Interface).setGranularity(PmGranularity._15min)
-                .setResourceIdentifier(
-                        new ResourceIdentifierBuilder().setResourceName(mapping.getSupportingOts()).build())
-                .build();
+            .setResourceType(ResourceTypeEnum.Interface)
+            .setResourceIdentifier(
+                new ResourceIdentifierBuilder().setResourceName(mapping.getSupportingOts()).build())
+            .setPmNameType(PmNamesEnum.valueOf(pmName))
+            .setGranularity(PmGranularity._15min)
+            .build();
         GetPmOutput otsPmOutput = getPm(getPmInput);
 
         if (otsPmOutput == null) {
@@ -313,7 +362,7 @@ public class OlmPowerServiceImpl implements OlmPowerService {
             for (Measurements measurement : otsPmOutput.getMeasurements()) {
                 if (pmName.equals(measurement.getPmparameterName())) {
                     return new OtsPmHolder(pmName, Double.parseDouble(measurement.getPmparameterValue()),
-                            mapping.getSupportingOts());
+                        mapping.getSupportingOts());
                 }
             }
         } catch (NumberFormatException e) {
@@ -339,68 +388,114 @@ public class OlmPowerServiceImpl implements OlmPowerService {
      */
     private boolean setSpanLoss(String nodeId, String interfaceName, BigDecimal spanLoss, String direction) {
         String realNodeId = getRealNodeId(nodeId);
-        LOG.info("Setting Spanloss in device for {}, InterfaceName: {}", realNodeId, interfaceName);
-        switch (direction) {
-            case "TX":
-                LOG.info("Setting 'span-loss-transmit' in device:  {}, Interface: {}", realNodeId, interfaceName);
-                break;
-            case "RX":
-                LOG.info("Setting 'span-loss-receive' in device:  {}, Interface: {}", realNodeId, interfaceName);
-                break;
-            default:
-                LOG.error("Impossible to set spanloss in device:  {}, Interface: {}", realNodeId, interfaceName);
-                break;
-        }
-        InstanceIdentifier<Interface> interfacesIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
-                .child(Interface.class, new InterfaceKey(interfaceName));
-        com.google.common.base.Optional<Interface> interfaceObject;
         try {
-            Future<Optional<DeviceTransaction>> deviceTxFuture =
-                    this.deviceTransactionManager.getDeviceTransaction(realNodeId);
-            java.util.Optional<DeviceTransaction> deviceTxOpt = deviceTxFuture.get();
-            DeviceTransaction deviceTx;
-            if (deviceTxOpt.isPresent()) {
-                deviceTx = deviceTxOpt.get();
-            } else {
-                LOG.error("Device transaction for device {} was not found!", nodeId);
-                return false;
-            }
-            interfaceObject = deviceTx.read(LogicalDatastoreType.CONFIGURATION, interfacesIID).get();
-            BigDecimal initialSpanloss = new BigDecimal(0);
-            RatioDB spanLossRx = new RatioDB(initialSpanloss);
-            RatioDB spanLossTx = new RatioDB(initialSpanloss);
-            if (interfaceObject.isPresent()) {
-                Interface intf = interfaceObject.get();
-                InterfaceBuilder interfaceBuilder = new InterfaceBuilder(intf);
-                OtsBuilder otsBuilder = new OtsBuilder();
-                if ((intf.augmentation(Interface1.class) != null)
-                    && (intf.augmentation(Interface1.class).getOts() != null)) {
-                    Ots ots = intf.augmentation(Interface1.class).getOts();
-                    otsBuilder.setFiberType(ots.getFiberType());
-                    spanLossRx = ots.getSpanLossReceive();
-                    spanLossTx = ots.getSpanLossTransmit();
+            LOG.info("Setting Spanloss in device for {}, InterfaceName: {}", realNodeId, interfaceName);
+            if (mappingUtils.getOpenRoadmVersion(realNodeId)
+                .equals(StringConstants.OPENROADM_DEVICE_VERSION_1_2_1)) {
+                RatioDB spanLossRx;
+                RatioDB spanLossTx;
+
+                Optional<Interface> interfaceObject;
+                interfaceObject = openRoadmInterfaces.getInterface(realNodeId, interfaceName);
+                if (interfaceObject.isPresent()) {
+                    InterfaceBuilder interfaceBuilder = new InterfaceBuilder(interfaceObject.get());
+                    OtsBuilder otsBuilder = new OtsBuilder();
+                    Interface intf = interfaceObject.get();
+                    if (intf.augmentation(Interface1.class) != null
+                        && intf.augmentation(Interface1.class).getOts() != null) {
+                        Ots ots = intf.augmentation(Interface1.class).getOts();
+                        otsBuilder.setFiberType(ots.getFiberType());
+                        spanLossRx = ots.getSpanLossReceive();
+                        spanLossTx = ots.getSpanLossTransmit();
+                    } else {
+                        spanLossRx = new RatioDB(spanLoss);
+                        spanLossTx = new RatioDB(spanLoss);
+                    }
+                    Interface1Builder intf1Builder = new Interface1Builder();
+                    if (direction.equals("TX")) {
+                        otsBuilder.setSpanLossTransmit(new RatioDB(spanLoss));
+                        otsBuilder.setSpanLossReceive(spanLossRx);
+                    } else {
+                        otsBuilder.setSpanLossTransmit(spanLossTx).setSpanLossReceive(new RatioDB(spanLoss));
+                    }
+                    interfaceBuilder.addAugmentation(Interface1.class, intf1Builder.setOts(otsBuilder.build()).build());
+                    openRoadmInterfaces.postInterface(realNodeId,interfaceBuilder);
+                    LOG.info("Spanloss Value update completed successfully");
+                    return true;
                 } else {
-                    spanLossRx = new RatioDB(spanLoss);
-                    spanLossTx = new RatioDB(spanLoss);
+                    LOG.error("Interface not found for nodeId: {} and interfaceName: {}", nodeId, interfaceName);
+                    return false;
                 }
-                Interface1Builder intf1Builder = new Interface1Builder();
-                if (direction.equals("TX")) {
-                    otsBuilder.setSpanLossTransmit(new RatioDB(spanLoss));
-                    otsBuilder.setSpanLossReceive(spanLossRx);
+            } else if (mappingUtils.getOpenRoadmVersion(realNodeId)
+                .equals(StringConstants.OPENROADM_DEVICE_VERSION_2_2_1)) {
+
+                org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.RatioDB spanLossRx;
+                org.opendaylight.yang.gen.v1.http.org.openroadm.common.types
+                    .rev181019.RatioDB spanLossTx;
+                Optional<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019
+                    .interfaces.grp.Interface> interfaceObject =
+                        openRoadmInterfaces.getInterface(realNodeId, interfaceName);
+                if (interfaceObject.isPresent()) {
+                    org.opendaylight.yang.gen.v1.http.org.openroadm.device
+                        .rev181019.interfaces.grp.InterfaceBuilder interfaceBuilder =
+                        new org.opendaylight.yang.gen.v1.http.org.openroadm.device
+                            .rev181019.interfaces.grp.InterfaceBuilder(interfaceObject.get());
+                    org.opendaylight.yang.gen.v1.http.org.openroadm.optical
+                        .transport.interfaces.rev181019.ots.container.OtsBuilder otsBuilder =
+                        new org.opendaylight.yang.gen.v1.http.org.openroadm
+                            .optical.transport.interfaces.rev181019.ots.container.OtsBuilder();
+                    org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev181019.interfaces.grp.Interface intf =
+                        interfaceObject.get();
+                    if (intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical
+                        .transport.interfaces.rev181019.Interface1.class) != null
+                            && intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport
+                                .interfaces.rev181019.Interface1.class).getOts() != null) {
+                        org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces
+                            .rev181019.ots.container.Ots ots =
+                                intf.augmentation(org.opendaylight.yang.gen.v1.http.org.openroadm.optical
+                                    .transport.interfaces.rev181019.Interface1.class).getOts();
+
+                        otsBuilder.setFiberType(ots.getFiberType());
+                        spanLossRx = ots.getSpanLossReceive();
+                        spanLossTx = ots.getSpanLossTransmit();
+                    } else {
+                        spanLossRx = new org.opendaylight.yang.gen.v1.http.org
+                            .openroadm.common.types.rev181019.RatioDB(spanLoss);
+                        spanLossTx = new org.opendaylight.yang.gen.v1.http.org
+                            .openroadm.common.types.rev181019.RatioDB(spanLoss);
+                    }
+                    org.opendaylight.yang.gen.v1.http.org.openroadm.optical.transport.interfaces
+                        .rev181019.Interface1Builder intf1Builder =
+                            new org.opendaylight.yang.gen.v1.http.org.openroadm.optical
+                            .transport.interfaces.rev181019.Interface1Builder();
+                    if (direction.equals("TX")) {
+                        otsBuilder.setSpanLossTransmit(new org.opendaylight.yang.gen.v1.http.org
+                            .openroadm.common.types.rev181019.RatioDB(spanLoss));
+                        otsBuilder.setSpanLossReceive(spanLossRx);
+                    } else {
+                        otsBuilder.setSpanLossTransmit(spanLossTx).setSpanLossReceive(
+                            new org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.RatioDB(spanLoss)
+                        );
+                    }
+                    interfaceBuilder.addAugmentation(org.opendaylight.yang.gen.v1.http
+                        .org.openroadm.optical.transport.interfaces.rev181019.Interface1.class,
+                        intf1Builder.setOts(otsBuilder.build()).build());
+                    openRoadmInterfaces.postInterface(realNodeId,interfaceBuilder);
+                    LOG.info("Spanloss Value update completed successfully");
+                    return true;
                 } else {
-                    otsBuilder.setSpanLossTransmit(spanLossTx).setSpanLossReceive(new RatioDB(spanLoss));
+                    LOG.error("Interface not found for nodeId: {} and interfaceName: {}", nodeId,interfaceName);
+                    return false;
                 }
-                interfaceBuilder.addAugmentation(Interface1.class, intf1Builder.setOts(otsBuilder.build()).build());
-                deviceTx.put(LogicalDatastoreType.CONFIGURATION, interfacesIID, interfaceBuilder.build());
-                ListenableFuture<Void> submit =
-                        deviceTx.submit(Timeouts.DEVICE_WRITE_TIMEOUT, Timeouts.DEVICE_WRITE_TIMEOUT_UNIT);
-                submit.get();
-                LOG.info("Spanloss Value update completed successfully");
-                return true;
             }
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.warn("Unable to set spanloss", e);
-        }
+        } catch (OpenRoadmInterfaceException e) {
+            // TODO Auto-generated catch block
+            LOG.error("OpenRoadmInterfaceException occured {}",e);
+        } /**catch (InterruptedException e) {
+         // TODO Auto-generated catch block
+         } catch (ExecutionException e) {
+         // TODO Auto-generated catch block
+         }**/
         return false;
     }
 
@@ -417,60 +512,82 @@ public class OlmPowerServiceImpl implements OlmPowerService {
      *            reference to list of RoadmLinks
      * @return map with list of spans with their spanloss value
      */
-    private Map<LinkId, BigDecimal> getLinkSpanloss(List<Link> roadmLinks) {
+    private Map<LinkId, BigDecimal> getLinkSpanloss(List<RoadmLinks> roadmLinks) {
         Map<LinkId, BigDecimal> map = new HashMap<LinkId, BigDecimal>();
         LOG.info("Executing GetLinkSpanLoss");
         BigDecimal spanLoss = new BigDecimal(0);
-        for (Link link : roadmLinks) {
-            String sourceNodeId = link.getSource().getSourceNode().getValue();
-            String sourceTpId = link.getSource().getSourceTp().toString();
-            String destNodeId = link.getDestination().getDestNode().getValue();
-            String destTpId = link.getDestination().getDestTp().toString();
+        for (RoadmLinks link : roadmLinks) {
+            String sourceNodeId = link.getSrcNodeId().toString();
+            String sourceTpId = link.getSrcTpId();
+            String destNodeId = link.getDestNodeId().toString();
+            String destTpId = link.getDestTpid();
             OtsPmHolder srcOtsPmHoler = getPmMeasurements(sourceNodeId, sourceTpId, "OpticalPowerOutput");
             OtsPmHolder destOtsPmHoler = getPmMeasurements(destNodeId, destTpId, "OpticalPowerInput");
             spanLoss = new BigDecimal(srcOtsPmHoler.getOtsParameterVal() - destOtsPmHoler.getOtsParameterVal())
                 .setScale(0, RoundingMode.HALF_UP);
-            LOG.info("Spanloss Calculated as :" + spanLoss + "=" + srcOtsPmHoler.getOtsParameterVal() + "-"
-                + destOtsPmHoler.getOtsParameterVal());
-            if ((spanLoss.doubleValue() < 28) && (spanLoss.doubleValue() > 0)) {
-                if (!setSpanLoss(sourceNodeId, srcOtsPmHoler.getOtsInterfaceName(), spanLoss, "TX")) {
-                    LOG.info("Setting spanLoss failed for " + sourceNodeId);
-                    return null;
-                }
-                if (!setSpanLoss(destNodeId, destOtsPmHoler.getOtsInterfaceName(), spanLoss, "RX")) {
-                    LOG.info("Setting spanLoss failed for " + destNodeId);
-                    return null;
-                }
-                map.put(link.getLinkId(), spanLoss);
+            LOG.info("Spanloss Calculated as :{}={}-{}",
+                spanLoss, srcOtsPmHoler.getOtsParameterVal(), destOtsPmHoler.getOtsParameterVal());
+            if (spanLoss.doubleValue() > 28) {
+                LOG.warn("Span Loss is out of range of OpenROADM specifications");
             }
+            if (!setSpanLoss(sourceNodeId, srcOtsPmHoler.getOtsInterfaceName(), spanLoss, "TX")) {
+                LOG.info("Setting spanLoss failed for {}", sourceNodeId);
+                return null;
+            }
+            if (!setSpanLoss(destNodeId, destOtsPmHoler.getOtsInterfaceName(), spanLoss, "RX")) {
+                LOG.info("Setting spanLoss failed for {}", destNodeId);
+                return null;
+            }
+            map.put(link.getLinkId(), spanLoss);
         }
         return map;
     }
 
     private String getRealNodeId(String mappedNodeId) {
         KeyedInstanceIdentifier<Node, NodeKey> mappedNodeII =
-                InstanceIdentifiers.OVERLAY_NETWORK_II.child(Node.class, new NodeKey(new NodeId(mappedNodeId)));
-        com.google.common.base.Optional<Node> realNode;
-        try (ReadOnlyTransaction readOnlyTransaction = this.dataBroker.newReadOnlyTransaction()) {
+            InstanceIdentifiers.OVERLAY_NETWORK_II.child(Node.class, new NodeKey(new NodeId(mappedNodeId)));
+        Optional<Node> realNode;
+        try (ReadTransaction readOnlyTransaction = this.dataBroker.newReadOnlyTransaction()) {
             realNode = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, mappedNodeII).get();
         } catch (InterruptedException | ExecutionException e) {
             LOG.error(e.getMessage(), e);
             throw new IllegalStateException(e);
         }
         if (!realNode.isPresent() || (realNode.get().getSupportingNode() == null)) {
+            LOG.error("supporting node is null");
             throw new IllegalArgumentException(
-                    String.format("Could not find node %s, or supporting node is not present", mappedNodeId));
+                String.format("Could not find node %s, or supporting node is not present", mappedNodeId));
         }
         List<SupportingNode> collect = realNode.get().getSupportingNode().stream()
-                .filter(node -> (node.getNetworkRef() != null)
-                        && NetworkUtils.UNDERLAY_NETWORK_ID.equals(node.getNetworkRef().getValue())
-                        && (node.getNodeRef() != null) && !Strings.isNullOrEmpty(node.getNodeRef().getValue()))
-                .collect(Collectors.toList());
+            .filter(node -> (node.getNetworkRef() != null)
+                && NetworkUtils.UNDERLAY_NETWORK_ID.equals(node.getNetworkRef().getValue())
+                && (node.getNodeRef() != null) && !Strings.isNullOrEmpty(node.getNodeRef().getValue()))
+            .collect(Collectors.toList());
         if (collect.isEmpty() || (collect.size() > 1)) {
             throw new IllegalArgumentException(String.format("Invalid support node count [%d] was found for node %s",
-                    collect.size(), mappedNodeId));
+                collect.size(), mappedNodeId));
+
         }
+        LOG.info("getRealNodeId - return {}", collect.iterator().next().getNodeRef().getValue());
         return collect.iterator().next().getNodeRef().getValue();
     }
 
+    private Link getNetworkLinkById(LinkId linkId) {
+        NetworkKey overlayTopologyKey = new NetworkKey(new NetworkId(NetworkUtils.OVERLAY_NETWORK_ID));
+        InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Networks.class)
+            .child(Network.class, overlayTopologyKey)
+            .augmentation(Network1.class).child(Link.class, new LinkKey(linkId))
+            .build();
+        Optional<Link> linkOptional;
+        try (ReadTransaction rtx = dataBroker.newReadOnlyTransaction()) {
+            //TODO change to constant from Timeouts class when it will be merged.
+            linkOptional = rtx.read(LogicalDatastoreType.CONFIGURATION, linkIID).get(Timeouts.DATASTORE_READ,
+                TimeUnit.MILLISECONDS);
+            return linkOptional.get();
+        } catch (InterruptedException | ExecutionException | TimeoutException e) {
+            LOG.warn("Read of {} topology failed", NetworkUtils.OVERLAY_NETWORK_ID);
+            return null;
+        }
+    }
+
 }