Use constants for PortMapping log messages Step 2
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / PortMappingVersion710.java
1 /*
2  * Copyright © 2020 AT&T, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.transportpce.common.mapping;
10
11 import com.google.common.util.concurrent.FluentFuture;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Comparator;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Locale;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Optional;
22 import java.util.concurrent.ExecutionException;
23 import java.util.stream.Collectors;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.mdsal.binding.api.DataBroker;
26 import org.opendaylight.mdsal.binding.api.ReadTransaction;
27 import org.opendaylight.mdsal.binding.api.WriteTransaction;
28 import org.opendaylight.mdsal.common.api.CommitInfo;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.transportpce.common.StringConstants;
31 import org.opendaylight.transportpce.common.Timeouts;
32 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
33 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
34 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
35 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.Network;
36 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.NetworkBuilder;
37 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.OpenroadmNodeVersion;
38 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegree;
39 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegreeBuilder;
40 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.cp.to.degree.CpToDegreeKey;
41 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.Mapping;
42 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.MappingBuilder;
43 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mapping.MappingKey;
44 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilities;
45 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilitiesBuilder;
46 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mc.capabilities.McCapabilitiesKey;
47 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.mpdr.restrictions.grp.MpdrRestrictionsBuilder;
48 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.Nodes;
49 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesBuilder;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.NodesKey;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfo;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.network.nodes.NodeInfoBuilder;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcp;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcpBuilder;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.SwitchingPoolLcpKey;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingList;
57 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingListBuilder;
58 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev210426.switching.pool.lcp.switching.pool.lcp.NonBlockingListKey;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.alarm.pm.types.rev191129.Direction;
60 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.optical.channel.types.rev200529.FrequencyGHz;
61 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.CircuitPack;
62 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.Ports;
63 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.pack.PortsKey;
64 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacks;
65 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.circuit.packs.CircuitPacksKey;
66 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.degree.ConnectionPorts;
67 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.Interface;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.interfaces.grp.InterfaceKey;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.OrgOpenroadmDevice;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.ConnectionMap;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Degree;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.DegreeKey;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Info;
74 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.McCapabilityProfile;
75 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.McCapabilityProfileKey;
76 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.MuxpProfile;
77 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.MuxpProfileKey;
78 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.OduSwitchingPools;
79 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Protocols;
80 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.SharedRiskGroup;
81 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.SharedRiskGroupKey;
82 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.Xponder;
83 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.connection.map.Destination;
84 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org.openroadm.device.odu.switching.pools.non.blocking.list.PortList;
85 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.port.Interfaces;
86 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.xponder.XpdrPort;
87 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.NodeTypes;
88 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.PortQual;
89 import org.opendaylight.yang.gen.v1.http.org.openroadm.device.types.rev191129.XpdrNodeTypes;
90 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.InterfaceType;
91 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OpenROADMOpticalMultiplex;
92 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OpticalTransport;
93 import org.opendaylight.yang.gen.v1.http.org.openroadm.interfaces.rev191129.OtnOdu;
94 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.Protocols1;
95 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.lldp.container.Lldp;
96 import org.opendaylight.yang.gen.v1.http.org.openroadm.lldp.rev200529.lldp.container.lldp.PortConfig;
97 import org.opendaylight.yang.gen.v1.http.org.openroadm.otn.common.types.rev200327.OpucnTribSlotDef;
98 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.Ports1;
99 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.port.capability.grp.port.capabilities.SupportedInterfaceCapability;
100 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.port.capability.grp.port.capabilities.SupportedInterfaceCapabilityKey;
101 import org.opendaylight.yang.gen.v1.http.org.openroadm.port.capability.rev200529.port.capability.grp.port.capabilities.supported._interface.capability.otn.capability.MpdrClientRestriction;
102 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
103 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
104 import org.opendaylight.yangtools.yang.common.Uint16;
105 import org.opendaylight.yangtools.yang.common.Uint32;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
108
109
110 // FIXME: many common pieces of code between PortMapping Versions 121 and 221 and 710
111 // some mutualization would be helpful
112 @SuppressWarnings("CPD-START")
113 public class PortMappingVersion710 {
114
115     private static final Logger LOG = LoggerFactory.getLogger(PortMappingVersion710.class);
116     private static final Map<Direction, String> SUFFIX;
117
118     private final DataBroker dataBroker;
119     private final DeviceTransactionManager deviceTransactionManager;
120     private final OpenRoadmInterfaces openRoadmInterfaces;
121
122     static {
123         SUFFIX =  Map.of(
124             Direction.Tx, "TX",
125             Direction.Rx, "RX",
126             Direction.Bidirectional, "TXRX");
127     }
128
129     public PortMappingVersion710(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
130             OpenRoadmInterfaces openRoadmInterfaces) {
131         this.dataBroker = dataBroker;
132         this.deviceTransactionManager = deviceTransactionManager;
133         this.openRoadmInterfaces = openRoadmInterfaces;
134     }
135
136     public boolean createMappingData(String nodeId) {
137         LOG.info(PortMappingUtils.CREATE_MAPPING_DATA_LOGMSG, nodeId, "7.1");
138         List<Mapping> portMapList = new ArrayList<>();
139         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = new HashMap<>();
140         InstanceIdentifier<Info> infoIID = InstanceIdentifier.create(OrgOpenroadmDevice.class).child(Info.class);
141         Optional<Info> deviceInfoOptional = this.deviceTransactionManager.getDataFromDevice(
142                 nodeId, LogicalDatastoreType.OPERATIONAL, infoIID,
143                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
144         if (deviceInfoOptional.isEmpty()) {
145             LOG.warn(PortMappingUtils.DEVICE_HAS_LOGMSG, nodeId, "no info", "subtree");
146             return false;
147         }
148         Info deviceInfo = deviceInfoOptional.get();
149         NodeInfo nodeInfo = createNodeInfo(deviceInfo);
150         if (nodeInfo == null) {
151             return false;
152         }
153         postPortMapping(nodeId, nodeInfo, null, null, null, null);
154
155         switch (deviceInfo.getNodeType()) {
156
157             case Rdm:
158                 // Get TTP port mapping
159                 if (!createTtpPortMapping(nodeId, deviceInfo, portMapList)) {
160                     // return false if mapping creation for TTP's failed
161                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "TTP's");
162                     return false;
163                 }
164
165                 // Get PP port mapping
166                 if (!createPpPortMapping(nodeId, deviceInfo, portMapList)) {
167                     // return false if mapping creation for PP's failed
168                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "PP's");
169                     return false;
170                 }
171                 // Get MC capabilities
172                 if (!createMcCapabilitiesList(nodeId, deviceInfo, mcCapabilities)) {
173                     // return false if MC capabilites failed
174                     LOG.warn(PortMappingUtils.UNABLE_MC_CAPA_LOGMSG, nodeId);
175                     return false;
176                 }
177                 break;
178             case Xpdr:
179                 if (!createXpdrPortMapping(nodeId, portMapList)) {
180                     LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "create", "Xponder");
181                     return false;
182                 }
183                 // In the case of 7.1 models, even XPDR advertizes mc-capabilities,
184                 // hence we need to populate this information into the port-mapping data
185                 // Get MC capabilities
186                 if (!createMcCapabilitiesList(nodeId, deviceInfo, mcCapabilities)) {
187                     // return false if MC capabilites failed
188                     LOG.warn(PortMappingUtils.UNABLE_MC_CAPA_LOGMSG, nodeId);
189                     return false;
190                 }
191                 break;
192             default:
193                 LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
194                     nodeId, "create", deviceInfo.getNodeType() + " - unknown nodetype");
195                 break;
196
197         }
198         return postPortMapping(nodeId, nodeInfo, portMapList, null, null, mcCapabilities);
199     }
200
201     public boolean updateMapping(String nodeId, Mapping oldMapping) {
202         if (nodeId == null) {
203             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, "node id null" , "update", "a null value");
204             return false;
205         }
206         if (oldMapping == null) {
207             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "update", "a null value");
208             return false;
209         }
210         InstanceIdentifier<Ports> portId = InstanceIdentifier.create(OrgOpenroadmDevice.class)
211             .child(CircuitPacks.class, new CircuitPacksKey(oldMapping.getSupportingCircuitPackName()))
212             .child(Ports.class, new PortsKey(oldMapping.getSupportingPort()));
213         try {
214             Ports port = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
215                 portId, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
216             Mapping newMapping = updateMappingObject(nodeId, port, oldMapping);
217             LOG.debug("{} : Updating old mapping Data {} for {} by new mapping data {}",
218                 nodeId, oldMapping, oldMapping.getLogicalConnectionPoint(), newMapping);
219             final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
220             InstanceIdentifier<Mapping> mapIID = InstanceIdentifier.create(Network.class)
221                 .child(Nodes.class, new NodesKey(nodeId))
222                 .child(Mapping.class, new MappingKey(oldMapping.getLogicalConnectionPoint()));
223             writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, mapIID, newMapping);
224             FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
225             commit.get();
226             return true;
227         } catch (InterruptedException | ExecutionException e) {
228             LOG.error(PortMappingUtils.UNABLE_MAPPING_LOGMSG,
229                 nodeId, "update", oldMapping.getLogicalConnectionPoint(), e);
230             return false;
231         }
232     }
233
234     public boolean updatePortMappingWithOduSwitchingPools(String nodeId, InstanceIdentifier<OduSwitchingPools> ospIID,
235             Map<Uint16, List<InstanceIdentifier<PortList>>> nbliidMap) {
236
237         KeyedInstanceIdentifier<Nodes, NodesKey> portMappingNodeIID = InstanceIdentifier.create(Network.class)
238             .child(Nodes.class, new NodesKey(nodeId));
239         Nodes portmappingNode = null;
240         try (ReadTransaction readTx = this.dataBroker.newReadOnlyTransaction()) {
241             portmappingNode = readTx.read(LogicalDatastoreType.CONFIGURATION, portMappingNodeIID).get().get();
242         } catch (InterruptedException | ExecutionException ex) {
243             LOG.error("Unable to read the port-mapping for nodeId {}", nodeId, ex);
244         }
245         if (portmappingNode == null) {
246             return false;
247         }
248         Map<MappingKey, Mapping> mappings = portmappingNode.nonnullMapping();
249
250         OduSwitchingPools osp = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
251             ospIID, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
252         Uint16 ospNumber = osp.getSwitchingPoolNumber();
253         Map<SwitchingPoolLcpKey, SwitchingPoolLcp> splMap =
254             new HashMap<SwitchingPoolLcpKey, SwitchingPoolLcp>(portmappingNode.nonnullSwitchingPoolLcp());
255         SwitchingPoolLcpBuilder splBldr = splMap.containsKey(new SwitchingPoolLcpKey(ospNumber))
256             ? new SwitchingPoolLcpBuilder(splMap.get(new SwitchingPoolLcpKey(ospNumber)))
257             : new SwitchingPoolLcpBuilder().setSwitchingPoolNumber(ospNumber)
258                 .setSwitchingPoolType(osp.getSwitchingPoolType());
259         Map<NonBlockingListKey, NonBlockingList> nblMap = new HashMap<>();
260         for (Entry<Uint16, List<InstanceIdentifier<PortList>>> entry : nbliidMap.entrySet()) {
261             Uint32 interconnectBw = osp.getNonBlockingList().get(new
262                     org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org
263                     .openroadm.device.odu.switching.pools.NonBlockingListKey(entry.getKey()))
264                 .getInterconnectBandwidth();
265             NonBlockingList nbl = createNonBlockingList(splBldr, interconnectBw, entry, mappings, nodeId);
266             if (nbl == null) {
267                 return false;
268             }
269             nblMap.put(nbl.key(), nbl);
270         }
271         SwitchingPoolLcp switchingPoolLcp = splBldr
272             .setNonBlockingList(nblMap)
273             .build();
274         splMap.put(switchingPoolLcp.key(), switchingPoolLcp);
275         List<SwitchingPoolLcp> switchingPoolList = new ArrayList<>(splMap.values());
276         postPortMapping(nodeId, null, null, null, switchingPoolList, null);
277         return true;
278     }
279
280     private NonBlockingList createNonBlockingList(SwitchingPoolLcpBuilder splBldr, Uint32 interconnectBw,
281             Entry<Uint16, List<InstanceIdentifier<PortList>>> entry, Map<MappingKey, Mapping> mappings, String nodeId) {
282         NonBlockingListBuilder nblBldr;
283         if (splBldr.getNonBlockingList() != null
284             && splBldr.getNonBlockingList().containsKey(new NonBlockingListKey(entry.getKey()))) {
285             nblBldr = new NonBlockingListBuilder(splBldr.getNonBlockingList()
286                 .get(new NonBlockingListKey(entry.getKey())));
287         } else {
288             nblBldr = new NonBlockingListBuilder()
289                 .setNblNumber(entry.getKey())
290                 .setInterconnectBandwidth(interconnectBw);
291         }
292         List<String> lcpList = nblBldr.getLcpList() != null ? nblBldr.getLcpList() : new ArrayList<>();
293         for (InstanceIdentifier<PortList> id : entry.getValue()) {
294             PortList portList = deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL,
295                 id, Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT).get();
296             String circuitPackName = portList.getCircuitPackName();
297             String portName = portList.getPortName();
298             String lcp = getLcpFromCpAndPort(mappings, circuitPackName, portName);
299             if (lcp != null && !lcpList.contains(lcp)) {
300                 lcpList.add(lcp);
301             } else {
302                 return null;
303             }
304         }
305         nblBldr.setLcpList(lcpList);
306         return nblBldr.build();
307     }
308
309     private boolean createXpdrPortMapping(String nodeId, List<Mapping> portMapList) {
310         // Creating for Xponder Line and Client Ports
311         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
312         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(nodeId,
313             LogicalDatastoreType.OPERATIONAL, deviceIID,
314             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
315         if (!deviceObject.isPresent()) {
316             LOG.error(PortMappingUtils.CANNOT_GET_DEV_CONF_LOGMSG, nodeId);
317             return false;
318         }
319         OrgOpenroadmDevice device = deviceObject.get();
320         if (device.getCircuitPacks() == null) {
321             LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG, nodeId, "found");
322             return false;
323         }
324
325         Map<String, String> lcpMap = new HashMap<>();
326         Map<String, Mapping> mappingMap = new HashMap<>();
327         List<CircuitPacks> circuitPackList = new ArrayList<>(device.nonnullCircuitPacks().values());
328         circuitPackList.sort(Comparator.comparing(CircuitPack::getCircuitPackName));
329         if (device.getXponder() == null) {
330             LOG.warn("{} : configuration does not contain a list of Xponders", nodeId);
331             // Variables to keep track of number of line ports and client ports
332             int line = 1;
333             int client = 1;
334             // TODO the treatment here inside the 2 nested for-loop is very similar to the one
335             //     when device.getXponder() != null. Some code mutualization must be considered.
336             for (CircuitPacks cp : circuitPackList) {
337                 String circuitPackName = cp.getCircuitPackName();
338                 if (cp.getPorts() == null) {
339                     LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, "found", circuitPackName);
340                     continue;
341                 }
342                 List<Ports> portList = new ArrayList<>(cp.nonnullPorts().values());
343                 portList.sort(Comparator.comparing(Ports::getPortName));
344                 for (Ports port : portList) {
345                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
346                         1, null, circuitPackName, port,
347                         circuitPackList, lcpMap, mappingMap);
348                     line = counters[0];
349                     client = counters[1];
350                 }
351             }
352         } else {
353             LOG.info("{} : configuration contains a list of xponders", nodeId);
354             for (Xponder xponder : deviceObject.get().nonnullXponder().values()) {
355                 // Variables to keep track of number of line ports and client ports
356                 int line = 1;
357                 int client = 1;
358                 Integer xponderNb = xponder.getXpdrNumber().toJava();
359                 XpdrNodeTypes xponderType = xponder.getXpdrType();
360                 for (XpdrPort xpdrPort : xponder.nonnullXpdrPort().values().stream()
361                         .sorted((xp1, xp2) -> xp1.getIndex().compareTo(xp2.getIndex())).collect(Collectors.toList())) {
362                     String circuitPackName = xpdrPort.getCircuitPackName();
363                     String portName = xpdrPort.getPortName();
364                     // If there xponder-subtree has missing circuit-packs or ports,
365                     // This gives a null-pointer expection,
366                     if (device.nonnullCircuitPacks().values().stream()
367                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
368                             .findFirst().isEmpty()) {
369                         LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
370                             nodeId, circuitPackName);
371                         continue;
372                     }
373                     if (device.nonnullCircuitPacks().values().stream()
374                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
375                             .findFirst().get().nonnullPorts().values().stream()
376                             .filter(p -> p.getPortName().equals(portName))
377                             .findFirst().isEmpty()) {
378                         LOG.warn(PortMappingUtils.NO_ASSOC_FOUND_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
379                             nodeId, portName, circuitPackName, "in the device");
380                         continue;
381                     }
382                     Ports port = device.nonnullCircuitPacks().values().stream()
383                             .filter(cp -> cp.getCircuitPackName().equals(circuitPackName))
384                             .findFirst().get().nonnullPorts().values().stream()
385                             .filter(p -> p.getPortName().equals(portName))
386                             .findFirst().get();
387                     int[] counters = fillXpdrLcpsMaps(line, client, nodeId,
388                         xponderNb, xponderType, circuitPackName, port,
389                         circuitPackList, lcpMap, mappingMap);
390                     line = counters[0];
391                     client = counters[1];
392                 }
393             }
394         }
395
396         if (device.getConnectionMap() == null) {
397             LOG.warn("{} : No connection-map inside device configuration", nodeId);
398         } else {
399             Collection<ConnectionMap> connectionMap = deviceObject.get().nonnullConnectionMap().values();
400             for (ConnectionMap cm : connectionMap) {
401                 String skey = cm.getSource().getCircuitPackName() + "+" + cm.getSource().getPortName();
402                 String slcp = lcpMap.containsKey(skey) ? lcpMap.get(skey) : null;
403                 Destination destination0 = cm.nonnullDestination().values().iterator().next();
404                 String dkey = destination0.getCircuitPackName() + "+" + destination0.getPortName();
405                 if (slcp == null) {
406                     LOG.error("{} : Error in connection-map analysis for source {} and destination (CP+port) {}",
407                         nodeId, skey, dkey);
408                     continue;
409                 }
410                 String dlcp = lcpMap.containsKey(dkey) ? lcpMap.get(dkey) : null;
411                 Mapping mapping = mappingMap.get(slcp);
412                 mappingMap.remove(slcp);
413                 portMapList.add(createXpdrMappingObject(nodeId, null, null, null, null, mapping, dlcp, null));
414             }
415         }
416
417         if (device.getOduSwitchingPools() != null) {
418             Collection<OduSwitchingPools> oduSwithcingPools = device.nonnullOduSwitchingPools().values();
419             List<SwitchingPoolLcp> switchingPoolList = new ArrayList<>();
420             for (OduSwitchingPools odp : oduSwithcingPools) {
421                 Map<NonBlockingListKey,NonBlockingList> nbMap = new HashMap<>();
422                 for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.org.openroadm.device.container.org
423                     .openroadm.device.odu.switching.pools.NonBlockingList nbl : odp.nonnullNonBlockingList().values()) {
424                     if (nbl.getPortList() == null) {
425                         continue;
426                     }
427                     List<String> lcpList = new ArrayList<>();
428                     for (PortList item : nbl.nonnullPortList().values()) {
429                         String key = item.getCircuitPackName() + "+" + item.getPortName();
430                         if (!lcpMap.containsKey(key)) {
431                             LOG.error(PortMappingUtils.NO_ASSOC_FOUND_LOGMSG,
432                                 nodeId, item.getPortName(), item.getCircuitPackName(), "to a logical connection point");
433                             continue;
434                         }
435                         lcpList.add(lcpMap.get(key));
436                     }
437                     NonBlockingList nonBlockingList = new NonBlockingListBuilder()
438                         .setNblNumber(nbl.getNblNumber())
439                         .setInterconnectBandwidth(nbl.getInterconnectBandwidth())
440                         .setInterconnectBandwidthUnit(nbl.getInterconnectBandwidthUnit())
441                         .setLcpList(lcpList)
442                         .build();
443                     nbMap.put(nonBlockingList.key(), nonBlockingList);
444                 }
445                 SwitchingPoolLcp splBldr = new SwitchingPoolLcpBuilder()
446                     .setSwitchingPoolNumber(odp.getSwitchingPoolNumber())
447                     .setSwitchingPoolType(odp.getSwitchingPoolType())
448                     //TODO differs from 2.2.1 SwitchingPoolTypes.forValue(odp.getSwitchingPoolType().getIntValue()
449                     .setNonBlockingList(nbMap)
450                     .build();
451                 switchingPoolList.add(splBldr);
452             }
453             postPortMapping(nodeId, null, null, null, switchingPoolList, null);
454         }
455
456         if (!mappingMap.isEmpty()) {
457             mappingMap.forEach((k,v) -> portMapList.add(v));
458         }
459         return true;
460     }
461
462     private boolean checkPartnerPortNotNull(Ports port) {
463         return (port.getPartnerPort() != null
464             && port.getPartnerPort().getCircuitPackName() != null
465             && port.getPartnerPort().getPortName() != null);
466     }
467
468     private boolean checkPartnerPortNoDir(String circuitPackName, Ports port1, Ports port2) {
469         return (checkPartnerPortNotNull(port2)
470             && port2.getPartnerPort().getCircuitPackName().equals(circuitPackName)
471             && port2.getPartnerPort().getPortName().equals(port1.getPortName()));
472     }
473
474     private boolean checkPartnerPort(String circuitPackName, Ports port1, Ports port2) {
475         return (checkPartnerPortNoDir(circuitPackName, port1, port2)
476             && ((Direction.Rx.getIntValue() == port1.getPortDirection().getIntValue()
477                     && Direction.Tx.getIntValue() == port2.getPortDirection().getIntValue())
478                 ||
479                 (Direction.Tx.getIntValue() == port1.getPortDirection().getIntValue()
480                     && Direction.Rx.getIntValue() == port2.getPortDirection().getIntValue())));
481     }
482
483
484     private HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg
485             .CircuitPacks>> getSrgCps(String deviceId, Info ordmInfo) {
486         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg
487             .CircuitPacks>> cpPerSrg = new HashMap<>();
488         // Get value for max Srg from info subtree, required for iteration
489         // if not present assume to be 20 (temporary)
490         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
491         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
492             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks> srgCps
493                 = new ArrayList<>();
494             LOG.debug("{} : Getting Circuitpacks for Srg Number {}", deviceId, srgCounter);
495             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
496                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
497             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
498                 LogicalDatastoreType.OPERATIONAL, srgIID,
499                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
500             if (ordmSrgObject.isPresent()) {
501                 srgCps.addAll(ordmSrgObject.get().nonnullCircuitPacks().values());
502                 cpPerSrg.put(ordmSrgObject.get().getSrgNumber().toJava(), srgCps);
503             }
504         }
505         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG, deviceId, cpPerSrg.size(), "SRG");
506         return cpPerSrg;
507     }
508
509     private boolean createPpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
510         // Creating mapping data for SRG's PP
511         HashMap<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks>> srgCps
512             = getSrgCps(nodeId, deviceInfo);
513         for (Entry<Integer, List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks>>
514                 srgCpEntry : srgCps.entrySet()) {
515             List<org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks> cpList =
516                 srgCps.get(srgCpEntry.getKey());
517             List<String> keys = new ArrayList<>();
518             for (org.opendaylight.yang.gen.v1.http.org.openroadm.device.rev200529.srg.CircuitPacks cp : cpList) {
519                 String circuitPackName = cp.getCircuitPackName();
520                 InstanceIdentifier<CircuitPacks> cpIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
521                     .child(CircuitPacks.class, new CircuitPacksKey(circuitPackName));
522                 Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
523                     LogicalDatastoreType.OPERATIONAL, cpIID,
524                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
525
526                 if (circuitPackObject.isEmpty()) {
527                     LOG.warn(PortMappingUtils.MISSING_CP_LOGMSG + PortMappingUtils.PORTMAPPING_IGNORE_LOGMSG,
528                         nodeId, circuitPackName);
529                     continue;
530                 }
531                 if (circuitPackObject.get().getPorts() == null) {
532                     LOG.warn(PortMappingUtils.NO_PORT_ON_CP_LOGMSG, nodeId, "found", circuitPackName);
533                     continue;
534                 }
535
536                 List<Ports> portList = new ArrayList<>(circuitPackObject.get().nonnullPorts().values());
537                 Collections.sort(portList, new SortPort710ByName());
538                 int portIndex = 1;
539                 for (Ports port : portList) {
540                     String currentKey = circuitPackName + "-" + port.getPortName();
541                     if (port.getPortQual() == null) {
542                         continue;
543                     }
544
545                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
546                         LOG.debug("{} : port {} on {} is not roadm-external" + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
547                             nodeId, port.getPortName(), circuitPackName);
548                         continue;
549                     }
550
551                     if (keys.contains(currentKey)) {
552                         LOG.debug("{} : port {} on {} has already been handled" + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
553                             nodeId, port.getPortName(), circuitPackName);
554                         continue;
555                     }
556
557                     switch (port.getPortDirection()) {
558
559                         case Bidirectional:
560                             String lcp = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
561                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
562                                 nodeId, port.getPortName(), circuitPackName, lcp);
563                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp));
564                             portIndex++;
565                             keys.add(currentKey);
566                             break;
567
568                         case Rx:
569                         case Tx:
570                             if (!checkPartnerPortNotNull(port)) {
571                                 LOG.info(PortMappingUtils.NO_VALID_PARTNERPORT_UNIDIR_LOGMSG
572                                         + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
573                                     nodeId, port.getPortName(), circuitPackName);
574                                 continue;
575                             }
576
577                             String lcp1 = createLogicalConnectionPort(port, srgCpEntry.getKey(), portIndex);
578                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
579                                 nodeId, port.getPortName(), circuitPackName, lcp1);
580                             InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
581                                 .child(CircuitPacks.class,
582                                     new CircuitPacksKey(port.getPartnerPort().getCircuitPackName()))
583                                 .child(Ports.class, new PortsKey(port.getPartnerPort().getPortName()));
584                             Optional<Ports> port2Object = this.deviceTransactionManager
585                                 .getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, port2ID,
586                                     Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
587                             if (port2Object.isEmpty()
588                                 || port2Object.get().getPortQual().getIntValue()
589                                     != PortQual.RoadmExternal.getIntValue()) {
590                                 LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG
591                                         + PortMappingUtils.PARTNERPORT_GET_ERROR_LOGMSG,
592                                     nodeId, port.getPartnerPort().getPortName(),
593                                     port.getPartnerPort().getCircuitPackName(),
594                                     port.getPortName(), circuitPackName);
595                                 continue;
596                             }
597
598                             Ports port2 = port2Object.get();
599                             if (!checkPartnerPort(circuitPackName, port, port2)) {
600                                 LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG
601                                         + PortMappingUtils.PARTNERPORT_CONF_ERROR_LOGMSG,
602                                     nodeId, port2.getPortName(), port.getPartnerPort().getCircuitPackName(),
603                                     port.getPortName(), circuitPackName);
604                                 portIndex++;
605                                 continue;
606                             }
607                             String lcp2 = createLogicalConnectionPort(port2, srgCpEntry.getKey(),portIndex);
608                             LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
609                                 nodeId, port2.getPortName(), circuitPackName, lcp2);
610                             portMapList.add(createMappingObject(nodeId, port, circuitPackName, lcp1));
611                             portMapList.add(
612                                 createMappingObject(nodeId ,port2, port.getPartnerPort().getCircuitPackName(), lcp2));
613                             portIndex++;
614                             keys.add(currentKey);
615                             keys.add(port.getPartnerPort().getCircuitPackName() + "-" + port2.getPortName());
616                             break;
617
618                         default:
619                             LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG + PortMappingUtils.CANNOT_AS_LCP_LOGMSG,
620                                     nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
621
622                     }
623                 }
624             }
625         }
626         return true;
627     }
628
629     private String createLogicalConnectionPort(Ports port, int index, int portIndex) {
630         if (SUFFIX.containsKey(port.getPortDirection())) {
631             return String.join("-", "SRG" + index, "PP" + portIndex, SUFFIX.get(port.getPortDirection()));
632         }
633         LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
634             "createLogicalConnectionPort", port, "SRG" + index + "-PP" + portIndex, port.getPortDirection());
635         return null;
636     }
637
638     private Map<McCapabilityProfileKey, McCapabilityProfile> getMcCapabilityProfiles(String deviceId, Info ordmInfo) {
639         Map<McCapabilityProfileKey, McCapabilityProfile>  mcCapabilityProfiles = new HashMap<>();
640         InstanceIdentifier<OrgOpenroadmDevice> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class);
641         Optional<OrgOpenroadmDevice> deviceObject = deviceTransactionManager.getDataFromDevice(deviceId,
642             LogicalDatastoreType.OPERATIONAL, deviceIID,
643             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
644         OrgOpenroadmDevice device = null;
645         if (!deviceObject.isPresent()) {
646             LOG.error(PortMappingUtils.CANNOT_GET_DEV_CONF_LOGMSG, deviceId);
647             LOG.warn("MC-capabilities profile will be empty for node {}", deviceId);
648             return mcCapabilityProfiles;
649         }
650         device = deviceObject.get();
651         mcCapabilityProfiles = device.getMcCapabilityProfile();
652         return mcCapabilityProfiles;
653     }
654
655     private Map<Integer, Degree> getDegreesMap(String deviceId, Info ordmInfo) {
656         Map<Integer, Degree> degrees = new HashMap<>();
657
658         // Get value for max degree from info subtree, required for iteration
659         // if not present assume to be 20 (temporary)
660         Integer maxDegree = ordmInfo.getMaxDegrees() == null ? 20 : ordmInfo.getMaxDegrees().toJava();
661
662         for (int degreeCounter = 1; degreeCounter <= maxDegree; degreeCounter++) {
663             LOG.debug("{} : Getting Connection ports for Degree Number {}", deviceId, degreeCounter);
664             InstanceIdentifier<Degree> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
665                 .child(Degree.class, new DegreeKey(Uint16.valueOf(degreeCounter)));
666             Optional<Degree> ordmDegreeObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
667                 LogicalDatastoreType.OPERATIONAL, deviceIID,
668                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
669             if (ordmDegreeObject.isPresent()) {
670                 degrees.put(degreeCounter, ordmDegreeObject.get());
671             }
672         }
673         LOG.info(PortMappingUtils.DEVICE_HAS_LOGMSG,
674             deviceId, degrees.size(), degrees.size() <= 1 ? "degree" : "degrees");
675         return degrees;
676     }
677
678     private Map<Integer, List<ConnectionPorts>> getPerDegreePorts(String deviceId, Info ordmInfo) {
679         Map<Integer, List<ConnectionPorts>> conPortMap = new HashMap<>();
680         getDegreesMap(deviceId, ordmInfo).forEach(
681             (index, degree) -> conPortMap.put(index, new ArrayList<>(degree.nonnullConnectionPorts().values())));
682         return conPortMap;
683     }
684
685     private List<SharedRiskGroup> getSrgs(String deviceId, Info ordmInfo) {
686         List<SharedRiskGroup> srgs = new ArrayList<>();
687
688         // Get value for max Srg from info subtree, required for iteration
689         // if not present assume to be 20 (temporary)
690         Integer maxSrg = ordmInfo.getMaxSrgs() == null ? 20 : ordmInfo.getMaxSrgs().toJava();
691         for (int srgCounter = 1; srgCounter <= maxSrg; srgCounter++) {
692             InstanceIdentifier<SharedRiskGroup> srgIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
693                 .child(SharedRiskGroup.class, new SharedRiskGroupKey(Uint16.valueOf(srgCounter)));
694             Optional<SharedRiskGroup> ordmSrgObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
695                 LogicalDatastoreType.OPERATIONAL, srgIID,
696                 Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
697             if (ordmSrgObject.isPresent()) {
698                 srgs.add(ordmSrgObject.get());
699
700             }
701         }
702         return srgs;
703     }
704
705     private Map<String, String> getEthInterfaceList(String nodeId) {
706         LOG.info(PortMappingUtils.GETTING_ETH_LIST_LOGMSG, nodeId);
707         InstanceIdentifier<Protocols> protocoliid = InstanceIdentifier.create(OrgOpenroadmDevice.class)
708             .child(Protocols.class);
709         Optional<Protocols> protocolObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
710             LogicalDatastoreType.OPERATIONAL, protocoliid, Timeouts.DEVICE_READ_TIMEOUT,
711             Timeouts.DEVICE_READ_TIMEOUT_UNIT);
712         if (!protocolObject.isPresent() || protocolObject.get().augmentation(Protocols1.class).getLldp() == null) {
713             LOG.warn(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, PortMappingUtils.CANNOT_GET_LLDP_CONF_LOGMSG);
714             return new HashMap<>();
715         }
716         Map<String, String> cpToInterfaceMap = new HashMap<>();
717         Lldp lldp = protocolObject.get().augmentation(Protocols1.class).getLldp();
718         for (PortConfig portConfig : lldp.nonnullPortConfig().values()) {
719             if (!portConfig.getAdminStatus().equals(PortConfig.AdminStatus.Txandrx)) {
720                 continue;
721             }
722             InstanceIdentifier<Interface> interfaceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
723                 .child(Interface.class, new InterfaceKey(portConfig.getIfName()));
724             Optional<Interface> interfaceObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
725                 LogicalDatastoreType.OPERATIONAL, interfaceIID, Timeouts.DEVICE_READ_TIMEOUT,
726                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
727             if (!interfaceObject.isPresent() || (interfaceObject.get().getSupportingCircuitPackName() == null)) {
728                 continue;
729             }
730             String supportingCircuitPackName = interfaceObject.get().getSupportingCircuitPackName();
731             cpToInterfaceMap.put(supportingCircuitPackName, portConfig.getIfName());
732             InstanceIdentifier<CircuitPacks> circuitPacksIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
733                 .child(CircuitPacks.class, new CircuitPacksKey(supportingCircuitPackName));
734             Optional<CircuitPacks> circuitPackObject = this.deviceTransactionManager.getDataFromDevice(
735                 nodeId, LogicalDatastoreType.OPERATIONAL, circuitPacksIID, Timeouts.DEVICE_READ_TIMEOUT,
736                 Timeouts.DEVICE_READ_TIMEOUT_UNIT);
737             if (!circuitPackObject.isPresent() || (circuitPackObject.get().getParentCircuitPack() == null)) {
738                 continue;
739             }
740             cpToInterfaceMap.put(circuitPackObject.get().getParentCircuitPack().getCircuitPackName(),
741                 portConfig.getIfName());
742         }
743         LOG.info(PortMappingUtils.PROCESSING_DONE_LOGMSG, nodeId, " - success");
744         return cpToInterfaceMap;
745     }
746
747     private List<CpToDegree> getCpToDegreeList(Map<Integer, Degree> degrees, Map<String, String> interfaceList) {
748         List<CpToDegree> cpToDegreeList = new ArrayList<>();
749         for (Degree degree : degrees.values()) {
750             LOG.debug("Inside CP to degree list");
751             cpToDegreeList.addAll(degree.nonnullCircuitPacks().values().stream()
752                 .map(cp -> createCpToDegreeObject(cp.getCircuitPackName(),
753                     degree.getDegreeNumber().toString(), interfaceList))
754                 .collect(Collectors.toList()));
755         }
756         return cpToDegreeList;
757     }
758
759     private Map<McCapabilitiesKey, McCapabilities> getMcCapabilities(Map<Integer, Degree> degrees,
760             List<SharedRiskGroup> srgs, Info deviceInfo, String nodeId) {
761         //TODO some divergences with 2.2.1 here
762         LOG.info(PortMappingUtils.GETTING_MC_CAPA_LOGMSG , nodeId, "degrees");
763         //Get all the mc-capability profiles from the device
764         Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfiles =
765             getMcCapabilityProfiles(nodeId, deviceInfo);
766         // Add the DEG mc-capabilities
767         Map<McCapabilitiesKey, McCapabilities> mcCapabilities = createMcCapDegreeObject(degrees, mcCapabilityProfiles,
768             nodeId);
769         // Add the SRG mc-capabilities
770         LOG.info(PortMappingUtils.GETTING_MC_CAPA_LOGMSG , nodeId, "SRGs");
771         mcCapabilities.putAll(createMcCapSrgObject(srgs, mcCapabilityProfiles, nodeId));
772         return mcCapabilities;
773     }
774
775     private boolean postPortMapping(String nodeId, NodeInfo nodeInfo, List<Mapping> portMapList,
776             List<CpToDegree> cp2DegreeList, List<SwitchingPoolLcp> splList,
777             Map<McCapabilitiesKey, McCapabilities> mcCapMap) {
778         NodesBuilder nodesBldr = new NodesBuilder().withKey(new NodesKey(nodeId)).setNodeId(nodeId);
779         if (nodeInfo != null) {
780             nodesBldr.setNodeInfo(nodeInfo);
781         }
782         if (portMapList != null) {
783             Map<MappingKey, Mapping> mappingMap = new HashMap<>();
784             // No element in the list below should be null at this stage
785             for (Mapping mapping: portMapList) {
786                 mappingMap.put(mapping.key(), mapping);
787             }
788             nodesBldr.setMapping(mappingMap);
789         }
790         if (cp2DegreeList != null) {
791             Map<CpToDegreeKey, CpToDegree> cpToDegreeMap = new HashMap<>();
792             // No element in the list below should be null at this stage
793             for (CpToDegree cp2Degree: cp2DegreeList) {
794                 cpToDegreeMap.put(cp2Degree.key(), cp2Degree);
795             }
796             nodesBldr.setCpToDegree(cpToDegreeMap);
797         }
798
799         if (splList != null) {
800             Map<SwitchingPoolLcpKey,SwitchingPoolLcp> splMap = new HashMap<>();
801             // No element in the list below should be null at this stage
802             for (SwitchingPoolLcp spl: splList) {
803                 splMap.put(spl.key(), spl);
804             }
805             nodesBldr.setSwitchingPoolLcp(splMap);
806         }
807         if (mcCapMap != null) {
808             nodesBldr.setMcCapabilities(mcCapMap);
809         }
810         Map<NodesKey,Nodes> nodesList = new HashMap<>();
811         Nodes nodes = nodesBldr.build();
812         nodesList.put(nodes.key(),nodes);
813
814         Network network = new NetworkBuilder().setNodes(nodesList).build();
815
816         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
817         InstanceIdentifier<Network> nodesIID = InstanceIdentifier.builder(Network.class).build();
818         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION, nodesIID, network);
819         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
820         try {
821             commit.get();
822             return true;
823         } catch (InterruptedException | ExecutionException e) {
824             LOG.warn("{} : Failed to post {}", nodeId, network, e);
825             return false;
826         }
827     }
828
829     private CpToDegree createCpToDegreeObject(String circuitPackName, String degreeNumber,
830             Map<String, String> interfaceList) {
831         return new CpToDegreeBuilder()
832             .withKey(new CpToDegreeKey(circuitPackName))
833             .setCircuitPackName(circuitPackName)
834             .setDegreeNumber(Uint32.valueOf(degreeNumber))
835             .setInterfaceName(interfaceList.get(circuitPackName)).build();
836     }
837
838     private Map<McCapabilitiesKey, McCapabilities> createMcCapDegreeObject(Map<Integer, Degree> degrees,
839             Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfileMap, String nodeId) {
840         //TODO some divergences here with 2.2.1
841         Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap = new HashMap<>();
842         for (Degree degree : degrees.values()) {
843
844             if ((degree.getMcCapabilityProfileName() == null) || (degree.getMcCapabilityProfileName().isEmpty())) {
845                 String mcNodeName =
846                     PortMappingUtils.degreeTtpNodeName(degree.getDegreeNumber().toString(), "default-profile");
847                 LOG.warn(PortMappingUtils.NO_MC_LOGMSG, nodeId, "degree",
848                     degree.getDegreeNumber() +  " - using " + mcNodeName + " as default MC profile name");
849                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
850                     .withKey(new McCapabilitiesKey(mcNodeName))
851                     .setMcNodeName(mcNodeName);
852                 mcCapabilitiesBuilder
853                     .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
854                     .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
855                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
856                 continue;
857             }
858
859             for (String mcCapabilityProfileName : degree.getMcCapabilityProfileName()) {
860                 McCapabilityProfileKey mcKey = new McCapabilityProfileKey(mcCapabilityProfileName);
861                 McCapabilityProfile mcCapabilityProfile = mcCapabilityProfileMap.get(mcKey);
862                 String mcNodeName = PortMappingUtils.degreeTtpNodeName(degree.getDegreeNumber().toString(),
863                         mcCapabilityProfile.toString());
864                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
865                     .withKey(new McCapabilitiesKey(mcNodeName))
866                     .setMcNodeName(mcNodeName);
867                 mcCapabilitiesBuilder
868                     .setCenterFreqGranularity(mcCapabilityProfile.getCenterFreqGranularity())
869                     .setSlotWidthGranularity(mcCapabilityProfile.getSlotWidthGranularity());
870                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
871             }
872
873         }
874         return mcCapabilitiesMap;
875     }
876
877     private Map<McCapabilitiesKey, McCapabilities> createMcCapSrgObject(List<SharedRiskGroup> srgs,
878             Map<McCapabilityProfileKey, McCapabilityProfile> mcCapabilityProfileMap, String nodeId) {
879
880         Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap = new HashMap<>();
881         for (SharedRiskGroup srg : srgs) {
882
883             if ((srg.getMcCapabilityProfileName() == null) || (srg.getMcCapabilityProfileName().isEmpty())) {
884                 String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP-" + "default-profile";
885                 LOG.warn(PortMappingUtils.NO_MC_LOGMSG, nodeId, "SRG",
886                     srg.getSrgNumber() + " - using " + mcNodeName + " as default MC profile name");
887                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
888                     .withKey(new McCapabilitiesKey(mcNodeName))
889                     .setMcNodeName(mcNodeName);
890                 mcCapabilitiesBuilder
891                     .setCenterFreqGranularity(FrequencyGHz.getDefaultInstance("50"))
892                     .setSlotWidthGranularity(FrequencyGHz.getDefaultInstance("50"));
893                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
894                 continue;
895             }
896
897             for (String mcCapabilityProfileName : srg.getMcCapabilityProfileName()) {
898                 McCapabilityProfileKey mcKey = new McCapabilityProfileKey(mcCapabilityProfileName);
899                 McCapabilityProfile mcCapabilityProfile = mcCapabilityProfileMap.get(mcKey);
900                 String mcNodeName = "SRG" + srg.getSrgNumber().toString() + "-PP-" + mcCapabilityProfile;
901                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
902                     .withKey(new McCapabilitiesKey(mcNodeName))
903                     .setMcNodeName(mcNodeName);
904                 mcCapabilitiesBuilder
905                     .setCenterFreqGranularity(mcCapabilityProfile.getCenterFreqGranularity())
906                     .setSlotWidthGranularity(mcCapabilityProfile.getSlotWidthGranularity());
907                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
908             }
909         }
910         return mcCapabilitiesMap;
911     }
912
913     private Mapping createMappingObject(String nodeId, Ports port, String circuitPackName,
914             String logicalConnectionPoint) {
915         MappingBuilder mpBldr = new MappingBuilder()
916                 .withKey(new MappingKey(logicalConnectionPoint))
917                 .setLogicalConnectionPoint(logicalConnectionPoint)
918                 .setSupportingCircuitPackName(circuitPackName)
919                 .setSupportingPort(port.getPortName())
920                 .setPortDirection(port.getPortDirection().getName());
921         if (port.getAdministrativeState() != null) {
922             mpBldr.setPortAdminState(port.getAdministrativeState().name());
923         }
924         if (port.getOperationalState() != null) {
925             mpBldr.setPortOperState(port.getOperationalState().name());
926         }
927
928         if ((port.getInterfaces() == null)
929             || (!logicalConnectionPoint.contains(StringConstants.TTP_TOKEN)
930                 && !logicalConnectionPoint.contains(StringConstants.NETWORK_TOKEN))) {
931             return mpBldr.build();
932         }
933         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
934         return mpBldr.build();
935     }
936
937     private Mapping updateMappingObject(String nodeId, Ports port, Mapping oldmapping) {
938         MappingBuilder mpBldr = new MappingBuilder(oldmapping);
939         updateMappingStates(mpBldr, port, oldmapping);
940         if ((port.getInterfaces() == null)
941             || (!oldmapping.getLogicalConnectionPoint().contains(StringConstants.TTP_TOKEN)
942                 && !oldmapping.getLogicalConnectionPoint().contains(StringConstants.NETWORK_TOKEN))) {
943             return mpBldr.build();
944         }
945         // Get interfaces provisioned on the port
946         mpBldr = updateMappingInterfaces(nodeId, mpBldr, port);
947         return mpBldr.build();
948     }
949
950     private MappingBuilder updateMappingStates(MappingBuilder mpBldr, Ports port, Mapping oldmapping) {
951         if (port.getAdministrativeState() != null
952             && !port.getAdministrativeState().getName().equals(oldmapping.getPortAdminState())) {
953             mpBldr.setPortAdminState(port.getAdministrativeState().name());
954         }
955         if (port.getOperationalState() != null
956             && !port.getOperationalState().getName().equals(oldmapping.getPortOperState())) {
957             mpBldr.setPortOperState(port.getOperationalState().name());
958         }
959         return mpBldr;
960     }
961
962     private MappingBuilder updateMappingInterfaces(String nodeId, MappingBuilder mpBldr, Ports port) {
963         for (Interfaces interfaces : port.getInterfaces()) {
964             try {
965                 Optional<Interface> openRoadmInterface = this.openRoadmInterfaces.getInterface(nodeId,
966                     interfaces.getInterfaceName());
967                 if (!openRoadmInterface.isPresent()) {
968                     LOG.warn("{} : Interface {} was null!", nodeId, interfaces.getInterfaceName());
969                     continue;
970                 }
971                 LOG.debug("{} : interface get from device is {} and of type {}",
972                     nodeId, openRoadmInterface.get().getName(), openRoadmInterface.get().getType());
973                 Class<? extends InterfaceType> interfaceType
974                     = (Class<? extends InterfaceType>) openRoadmInterface.get().getType();
975                 // Check if interface type is OMS or OTS
976                 if (interfaceType.equals(OpenROADMOpticalMultiplex.class)) {
977                     mpBldr.setSupportingOms(interfaces.getInterfaceName());
978                 }
979                 if (interfaceType.equals(OpticalTransport.class)) {
980                     mpBldr.setSupportingOts(interfaces.getInterfaceName());
981                 }
982                 String interfaceName = interfaces.getInterfaceName();
983                 if (interfaceType.equals(OtnOdu.class)
984                     && (interfaceName.substring(interfaceName.lastIndexOf("-") + 1)
985                     .equals("ODU"))) {
986                     mpBldr.setSupportingOdu4(interfaces.getInterfaceName());
987                 }
988                 if ((interfaceType.equals(OtnOdu.class))
989                     && (interfaceName.substring(interfaceName.lastIndexOf("-") + 1)
990                     .equals("ODUC4"))) {
991                     mpBldr.setSupportingOduc4(interfaces.getInterfaceName());
992                 }
993
994             } catch (OpenRoadmInterfaceException ex) {
995                 LOG.warn("{} : Error while getting interface {} - ",
996                     nodeId, interfaces.getInterfaceName(), ex);
997             }
998         }
999         return mpBldr;
1000     }
1001
1002     private Mapping createXpdrMappingObject(String nodeId, Ports port, String circuitPackName,
1003             String logicalConnectionPoint, String partnerLcp, Mapping mapping, String connectionMapLcp,
1004             XpdrNodeTypes xpdrNodeType) {
1005
1006         //TODO some divergens here with 2.2.1
1007         if (mapping != null && connectionMapLcp != null) {
1008             // update existing mapping
1009             return new MappingBuilder(mapping).setConnectionMapLcp(connectionMapLcp).build();
1010         }
1011
1012         // create a new mapping
1013         String nodeIdLcp = nodeId + "-" + logicalConnectionPoint;
1014         MappingBuilder mpBldr = new MappingBuilder()
1015                 .withKey(new MappingKey(logicalConnectionPoint))
1016                 .setLogicalConnectionPoint(logicalConnectionPoint)
1017                 .setSupportingCircuitPackName(circuitPackName)
1018                 .setSupportingPort(port.getPortName())
1019                 .setPortDirection(port.getPortDirection().getName())
1020                 .setLcpHashVal(PortMappingUtils.fnv1size64(nodeIdLcp));
1021         if (port.getPortQual() != null) {
1022             mpBldr.setPortQual(port.getPortQual().getName());
1023         }
1024         if (xpdrNodeType != null) {
1025             mpBldr.setXponderType(xpdrNodeType);
1026         }
1027         if (partnerLcp != null) {
1028             mpBldr.setPartnerLcp(partnerLcp);
1029         }
1030         if (port.augmentation(Ports1.class) != null && port.augmentation(Ports1.class).getPortCapabilities() != null) {
1031             List<Class<? extends org.opendaylight.yang.gen.v1.http.org.openroadm.port.types.rev200327
1032                 .SupportedIfCapability>> supportedIntf = new ArrayList<>();
1033             Map<SupportedInterfaceCapabilityKey, SupportedInterfaceCapability> supIfCapMap = port
1034                 .augmentation(Ports1.class).getPortCapabilities().nonnullSupportedInterfaceCapability();
1035             SupportedInterfaceCapability sic1 = null;
1036             for (SupportedInterfaceCapability sic : supIfCapMap.values()) {
1037                 supportedIntf.add(sic.getIfCapType());
1038                 sic1 = sic;
1039             }
1040             if (port.getPortQual() == PortQual.SwitchClient
1041                 && !sic1.getOtnCapability().getMpdrClientRestriction().isEmpty()) {
1042                 List<MpdrClientRestriction> mpdrClientRestriction = sic1.getOtnCapability().getMpdrClientRestriction();
1043                 // Here we assume all the supported-interfaces has the support same rates, and the
1044                 // trib-slot numbers are assumed to be the same
1045                 String mxpProfileName = mpdrClientRestriction.get(0).getMuxpProfileName().get(0);
1046                 // From this muxponder-profile get the min-trib-slot and the max-trib-slot
1047                 LOG.info("{}: Muxp-profile used for trib information {}", nodeId, mxpProfileName);
1048                 // This provides the tribSlot information from muxProfile
1049                 List<OpucnTribSlotDef> minMaxOpucnTribSlots = getOpucnTribSlots(nodeId, mxpProfileName);
1050                 mpBldr.setMpdrRestrictions(
1051                     new MpdrRestrictionsBuilder()
1052                         .setMinTribSlot(minMaxOpucnTribSlots.get(0))
1053                         .setMaxTribSlot(minMaxOpucnTribSlots.get(1))
1054                         .build());
1055             }
1056             mpBldr.setSupportedInterfaceCapability(supportedIntf);
1057         }
1058         if (port.getAdministrativeState() != null) {
1059             mpBldr.setPortAdminState(port.getAdministrativeState().name());
1060         }
1061         if (port.getOperationalState() != null) {
1062             mpBldr.setPortOperState(port.getOperationalState().name());
1063         }
1064         return mpBldr.build();
1065     }
1066
1067     private ArrayList<OpucnTribSlotDef> getOpucnTribSlots(String deviceId, String mxpProfileName) {
1068         ArrayList<OpucnTribSlotDef> minMaxOpucnTribSlots = new ArrayList<>(2);
1069
1070         LOG.info("{} : Getting Min/Max Trib-slots from {}", deviceId, mxpProfileName);
1071         InstanceIdentifier<MuxpProfile> deviceIID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1072             .child(MuxpProfile.class, new MuxpProfileKey(mxpProfileName));
1073
1074         Optional<MuxpProfile> muxpProfileObject = this.deviceTransactionManager.getDataFromDevice(deviceId,
1075             LogicalDatastoreType.OPERATIONAL, deviceIID,
1076             Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1077
1078         List<OpucnTribSlotDef> ntwHoOduOpucnTribSlots = muxpProfileObject.get().getNetworkHoOduOpucnTribSlots();
1079         // Sort the tib-slots in ascending order and pick min and max
1080         List<OpucnTribSlotDef> sortedNtwHoOduOpucnTribSlots = ntwHoOduOpucnTribSlots.stream().sorted(
1081             Comparator.comparingDouble(x -> Double.parseDouble(
1082                 x.getValue().substring(x.getValue().lastIndexOf('.') + 1))))
1083             .collect(Collectors.toList());
1084         minMaxOpucnTribSlots.add(sortedNtwHoOduOpucnTribSlots.get(0));
1085         minMaxOpucnTribSlots.add(sortedNtwHoOduOpucnTribSlots.get(sortedNtwHoOduOpucnTribSlots.size() - 1));
1086         LOG.debug("Min, Max trib slot list {}", minMaxOpucnTribSlots);
1087         return minMaxOpucnTribSlots;
1088     }
1089
1090     private Ports getPort2(Ports port, String nodeId, String circuitPackName, StringBuilder circuitPackName2,
1091             //circuitPackName2 will be updated by reference contrary to circuitPackName
1092             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap) {
1093         if (!checkPartnerPortNotNull(port)) {
1094             LOG.warn("{} : port {} on {} - Error in the configuration ", nodeId, port.getPortName(), circuitPackName);
1095             return null;
1096         }
1097         if (lcpMap.containsKey(circuitPackName + '+' + port.getPortName())) {
1098             return null;
1099         }
1100         Optional<CircuitPacks> cpOpt = circuitPackList.stream()
1101             .filter(
1102                 cP -> cP.getCircuitPackName().equals(port.getPartnerPort().getCircuitPackName()))
1103             .findFirst();
1104         if (!cpOpt.isPresent()) {
1105             LOG.error("{} : Error fetching circuit-pack {}", nodeId, port.getPartnerPort().getCircuitPackName());
1106             return null;
1107         }
1108         Optional<Ports> poOpt = cpOpt.get().nonnullPorts().values().stream()
1109             .filter(p -> p.getPortName().equals(port.getPartnerPort().getPortName()))
1110             .findFirst();
1111         if (!poOpt.isPresent()) {
1112             LOG.error("{} : Error fetching port {} on {}",
1113                 nodeId, port.getPartnerPort().getPortName(), port.getPartnerPort().getCircuitPackName());
1114             return null;
1115         }
1116         Ports port2 = poOpt.get();
1117         circuitPackName2.append(cpOpt.get().getCircuitPackName());
1118         if (!checkPartnerPort(circuitPackName, port, port2)) {
1119             LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1120                 nodeId, port2.getPortName(), circuitPackName2, port.getPortName(), circuitPackName);
1121             return null;
1122         }
1123         return port2;
1124     }
1125
1126
1127     private void putXpdrLcpsInMaps(int line, String nodeId,
1128             Integer xponderNb, XpdrNodeTypes xponderType,
1129             String circuitPackName, String circuitPackName2, Ports port, Ports port2,
1130             Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1131         String lcp1 =
1132             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
1133         if (lcpMap.containsKey(lcp1)) {
1134             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp1 + " - already exist");
1135             return;
1136         }
1137         String lcp2 =
1138             PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line + 1, StringConstants.NETWORK_TOKEN);
1139         if (lcpMap.containsKey(lcp2)) {
1140             LOG.warn(PortMappingUtils.UNABLE_MAPPING_LOGMSG, nodeId, "add", lcp2 + " - already exist");
1141             return;
1142         }
1143         lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp1);
1144         lcpMap.put(circuitPackName2 + '+' + port2.getPortName(), lcp2);
1145         mappingMap.put(lcp1,
1146                 createXpdrMappingObject(nodeId, port, circuitPackName, lcp1, lcp2, null, null, xponderType));
1147         mappingMap.put(lcp2,
1148                 createXpdrMappingObject(nodeId, port2, circuitPackName2, lcp2, lcp1, null, null, xponderType));
1149         return;
1150     }
1151
1152     private int[] fillXpdrLcpsMaps(int line, int client, String nodeId,
1153             Integer xponderNb, XpdrNodeTypes xponderType,
1154             String circuitPackName,  Ports port,
1155             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1156
1157         if (port.getPortQual() == null) {
1158             LOG.warn("{} : port {} on {} - PortQual was not found", nodeId, port.getPortName(), circuitPackName);
1159             return new int[] {line, client};
1160         }
1161
1162         switch (port.getPortQual()) {
1163
1164             case XpdrClient:
1165             case SwitchClient:
1166                 String lcp0 =
1167                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, client, StringConstants.CLIENT_TOKEN);
1168                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp0);
1169                 mappingMap.put(lcp0,
1170                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp0, null, null, null, null));
1171                 client++;
1172                 break;
1173
1174             case XpdrNetwork:
1175             case SwitchNetwork:
1176                 line = fillXpdrNetworkLcpsMaps(line, nodeId,
1177                         xponderNb, xponderType,
1178                         circuitPackName,  port,
1179                         circuitPackList,  lcpMap, mappingMap);
1180                 break;
1181
1182             default:
1183                 LOG.error("{} : port {} on {} - unsupported PortQual {}",
1184                     nodeId, port.getPortName(), circuitPackName, port.getPortQual());
1185         }
1186         return new int[] {line, client};
1187     }
1188
1189     private int fillXpdrNetworkLcpsMaps(int line, String nodeId,
1190             Integer xponderNb, XpdrNodeTypes xponderType,
1191             String circuitPackName,  Ports port,
1192             List<CircuitPacks> circuitPackList, Map<String, String> lcpMap, Map<String, Mapping> mappingMap) {
1193
1194         switch (port.getPortDirection()) {
1195
1196             case Bidirectional:
1197                 String lcp =
1198                     PortMappingUtils.createXpdrLogicalConnectionPort(xponderNb, line, StringConstants.NETWORK_TOKEN);
1199                 lcpMap.put(circuitPackName + '+' + port.getPortName(), lcp);
1200                 mappingMap.put(lcp,
1201                     createXpdrMappingObject(nodeId, port, circuitPackName, lcp, null, null, null, xponderType));
1202                 line++;
1203                 break;
1204
1205             case Rx:
1206             case Tx:
1207                 StringBuilder circuitPackName2 = new StringBuilder();
1208                 Ports port2 = getPort2(port, nodeId, circuitPackName, circuitPackName2,
1209                         circuitPackList, lcpMap);
1210
1211                 if (port2 == null) {
1212                      //key already present or an error occured and was logged
1213                     return line;
1214                 }
1215
1216                 putXpdrLcpsInMaps(line, nodeId, xponderNb, xponderType,
1217                         circuitPackName, circuitPackName2.toString(), port, port2,
1218                         lcpMap, mappingMap);
1219                 line += 2;
1220                 break;
1221
1222             default:
1223                 LOG.error(PortMappingUtils.UNSUPPORTED_DIR_LOGMSG,
1224                      nodeId, port.getPortName(), circuitPackName, port.getPortDirection());
1225         }
1226
1227         return line;
1228     }
1229
1230     private boolean createMcCapabilitiesList(String nodeId, Info deviceInfo,
1231             Map<McCapabilitiesKey, McCapabilities> mcCapabilitiesMap) {
1232         if (deviceInfo.getNodeType() == NodeTypes.Rdm) {
1233             Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1234             List<SharedRiskGroup> srgs = getSrgs(nodeId, deviceInfo);
1235             mcCapabilitiesMap.putAll(getMcCapabilities(degrees, srgs, deviceInfo, nodeId));
1236         } else if ((deviceInfo.getNodeType() == NodeTypes.Xpdr)) {
1237             Map<McCapabilityProfileKey, McCapabilityProfile> mcProfileXpdr = getMcCapabilityProfiles(nodeId,
1238                 deviceInfo);
1239             if (mcProfileXpdr.size() > 1) {
1240                 LOG.warn("Re-check the mc-capability-profiles for XPDR port-mapping");
1241             }
1242             // Typically for a XPDR there will be only one mc-capability-profile
1243             for (Map.Entry<McCapabilityProfileKey, McCapabilityProfile> mcCapProfile : mcProfileXpdr.entrySet()) {
1244                 String mcNodeName = "XPDR" + "-" + "mcprofile";
1245                 McCapabilitiesBuilder mcCapabilitiesBuilder = new McCapabilitiesBuilder()
1246                     .withKey(new McCapabilitiesKey(mcNodeName))
1247                     .setMcNodeName(mcNodeName);
1248                 mcCapabilitiesBuilder
1249                     .setCenterFreqGranularity(mcCapProfile.getValue().getCenterFreqGranularity())
1250                     .setSlotWidthGranularity(mcCapProfile.getValue().getSlotWidthGranularity());
1251                 // Build and add to the Map
1252                 mcCapabilitiesMap.put(mcCapabilitiesBuilder.key(), mcCapabilitiesBuilder.build());
1253                 LOG.info("Finished building mc-capability profile for XPDR {}", nodeId);
1254                 // Since we only have one mc-profile for XPDR, we can break the for-loop
1255                 break;
1256             }
1257
1258         }
1259         return true;
1260     }
1261
1262     private boolean createTtpPortMapping(String nodeId, Info deviceInfo, List<Mapping> portMapList) {
1263         // Creating mapping data for degree TTP's
1264         Map<Integer, Degree> degrees = getDegreesMap(nodeId, deviceInfo);
1265         Map<String, String> interfaceList = getEthInterfaceList(nodeId);
1266         List<CpToDegree> cpToDegreeList = getCpToDegreeList(degrees, interfaceList);
1267         LOG.info("{} : Map looks like this {}", nodeId, interfaceList);
1268         postPortMapping(nodeId, null, null, cpToDegreeList, null, null);
1269
1270         Map<Integer, List<ConnectionPorts>> connectionPortMap = getPerDegreePorts(nodeId, deviceInfo);
1271         for (Entry<Integer, List<ConnectionPorts>> cpMapEntry : connectionPortMap.entrySet()) {
1272             switch (connectionPortMap.get(cpMapEntry.getKey()).size()) {
1273                 case 1:
1274                     // port is bidirectional
1275                     String cpName = connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName();
1276                     InstanceIdentifier<Ports> portID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1277                         .child(CircuitPacks.class, new CircuitPacksKey(cpName))
1278                         .child(Ports.class,
1279                                 new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName()));
1280                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG,
1281                         nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cpName);
1282                     Optional<Ports> portObject = this.deviceTransactionManager.getDataFromDevice(nodeId,
1283                         LogicalDatastoreType.OPERATIONAL, portID, Timeouts.DEVICE_READ_TIMEOUT,
1284                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1285                     if (!portObject.isPresent()) {
1286                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
1287                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cpName);
1288                         return false;
1289                     }
1290                     Ports port = portObject.get();
1291                     if (port.getPortQual() == null) {
1292                         continue;
1293                     }
1294                     if (PortQual.RoadmExternal.getIntValue() != port.getPortQual().getIntValue()) {
1295                         LOG.error(PortMappingUtils.CANNOT_CREATE_LCP_LOGMSG + PortMappingUtils.PORTQUAL_ERROR_LOGMSG,
1296                             nodeId, port.getPortName(), cpName);
1297                         continue;
1298                     }
1299                     if (Direction.Bidirectional.getIntValue() != port.getPortDirection().getIntValue()) {
1300                         LOG.error(PortMappingUtils.CANNOT_CREATE_LCP_LOGMSG + PortMappingUtils.PORTDIR_ERROR_LOGMSG,
1301                             nodeId, port.getPortName(), cpName);
1302                         continue;
1303                     }
1304
1305                     String logicalConnectionPoint =
1306                             PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(), "TXRX");
1307                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1308                         nodeId, port.getPortName(), cpName, logicalConnectionPoint);
1309                     portMapList.add(createMappingObject(nodeId, port, cpName, logicalConnectionPoint));
1310                     break;
1311                 case 2:
1312                     // ports are unidirectionals
1313                     String cp1Name = connectionPortMap.get(cpMapEntry.getKey()).get(0).getCircuitPackName();
1314                     String cp2Name = connectionPortMap.get(cpMapEntry.getKey()).get(1).getCircuitPackName();
1315                     InstanceIdentifier<Ports> port1ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1316                         .child(CircuitPacks.class, new CircuitPacksKey(cp1Name))
1317                         .child(Ports.class,
1318                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName()));
1319                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG,
1320                         nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cp1Name);
1321                     Optional<Ports> port1Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1322                         LogicalDatastoreType.OPERATIONAL, port1ID, Timeouts.DEVICE_READ_TIMEOUT,
1323                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1324                     InstanceIdentifier<Ports> port2ID = InstanceIdentifier.create(OrgOpenroadmDevice.class)
1325                         .child(CircuitPacks.class, new CircuitPacksKey(cp2Name))
1326                         .child(Ports.class,
1327                             new PortsKey(connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName()));
1328                     LOG.debug(PortMappingUtils.FETCH_CONNECTIONPORT_LOGMSG,
1329                         nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName(), cp2Name);
1330                     Optional<Ports> port2Object = this.deviceTransactionManager.getDataFromDevice(nodeId,
1331                         LogicalDatastoreType.OPERATIONAL, port2ID, Timeouts.DEVICE_READ_TIMEOUT,
1332                         Timeouts.DEVICE_READ_TIMEOUT_UNIT);
1333                     if (!port1Object.isPresent() || !port2Object.isPresent()) {
1334                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
1335                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(0).getPortName(), cp1Name);
1336                         return false;
1337                     }
1338                     if (!port2Object.isPresent()) {
1339                         LOG.error(PortMappingUtils.NO_PORT_ON_CP_LOGMSG,
1340                             nodeId, connectionPortMap.get(cpMapEntry.getKey()).get(1).getPortName(), cp2Name);
1341                         return false;
1342                     }
1343
1344                     Ports port1 = port1Object.get();
1345                     Ports port2 = port2Object.get();
1346                     if (port1.getPortQual() == null || port2.getPortQual() == null) {
1347                         continue;
1348                     }
1349                     if (PortQual.RoadmExternal.getIntValue() != port1.getPortQual().getIntValue()) {
1350                         LOG.error(PortMappingUtils.CANNOT_CREATE_LCP_LOGMSG + PortMappingUtils.PORTQUAL_ERROR_LOGMSG,
1351                             nodeId, port1.getPortName(), cp1Name);
1352                         continue;
1353                     }
1354                     if (PortQual.RoadmExternal.getIntValue() != port2.getPortQual().getIntValue()) {
1355                         LOG.error(PortMappingUtils.CANNOT_CREATE_LCP_LOGMSG + PortMappingUtils.PORTQUAL_ERROR_LOGMSG,
1356                             nodeId, port2.getPortName(), cp2Name);
1357                         continue;
1358                     }
1359
1360                     if (!checkPartnerPort(cp1Name, port1, port2)) {
1361                         LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1362                             nodeId, port2.getPortName(), cp2Name, port1.getPortName(), cp1Name);
1363                         continue;
1364                     }
1365                     // Directions checks are the same for cp1 and cp2, no need to check them twice.
1366                     if (!checkPartnerPortNoDir(cp2Name, port2, port1)) {
1367                         LOG.error(PortMappingUtils.NOT_CORRECT_PARTNERPORT_LOGMSG,
1368                             nodeId, port1.getPortName(), cp1Name, port2.getPortName(), cp2Name);
1369                         continue;
1370                     }
1371
1372                     String logicalConnectionPoint1 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
1373                             port1.getPortDirection().getName().toUpperCase(Locale.getDefault()));
1374                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1375                         nodeId, port1.getPortName(), cp1Name, logicalConnectionPoint1);
1376                     portMapList.add(createMappingObject(nodeId, port1, cp1Name, logicalConnectionPoint1));
1377                     String logicalConnectionPoint2 = PortMappingUtils.degreeTtpNodeName(cpMapEntry.getKey().toString(),
1378                             port2.getPortDirection().getName().toUpperCase(Locale.getDefault()));
1379                     LOG.info(PortMappingUtils.ASSOCIATED_LCP_LOGMSG,
1380                         nodeId, port2.getPortName(), cp2Name, logicalConnectionPoint2);
1381                     portMapList.add(createMappingObject(nodeId, port2, cp2Name, logicalConnectionPoint2));
1382                     break;
1383                 default:
1384                     LOG.error("{} : Number of connection port for DEG{} is incorrect", nodeId, cpMapEntry.getKey());
1385                     continue;
1386             }
1387         }
1388         return true;
1389     }
1390
1391     private NodeInfo createNodeInfo(Info deviceInfo) {
1392
1393         if (deviceInfo.getNodeType() == null) {
1394             // TODO make mandatory in yang
1395             LOG.error("Node type field is missing");
1396             return null;
1397         }
1398
1399         NodeInfoBuilder nodeInfoBldr = new NodeInfoBuilder()
1400                 .setOpenroadmVersion(OpenroadmNodeVersion._71)
1401                 .setNodeType(deviceInfo.getNodeType());
1402         // TODO: 221 versions expects an int value - need to check whether it is bug or an evolution here
1403         if (deviceInfo.getClli() != null && !deviceInfo.getClli().isEmpty()) {
1404             nodeInfoBldr.setNodeClli(deviceInfo.getClli());
1405         } else {
1406             nodeInfoBldr.setNodeClli("defaultCLLI");
1407         }
1408         if (deviceInfo.getModel() != null) {
1409             nodeInfoBldr.setNodeModel(deviceInfo.getModel());
1410         }
1411         if (deviceInfo.getVendor() != null) {
1412             nodeInfoBldr.setNodeVendor(deviceInfo.getVendor());
1413         }
1414         if (deviceInfo.getIpAddress() != null) {
1415             nodeInfoBldr.setNodeIpAddress(deviceInfo.getIpAddress());
1416         }
1417
1418         return nodeInfoBldr.build();
1419     }
1420
1421     private String getLcpFromCpAndPort(Map<MappingKey, Mapping> mappings, String cpName, String portName) {
1422         for (Mapping mapping : mappings.values()) {
1423             if (cpName.equals(mapping.getSupportingCircuitPackName())
1424                 && portName.equals(mapping.getSupportingPort())) {
1425                 return mapping.getLogicalConnectionPoint();
1426             }
1427         }
1428         return null;
1429     }
1430
1431 }