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